1,、啟動(dòng)IIC驅(qū)動(dòng)
nano /etc/modules
添加i2c-dev ,如下:
取消對(duì)IIC驅(qū)動(dòng)的黑名單
nano /etc/modprobe.d/raspi-blacklist.conf
3,、重啟
4,、安裝i2cdetect
apt-get install i2c-tools
5、將BH1750連接到樹(shù)莓派
6,、i2cdetect -y -a 1
效果如下:
7,、編寫(xiě)程序
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
執(zhí)行:
./bh1750
效果如下:
|