本实验是树莓派通过C语言和python读取光照传感器BH1750,获取当前环境光照的系数,环境越亮系数越高,并转换成百分比。BH1750FVI是一种用于两线式串行总线接口的数字型光强度传感器集成电路,利用本实验的这种集成电路可以根据收集的光线强度数据来调整液晶或者键盘背景灯的亮度。在笔者的应用就可以用于环境监测。
1、接线图
运行命令sudo i2cdetect -y 1 查看 地址为地址为0x23,说明成功连接到i2c传感器。
2、C语言 bh1750.c
#include <wiringPiI2C.h>
#include <stdio.h>
#include <sys/time.h>
#include <wiringPi.h>
int main (void)
{
int handle = wiringPiI2CSetup(0x23);
while(1)
{
wiringPiI2CWrite(handle, 0x21);
delay(1000);
int word = wiringPiI2CReadReg16(handle, 0x00);
int lux = ((word & 0xff00)>>8) | ((word & 0x00ff)<<8);
int percent = (100.0/65535.0)*lux;
printf("Current light: %d Lux (%d%%)\n", lux, percent);
}
return 0;
}
编译:gcc bh1750.c -o bh1750 -lwiringPi
运行:./bh1750
3、python语言 bh1750.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)
percent = int((100.0/65535.0)*res);
#print() res percent
print res,percent
#result="光照强度: "+str(res)+"lx"
#return result
while True:
getIlluminance()
time.sleep(2)
运行:python bh1750.py
网友评论