-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux.c
More file actions
112 lines (86 loc) · 2.32 KB
/
linux.c
File metadata and controls
112 lines (86 loc) · 2.32 KB
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
#include <crossi2c/linux.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#define MIN(a,b) ((a)<(b) ? (a) : (b))
#define CROSSLOG_TAG "crossi2c"
#include <crosslog.h>
int crossi2c_linux_create(struct crossi2c_bus *bus, const char *path) {
int fd;
memset(bus, 0, sizeof(*bus));
fd = open(path, O_RDWR, 0);
if (fd < 0) {
CROSSLOG_ERRNO("open");
return -1;
}
bus->fd = fd;
return 0;
}
int crossi2c_destroy(struct crossi2c_bus *bus) {
close(bus->fd);
memset(bus, 0, sizeof(*bus));
return 0;
}
static int i2c_transfer(struct crossi2c_bus *bus, struct i2c_msg *msgs, size_t nmsgs) {
int rc;
struct i2c_rdwr_ioctl_data data = {
.msgs = msgs,
.nmsgs = nmsgs
};
rc = ioctl(bus->fd, I2C_RDWR, &data);
if (rc < 0 || (size_t)rc != nmsgs) {
CROSSLOG_ERRNO("ioctl");
return -1;
}
return 0;
}
int crossi2c_read(struct crossi2c_bus *bus, uint16_t addr, void *buf, size_t len) {
struct i2c_msg msg;
msg.addr = addr;
msg.flags = I2C_M_RD | I2C_M_STOP;
msg.len = len;
msg.buf = buf;
return i2c_transfer(bus, &msg, 1);
}
int crossi2c_write(struct crossi2c_bus *bus, uint16_t addr, const void *buf, size_t len) {
struct i2c_msg msg;
msg.addr = addr;
msg.flags = I2C_M_STOP;
msg.len = len;
msg.buf = (void*)buf;
return i2c_transfer(bus, &msg, 1);
}
int crossi2c_write_read(struct crossi2c_bus *bus, uint16_t addr,
const void *writebuf, size_t writelen,
void *readbuf, size_t readlen)
{
struct i2c_msg msg[2];
msg[0].addr = addr;
msg[0].flags = 0;
msg[0].len = writelen;
msg[0].buf = (void*)writebuf;
msg[1].addr = addr;
msg[1].flags = I2C_M_RD | I2C_M_STOP;
msg[1].len = readlen;
msg[1].buf = readbuf;
return i2c_transfer(bus, msg, 2);
}
int crossi2c_burst_write(struct crossi2c_bus *bus, uint16_t addr,
uint8_t reg, const void *buf, size_t len)
{
struct i2c_msg msg[2];
msg[0].addr = addr;
msg[0].flags = 0;
msg[0].len = 1;
msg[0].buf = ®
msg[1].addr = addr;
msg[1].flags = I2C_M_NOSTART | I2C_M_STOP;
msg[1].len = len;
msg[1].buf = (void*)buf;
return i2c_transfer(bus, msg, 2);
}