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
-
#include <stdio.h>
-
#include <fcntl.h>
-
#include <linux/i2c-dev.h>
-
#include <errno.h>
-
#define I2C_ADDR 0x5c
-
int main(void)
-
{
-
int fd;
-
char buf[3];
-
char val,value;
-
float flight;
-
fd=open("/dev/i2c-1",O_RDWR);
-
if(fd<0)
-
{
-
printf("err open file:%s\r\n",strerror(errno)); return 1;
-
}
-
if(ioctl( fd,I2C_SLAVE,I2C_ADDR)<0 )
-
{
-
printf("ioctl error : %s\r\n",strerror(errno));return 1;
-
}
-
val=0x01;
-
if(write(fd,&val,1)<0)
-
{
-
printf("write 0x01 err\r\n");
-
}
-
val=0x10;
-
if(write(fd,&val,1)<0)
-
{
-
printf("write 0x10 err\r\n");
-
}
-
while(1)
-
-
{
-
if(read(fd,&buf,3))
-
{
-
flight=(buf[0]*256+buf[1])/1.2;
-
printf("light is %6.3f\r\n",flight);
-
}
-
else
-
{
-
printf("read light error\r\n");
-
}
-
usleep(100000);//sleep 0.1s
-
}
-
}
编译:
gcc -o bh1750 iic_bh1750.c
执行:
./bh1750
效果如下:
阅读(865) | 评论(0) | 转发(0) |