Raspberry pi 2B+ 的单个超声波传感器无法从 Pi 终端运行

Single Ultrasonic Sensor for Raspberry pi 2B+ not functioning from Pi Terminal

我一直在使用 4 针 HC-SRO4 超声波传感器,一次最多四个。我一直在开发代码以使这些传感器中的 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("here") 始终如一地执行,但第二个 print 语句 print("also here") 没有,我不知所措。换句话说,为什么第二个while循环没有被执行?此处提出的其他问题对我的问题不起作用。任何帮助将不胜感激。

谢谢, H.

这是 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()