-
Notifications
You must be signed in to change notification settings - Fork 0
/
libi2c-com.c
executable file
·78 lines (62 loc) · 1.49 KB
/
libi2c-com.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
#include <stdio.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
static int fd = -1;
int OpenI2C(int bus, int extra_open_flags, int *err)
{
char fName[16];
snprintf(fName,16,"/dev/i2c-%d",bus);
if (-1 == (fd = open(fName,O_RDWR|extra_open_flags)))
{
*err = errno;
return -1;
}
return 0;
}
int CloseI2C(int *err)
{
if (-1 == close(fd))
{
*err = errno;
return -1;
}
return 0;
}
int WriteBytes(int address, unsigned char bytes[], int *err)
{
struct i2c_rdwr_ioctl_data ioctl_arg;
struct i2c_msg messages[1];
messages[0].addr = address;
messages[0].flags = 0;
messages[0].len = sizeof(unsigned char) * bytes[0]; // bytes is a counted array
messages[0].buf = bytes + 1; // ignore the first element
ioctl_arg.msgs = messages;
ioctl_arg.nmsgs = 1;
if(ioctl(fd, I2C_RDWR, &ioctl_arg) < 0)
{
*err = errno;
return -1;
}
return 0;
}
int ReadBytes(int address, unsigned char bytes[256], int *err)
{
struct i2c_rdwr_ioctl_data ioctl_arg;
struct i2c_msg messages[1];
messages[0].addr = address;
messages[0].flags = I2C_M_RD;
messages[0].len = sizeof(unsigned char) * bytes[0]; // bytes is a counted array
messages[0].buf = bytes; // include first element as we're receiving data
ioctl_arg.msgs = messages;
ioctl_arg.nmsgs = 1;
if(ioctl(fd, I2C_RDWR, &ioctl_arg) < 0)
{
*err = errno;
return -1;
}
return 0;
}