RaspberryPi-Sensor-Board - emakefun文档中心 (test-doc-zh-cn.readthedocs.io)
扩展板MCU I2C地址为0x04,寄存地址说明如下:
0x10 ~ 0x17: 读取ADC原始数据
0x20 ~ 0x27: 读取输入电压
0x30 ~ 0x37: 读取输入电压与输出电压的比 输入电压/输出电压
众所周知,Raspberry Pi中没有ADC,因此不能直接读取传感器的模拟值。在扩展板内置的MCU 的帮助下可以读取10位ADC这就意味着可以在树莓派上使用模拟传感器,且一共有8个可用的接口。
模拟传感器将模拟电压输入10位模数转换器。模数转换器将模拟数据转换成数字数据后,通过I2C将数字数据输入到树莓派中。
在终端输入“sudo i2cdetect -y 1”命令即可扫描接在I2C总线上的所有I2C设备,并打印出该设备的I2C总线地址(这里使用的是PCF8591)0x48
import time
import RPi.GPIO as GPIO
import smbus
GPIO.setmode(GPIO.BCM)
address=0x48
delta=20
time_list=[0,0,0,0]
threshold=[0,0,0,0]
basic_value_1=[]
basic_value_2=[]
basic_value_3=[]
basic_value_4=[]
bus=smbus.SMBus(1)
def loop_print():
flag1=0
flag2=0
flag3=0
flag4=0
while True:
bus.write_byte(address,0x40)
bus.write_byte(address,0x41)
bus.write_byte(address,0x42)
bus.write_byte(address,0x43)
sound1=bus.read_byte_data(address,0x40)
sound2=bus.read_byte_data(address,0x41)
sound3=bus.read_byte_data(address,0x42)
sound4=bus.read_byte_data(address,0x43)
if sound1:
print("the NO.1 power of the sound is %lf"%sound1)
if len(basic_value_1)<=10:
basic_value_1.append(sound1)
if len(basic_value_1)==10:
value=0
for i in range(10):
value+=basic_value_1[i]
threshold[0]=(value/10)+delta
if 0 not in threshold:
if sound1>threshold[0] and flag1==0:
time_list[0]=time.time_ns()/10**9
flag1=1
time.sleep(0.0)
if sound2:
print("the NO.2 power of the sound is %lf"%sound2)
if len(basic_value_2)<=10:
basic_value_2.append(sound2)
if len(basic_value_2)==10:
value=0
for i in range(10):
value+=basic_value_2[i]
threshold[1]=(value/10)+delta
if 0 not in threshold:
if sound2>threshold[1] and flag2==0:
time_list[1]=time.time_ns()/10**9
flag2=1
time.sleep(0.0)
if sound3:
print("the NO.3 power of the sound is %lf"%sound3)
if len(basic_value_3)<=10:
basic_value_3.append(sound3)
if len(basic_value_3)==10:
value=0
for i in range(10):
value+=basic_value_3[i]
threshold[2]=(value/10)+delta
if 0 not in threshold:
if sound3>threshold[2] and flag3==0:
time_list[2]=time.time_ns()/10**9
flag3=1
time.sleep(0.0)
if sound4:
print("the NO.4 power of the sound is %lf"%sound4)
if len(basic_value_4)<=10:
basic_value_4.append(sound4)
if len(basic_value_4)==10:
value=0
for i in range(10):
value+=basic_value_4[i]
threshold[3]=(value/10)+delta
if 0 not in threshold:
if sound4>threshold[3] and flag4==0:
time_list[3]=time.time_ns()/10**9
flag4=1
time.sleep(0.0)
if (0 not in time_list) and (0 not in threshold):
print(threshold)
print(time_list)
break
loop_print()