HCSR04卡住了(Python和Raspberry Pi)

2024-03-29 11:50:30 发布

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

我正在尝试使用HC-SR04超声波传感器在树莓皮3与Python。我从this site获得了大部分代码。然而,当我减少每次距离测量之间的睡眠时间时,代码就会陷入while GPIO.input(ECHO)==0:循环,然后停止一切。也许我把睡眠时间设置得太低了,但我真的不知道这会改变什么。你知道吗

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
TRIG=23
ECHO=24

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

def pulseIn():
    while True:
        GPIO.output(TRIG, False)
        time.sleep(.000005)
        GPIO.output(TRIG, True) # Sending out a trigger pulse for 10 microseconds
        time.sleep(.00001)
        GPIO.output(TRIG, False)
        pulse_start = time.time()
        pulse_end = time.time()
        while GPIO.input(ECHO)==0: # This is where it keeps getting stuck
            pulse_start = time.time()
            #if pulse_start-pulse_end>.5:  # This is one of my attempts to fix the problem.
            # It caused some bad output values
             #   continue

        while GPIO.input(ECHO)==1:
            pulse_end = time.time()
        return pulse_end-pulse_start


time.sleep(2) # Giving the sensor some time to warm up
for i in range(100):
    print(pulseIn()*17500)
    time.sleep(.001) # It seems to work when I set this to 1, but I would prefer if it worked faster

Tags: to代码echoinputoutputgpiotime时间
1条回答
网友
1楼 · 发布于 2024-03-29 11:50:30

从数据表中我们可以看到,该传感器的最大距离范围为4米。因此,当您减少两次连续测量之间的延迟时,您可能会在前一个信号未到达时从传感器发送另一个超声波信号。数据表建议该传感器的测量周期为60 ms。您的测量周期远小于建议值。你知道吗

传感器数据表: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf

相关问题 更多 >