Linux应用层I2C操作
背景:
项目需求,需检测是否有camera sensor(CHIP_ADDR:0x6C>>1),
通过I2C读取sensor的CHIP ID(CHIP_ID_H:0x300A, CHIP_ID_L:0x300B)为0x27 0x70
应用层I2C操作:
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;
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 DD'Notes!
评论