文件里分别有三个文件: main.py 、PCF8591.py 和 chaoshengbo.py.。以及一小段报警声音。
首先是PCF8591.py (之前发表的博客有介绍到)
import smbus
import time
address = 0x48
A0 = 0x40
A1 = 0x41
A2 = 0X42
A3 = 0X43
bus = smbus.SMBus(1)
def AD():
while True:
bus.write_byte(address,A3)
value = bus.read_byte(address)
print(value)
time.sleep(1)
然后是chaoshengbo.py(之前发表的博客也介绍到)
import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#print( "Measuring Distance")
GPIO.setup(23,GPIO.OUT)
GPIO.setup(24,GPIO.IN)
time.sleep(0.2)
GPIO.output(23,False)
#print( "Setting Trigger pin to zero by default")
#time.sleep(1)
def distance():
while True:
GPIO.output(23,True)
time.sleep(0.00001)
GPIO.output(23,False)
while GPIO.input(24) == 0:
start_time = time.time()
while GPIO.input(24) == 1:
end_time = time.time()
Time = end_time - start_time
distance = Time * 17150
print("Measired Distance is:",distance,"cm.")
time.sleep(1)
最后是main.py文件
import threading
import time
import queue
import chaoshengbo
import PCF8591
def main():
chao_thread = threading.Thread(target=chaoshengbo.distance)
PCF8591_thread = threading.Thread(target=PCF8591.AD)
chao_thread.start()
PCF8591_thread.start()
chao_thread.join()
PCF8591_thread.join()
if __name__ == "__main__":
main()
测试效果:
在树莓派上不太好截图,只好用手机拍照,255是读取可调电阻的值,下一行是距离。