Python 树莓皮2B和x2B的单超声波传感器;从Pi终端不起作用
我一直在使用4针HC-SRO4超声波传感器,一次最多4个。我一直在开发代码,以使其中4个传感器同时工作,在重新组织项目上安装的电线并使用基本代码运行一个之后,我无法使传感器工作。代码如下:Python 树莓皮2B和x2B的单超声波传感器;从Pi终端不起作用,python,raspberry-pi2,Python,Raspberry Pi2,我一直在使用4针HC-SRO4超声波传感器,一次最多4个。我一直在开发代码,以使其中4个传感器同时工作,在重新组织项目上安装的电线并使用基本代码运行一个之后,我无法使传感器工作。代码如下: 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.OU
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语句print(“也在这里”)
没有执行,我无法解释。换句话说,为什么第二个while循环没有被执行?这里提出的其他问题对我的问题不起作用。任何帮助都将不胜感激
谢谢,
H.以下是Gaven MacDonald的一篇教程,可能会对这方面有所帮助: 首先,ECHO1==0的while块将永远循环,直到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()
下面是Gaven MacDonald的一个教程,可能会对这方面有所帮助: 首先,ECHO1==0的while块将永远循环,直到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视频,但是感谢代码帮助,它解决了这个问题。再次感谢,HaydonI实际上已经使用了youtube视频,但是感谢代码帮助,它解决了这个问题。再次感谢你,海顿