树莓pi 2B+单超声波传感器不能从pi终端工作

2024-05-15 12:09:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用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.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("here") 执行一致,但第二个print语句print("also here")没有执行,我无法解释。换句话说,为什么第二个while循环没有被执行?这里提出的其他问题对我的问题不起作用。任何帮助都将不胜感激。你知道吗

谢谢你, H


Tags: 代码importoutputgpioheretimesetupsleep
1条回答
网友
1楼 · 发布于 2024-05-15 12:09:32

下面是Gaven MacDonald的一个教程,可能对这方面有所帮助:https://www.youtube.com/watch?v=xACy8l3LsXI

首先,带有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()

相关问题 更多 >