Chinaunix首页 | 论坛 | 博客
  • 博客访问: 919781
  • 博文数量: 191
  • 博客积分: 3070
  • 博客等级: 中校
  • 技术积分: 1861
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-27 23:44
个人简介

Start Linux Leave Linux a while Back to Linux

文章分类

全部博文(191)

文章存档

2023年(18)

2022年(11)

2021年(8)

2020年(14)

2019年(7)

2018年(13)

2017年(16)

2016年(4)

2012年(2)

2011年(13)

2010年(26)

2009年(13)

2008年(27)

2007年(20)

我的朋友

分类: LINUX

2019-02-26 21:34:02

Code:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #include <sys/ioctl.h>
  7. #include <linux/i2c.h>
  8. #include <linux/i2c-dev.h>


  9. #define I2C_DEV "/dev/i2c-1"
  10. #define CHIP_ADDR 0xD6


  11. int main(int argc, char *argv[])
  12. {
  13.     int i = 0, fd = -1;
  14.     int bits = 0;
  15.     int chipAddr = 0xd6;
  16.     unsigned char buf[1]={0x0f};
  17.     unsigned char recbuf[8];


  18.     if(argc <= 1)
  19.     {
  20.         printf("Usage: i2ctest device_addr device_name bitsel \n");
  21.         return -1;
  22.     }


  23.     chipAddr = atoi(argv[1]);
  24.     printf("Device addr: 0x%x \n", chipAddr);


  25.     printf("Device name: %s \n", argv[2]);


  26.     bits = atoi(argv[3]);
  27.     if(bits == 0 || bits == 1)
  28.         printf("Bit select: %s \n", bits == 0? "7 bit": "10 bit" );
  29.     else
  30.     {
  31.         printf("bits error \n");
  32.         return -1;
  33.     }

  34.     fd = open(argv[2], O_RDWR);// I2C_DEV /dev/i2c-0
  35.     if(fd < 0)
  36.     {
  37.         printf("####i2c test device open failed####\n");
  38.         return -1;
  39.     }


  40.     // I2C_TENBIT:对应的arg取值为0:从机地址为7 bit;对应的arg取值为1:从机地址为10bit
  41.     ioctl(fd, I2C_TENBIT, bits); //not 10bit
  42.     ioctl(fd, I2C_SLAVE, chipAddr); //设置I2C从设备地址[6:0]


  43.     write(fd,buf,1); /* 发送子地址0 */
  44.     usleep(200000);
  45.     read(fd, recbuf, 8);


  46.     printf("\nReceived data: ");
  47.     for(i = 0; i < 8; i++)
  48.     {
  49.         printf("0x%02x ", recbuf[i]);
  50.     }
  51.     printf("\nEnd \n");
  52.     return 0;
  53. }

root@firefly:/usr/local# gcc test.c -o i2c-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
阅读(6435) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~