-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathlinux_i2c.c
68 lines (57 loc) · 1.04 KB
/
linux_i2c.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
#include <stdint.h>
#include <stdlib.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
static int file_i2c = 0;
uint8_t _i2c_init(int i2c, int dev_addr)
{
if (file_i2c == 0)
{
char filename[32];
sprintf(filename, "/dev/i2c-%d", i2c); // I2C bus number passed
file_i2c = open(filename, O_RDWR);
if (file_i2c < 0)
{
file_i2c = 0;
return 1;
}
if (ioctl(file_i2c, I2C_SLAVE, dev_addr) < 0) // set slave address
{
close(file_i2c);
file_i2c = 0;
return 1;
}
return 0;
}
// assume done init already
return 0;
}
uint8_t _i2c_close()
{
if (file_i2c != 0)
{
close(file_i2c);
file_i2c = 0;
return 0;
}
return 1;
}
uint8_t _i2c_write(uint8_t* ptr, int16_t len)
{
if (file_i2c == 0 || ptr == 0 || len <= 0)
return 1;
write(file_i2c, ptr, len);
return 0;
}
uint8_t _i2c_read(uint8_t *ptr, int16_t len)
{
if (file_i2c == 0 || ptr == 0 || len <= 0)
return 1;
read(file_i2c, ptr, len);
return 0;
}