-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrpii2c.c
120 lines (106 loc) · 2.25 KB
/
rpii2c.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* rpii2c.c
*
* Created by Tobias Gall <[email protected]>
* Based on Adafruit's python code for CharLCDPlate
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*
*/
#include "rpii2c.h"
int fd; // FileDiscriptor
/*
*
* name: rpiI2cSetup
* @param __u8 addr (Address of I2C Device), __u8 busnum
* @return void
*
* Sets up an I2C Device
*
*/
void rpiI2cSetup(__u8 addr, __u8 busnum)
{
char *fileName;
if(busnum == 0)
fileName = "/dev/i2c-0";
else if(busnum == 1)
fileName = "/dev/i2c-1";
else
exit(1);
// Open File for READ/WRITE
if((fd = open(fileName, O_RDWR)) < 0)
exit(1);
// Sets Device as I2C Slave
if(ioctl(fd, I2C_SLAVE, addr) < 0) {
close(fd);
exit(1);
}
}
/*
*
* name: rpiI2cWrite
* @param __u8 reg (Register), __u8 value (1 Byte Value)
* @return void
*
* Writes Value to I2C Device on Register reg
*
*/
void rpiI2cWrite(__u8 reg, __u8 value)
{
if (i2c_smbus_write_byte_data(fd, reg, value) < 0) {
close(fd);
exit(1);
}
}
/*
*
* name: rpiI2cRead8
* @param __u8 reg (Register)
* @return __u8 (1 Byte Data)
*
* Reads 1 Byte Data from I2C Device on Register reg
*
*/
__u8 rpiI2cRead8(__u8 reg)
{
__u8 res = i2c_smbus_read_byte_data(fd, reg);
return res;
}
/*
*
* name: rpiI2cRead16
* @param __u8 reg (Register)
* @return __u16 (2 Byte Data)
*
*/
__u16 rpiI2cRead16(__u8 reg)
{
__u16 hi = i2c_smbus_read_byte_data(fd, reg);
__u16 res = (hi << 8) + i2c_smbus_read_byte_data(fd, reg+1);
return res;
}
/*
*
* name: rpiI2cClose
* @param void
* @return void
*
*/
void rpiI2cClose(void)
{
close(fd);
}