新闻| 论坛| 博客| 在线研讨会
Linux 下测试 I2C 通讯
电子禅石| 2024-01-28 17:38:45 阅读:17530 发布文章

#include  #include  #include  #include  #include  #include  #include  #include  #define I2C_DEV "/dev/i2c-1" #define CHIP_ADDR 0xD6 int main(int argc, char *argv[]) { int i = 0, fd = -1; int bits = 0; int chipAddr = 0xd6; unsigned char buf[1]={0x0f}; unsigned char recbuf[8]; if(argc <= 1) { printf("Usage: i2ctest device_addr device_name bitsel \n"); return -1; } chipAddr = atoi(argv[1]); printf("Device addr: 0x%x \n", chipAddr); printf("Device name: %s \n", argv[2]); bits = atoi(argv[3]); if(bits == 0 || bits == 1) printf("Bit select: %s \n", bits == 0? "7 bit": "10 bit" ); else { printf("bits error \n"); return -1; } fd = open(argv[2], O_RDWR);// I2C_DEV /dev/i2c-0 if(fd < 0) { printf("####i2c test device open failed####\n"); return -1; } // I2C_TENBIT:对应的arg取值为0:从机地址为7 bit;对应的arg取值为1:从机地址为10bit ioctl(fd, I2C_TENBIT, bits); //not 10bit ioctl(fd, I2C_SLAVE, chipAddr); //设置I2C从设备地址[6:0] write(fd,buf,1); /* 发送子地址0 */ usleep(200000); read(fd, recbuf, 8); printf("\nReceived data: "); for(i = 0; i < 8; i++) { printf("0x%02x ", recbuf[i]); } printf("\nEnd \n"); return 0; }

root@firefly:/usr/local#gcc test.c -oi2c-test
root@firefly:/usr/local# ./i2c-test 107 /dev/i2c-1 1
Device addr: 0x6b
Device name: /dev/i2c-1
Bit select: 10 bit

Received data: 0x69 0x00 0x00 0x04 0x00 0x00 0x00 0x00
End

*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

参与讨论
登录后参与讨论
属于自己的技术积累分享,成为嵌入式系统研发高手。
最近文章
签名类型
2024-04-29 16:28:59
cat 文件名
2024-04-29 15:05:34
推荐文章
最近访客