Linux应用层I2C操作

背景:

项目需求,需检测是否有camera sensor(CHIP_ADDR:0x6C>>1),
通过I2C读取sensor的CHIP ID(CHIP_ID_H:0x300A, CHIP_ID_L:0x300B)为0x27 0x70

应用层I2C操作:

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
    unsigned char rddata[2]={0};
unsigned char rdaddr0[2] = {0x30, 0x0A}; //CHIP_ID_H 0x27
unsigned char rdaddr1[2] = {0x30, 0x0B}; //CHIP_ID_L 0x70
int fd =open(CHIP, O_RDWR);
if (fd< 0) {
printf("open"CHIP"failed\n");
return -1;
}
#if 0 //方式一
if (ioctl(fd, I2C_SLAVE_FORCE, CHIP_ADDR) < 0) {
/* 设置芯片地址 */
printf("oictl:setslave address failed\n");
close(fd);
return 0;
}
struct i2c_msg msg;

printf("writeaddress return: %d\n",write(fd, rdaddr0, 2)); /* 读取寄存器地址 */
printf("readdata return:%d\n", read(fd, &rddata[1], 1));
printf("writeaddress return: %d\n",write(fd, rdaddr1, 2)); // 读取寄存器地址
printf("readdata return:%d\n", read(fd, &rddata[0], 1));

#endif
#if 1 //方式二
struct i2c_msg msgs[2];
struct i2c_rdwr_ioctl_data ioctl_data;

msgs[0].addr= CHIP_ADDR;
msgs[0].flags = 0;//write
msgs[0].len= 2;
msgs[0].buf= rdaddr0;
msgs[1].addr= CHIP_ADDR;
msgs[1].flags|= I2C_M_RD;
msgs[1].len= 1;
msgs[1].buf= &rddata[1];
ioctl_data.nmsgs= 2;
ioctl_data.msgs= msgs;
printf("ioctlwrite address, return :%d\n", ioctl(fd, I2C_RDWR, &ioctl_data));

msgs[0].buf= rdaddr1;
msgs[1].buf= &rddata[0];
printf("ioctlwrite address, return :%d\n", ioctl(fd, I2C_RDWR, &ioctl_data));

#endif
printf("rddata:%02x %02x\n", rddata[1], rddata[0]);
close(fd);
if((rddata[1]==0x27)&&(rddata[0]==0x70))
{
return 1;
}

return 0;