Raspberry pi 2B +的单超声波传感器不能从Pi端子运行
问题描述:
我一直在使用4针HC-SRO4超声波传感器,一次最多四个。我一直在开发代码,以使这些传感器中的4个同时工作,并且在重新组织用于项目安装的导线并使用基本代码运行之后,我无法使传感器正常工作。码如下:Raspberry pi 2B +的单超声波传感器不能从Pi端子运行
import RPi.GPIO as GPIO
import time
TRIG1 = 15
ECHO1 = 13
start1 = 0
stop1 = 0
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(TRIG1, GPIO.OUT)
GPIO.output(TRIG1, 0)
GPIO.setup(ECHO1, GPIO.IN)
while True:
time.sleep(0.1)
GPIO.output(TRIG1, 1)
time.sleep(0.00001)
GPIO.output(TRIG1, 0)
while GPIO.input(ECHO1) == 0:
start1 = time.time()
print("here")
while GPIO.input(ECHO1) == 1:
stop1 = time.time()
print("also here")
print("sensor 1:")
print (stop1-start1) * 17000
GPIO.cleanup()
电路(包括GPIO引脚)内改变线,传感器和其它部件我已经看过的代码,并加入打印语句给终端以查看哪些代码的部分是后运行。第一次打印声明 print("here")
执行一致,但第二个打印语句print("also here")
没有,并且我在解释损失。换句话说,为什么第二个while循环没有被执行?其他问题在这里没有解决我的问题。任何帮助将不胜感激。
感谢, H.
答
下面是Gaven麦克唐纳的教程,可能这方面的帮助:https://www.youtube.com/watch?v=xACy8l3LsXI
首先,与ECHO1 == 0
会循环的,而永远阻止,直到ECHO1变为1。这段时间里面的代码会被一次又一次地执行。你不希望一次又一次地设定时间,所以你可以做这样的事情:
while GPIO.input(ECHO1) == 0:
pass #This is here to make the while loop do nothing and check again.
start = time.time() #Here you set the start time.
while GPIO.input(ECHO1) == 1:
pass #Doing the same thing, looping until the condition is true.
stop = time.time()
print (stop - start) * 170 #Note that since both values are integers, python would multiply the value with 170. If our values were string, python would write the same string again and again: for 170 times.
而且,只是作为一个最佳实践,您应该使用try except块安全地退出代码。如:
try:
while True:
#Code code code...
except KeyboardInterrupt: #This would check if you have pressed Ctrl+C
GPIO.cleanup()
我已经使用过YouTube视频,但是感谢代码帮助,它解决了这个问题。再次感谢,Haydon –