Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1965955
  • 博文数量: 356
  • 博客积分: 8284
  • 博客等级: 中将
  • 技术积分: 4580
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-15 20:25
个人简介

天行健,君子以自强不息

文章分类

全部博文(356)

文章存档

2018年(1)

2016年(4)

2015年(13)

2014年(14)

2013年(2)

2012年(25)

2011年(43)

2010年(65)

2009年(189)

分类: C/C++

2014-12-19 14:48:03

1、启动IIC驱动
nano  /etc/modules
添加i2c-dev ,如下:


取消对IIC驱动的黑名单
nano /etc/modprobe.d/raspi-blacklist.conf


3、重启
4、安装i2cdetect
apt-get install i2c-tools
5、将BH1750连接到树莓派

6、i2cdetect -y -a  1
效果如下:

7、编写程序
cd /home/pi
nano iic_bh1750.c

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <linux/i2c-dev.h>
  4. #include <errno.h>
  5. #define I2C_ADDR 0x5c
  6. int main(void)
  7. {
  8.         int fd;
  9.         char buf[3];
  10.         char val,value;
  11.         float flight;
  12.         fd=open("/dev/i2c-1",O_RDWR);
  13.         if(fd<0)
  14.         {
  15.                 printf("err open file:%s\r\n",strerror(errno)); return 1;
  16.         }
  17.         if(ioctl( fd,I2C_SLAVE,I2C_ADDR)<0 )
  18.         {
  19.                 printf("ioctl error : %s\r\n",strerror(errno));return 1;
  20.         }
  21.         val=0x01;
  22.         if(write(fd,&val,1)<0)
  23.         {
  24.                 printf("write 0x01 err\r\n");
  25.         }
  26.         val=0x10;
  27.         if(write(fd,&val,1)<0)
  28.         {
  29.                 printf("write 0x10 err\r\n");
  30.         }
  31.         while(1)

  32.         {
  33.                 if(read(fd,&buf,3))
  34.                 {
  35.                         flight=(buf[0]*256+buf[1])/1.2;
  36.                         printf("light is %6.3f\r\n",flight);
  37.                 }
  38.                 else
  39.                 {
  40.                         printf("read light error\r\n");
  41.                 }
  42.                 usleep(100000);//sleep 0.1s
  43.         }
  44. }
编译:
gcc  -o  bh1750  iic_bh1750.c
执行:
./bh1750
效果如下:


阅读(11089) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

jineklaalkenij2015-01-29 21:25:03

绝赞了,之前也试过用write/read,没成功,后来决定ioctl写,现在发现一直是地址弄错了,感谢博主分享啊,我的目前遇到段错误,应该也很快解决了