一、前期准備
1.環境要求
GY30模塊(BH1750FVI傳感器),樹莓派系統,python-smbus,iic開啟
2.取消對IIC驅動的黑名單
nano /etc/modprobe.d/raspi-blacklist.conf

3.啟動IIC驅動
nano /etc/modules
添加i2c-dev ,如下:

4.重啟
5.安裝python-smbus
這個安裝會附帶安裝i2c-tools,省的單獨安裝了
sudo apt-get install python-smbus
6.將BH1750連接到樹莓派
| GY-30 | 樹莓派 | |
|---|---|---|
| VCC | —— | 1 |
| GND | —— | 6 |
| SDA | —— | 3 |
| SCL | —— | 5 |
| ADDR | —— | 不接 |
二、連接測試
sudo i2cdetect -y 1

問題分析:
pi@raspberrypi:~$ i2cdetect -y 1 Error: Could not open file dev/i2c-1' or `/dev/i2c/1': No such file or directory
無設備目錄
解決方法:
方法一:raspi-config,進入Interfacing Options高級設置,將spi與i2c設置為enable,reboot;
方法二:blacklist里面有i2c,所以i2cdetect檢測不到dev里面的設備,現在把blacklist里面的i2c模塊注釋掉就可以檢測到i2cdev。
三、光照強度測量
1.創建iic_bh1750.c
#include <stdio.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <errno.h>
#define I2C_ADDR 0x23
int main(void)
{
int fd;
char buf[3];
char val,value;
float flight;
fd=open("/dev/i2c-1",O_RDWR);
if(fd<0)
{
printf("打開文件錯誤:%s\r\n",strerror(errno)); return 1;
}
if(ioctl( fd,I2C_SLAVE,I2C_ADDR)<0 )
{
printf("ioctl 錯誤 : %s\r\n",strerror(errno));return 1;
}
val=0x01;
if(write(fd,&val,1)<0)
{
printf("上電失敗\r\n");
}
val=0x11;
if(write(fd,&val,1)<0)
{
printf("開啟高分辨率模式2\r\n");
}
usleep(200000);
if(read(fd,&buf,3)){
flight=(buf[0]*256+buf[1])*0.5/1.2;
printf("光照度: %6.2flx\r\n",flight);
}
else{
printf("讀取錯誤\r\n");
}
}
編譯:
gcc -o bh1750 iic_bh1750.c
執行:
./bh1750
2.與python相比
創建illuminance.py
cd /home/pi/helloworld/illuminance vim illuminance.py
illuminance.py
#!/usr/bin/env python
# encoding: utf-8
import smbus
import time
#BH1750地址
__DEV_ADDR=0x23
#控制字
__CMD_PWR_OFF=0x00 #關機
__CMD_PWR_ON=0x01 #開機
__CMD_RESET=0x07 #重置
__CMD_CHRES=0x10 #持續高分辨率檢測
__CMD_CHRES2=0x11 #持續高分辨率模式2檢測
__CMD_CLHRES=0x13 #持續低分辨率檢測
__CMD_THRES=0x20 #一次高分辨率
__CMD_THRES2=0x21 #一次高分辨率模式2
__CMD_TLRES=0x23 #一次分辨率
__CMD_SEN100H=0x42 #靈敏度100%,高位
__CMD_SEN100L=0X65 #靈敏度100%,低位
__CMD_SEN50H=0x44 #50%
__CMD_SEN50L=0x6A #50%
__CMD_SEN200H=0x41 #200%
__CMD_SEN200L=0x73 #200%
bus=smbus.SMBus(1)
bus.write_byte(__DEV_ADDR,__CMD_PWR_ON)
bus.write_byte(__DEV_ADDR,__CMD_RESET)
bus.write_byte(__DEV_ADDR,__CMD_SEN100H)
bus.write_byte(__DEV_ADDR,__CMD_SEN100L)
bus.write_byte(__DEV_ADDR,__CMD_PWR_OFF)
def getIlluminance():
bus.write_byte(__DEV_ADDR,__CMD_PWR_ON)
bus.write_byte(__DEV_ADDR,__CMD_THRES2)
time.sleep(0.2)
res=bus.read_word_data(__DEV_ADDR,0)
#read_word_data
res=((res>>8)&0xff)|(res<<8)&0xff00
res=round(res/(2*1.2),2)
result="光照強度: "+str(res)+"lx"
return result
測試結果
重啟uwsgi服務
sudo systemctl restart emperor.uwsgi.service
測試
在樹莓派瀏覽器輸入 http://127.0.0.1/illuminance 或者在電腦瀏覽器輸入 http://樹莓派IP/illuminance

