在树莓π中使用超声波传感器测量距离



我正在尝试使用超声波传感器测量传感器(S)到障碍物(X)的距离(D)。基本原理是,我将发送一个声音脉冲并将其接收回来,并利用它从从S到X再回来(比如T),我将使用以下公式计算距离:D=(V*T)/2。(V是声音在空气中的速度)。以下是一些python代码实现的相同功能:

#Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO    = 24
print "Ultrasonic Measurement"
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
# Allow module to settle
time.sleep(0.5)
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
# Calculate pulse length
elapsed = stop-start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34300
# That was the distance there and back so halve the value
distance = distance / 2

我很难理解为什么开始和停止时间是这样计算的。对我来说,开始时间似乎是"我们第一次得到高信号时"的时间,停止时间是"我们最后一次得到低信号时",所以它们的差异将是"脉冲高的时间",我认为这将与距离无关,因为高信号每次都会在相同的持续时间内发出。我试着查看了其他来源,他们似乎都只考虑了这个时间,也就是说,ECHO传感器的输入高的时间。然而,我不同意。

它认为代码应该是这样的:

# start time is time when we start sending the signal
start = time.time()
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
while GPIO.input(GPIO_ECHO)==0:
pass
# stop time is the time when we first get a high on the output.
stop = time.time()
while GPIO.input(GPIO_ECHO)==1:
pass
# Calculate pulse length
elapsed = stop-start

在我看来,我似乎错过了一些显而易见的东西。如果有人能告诉我它是什么,我将不胜感激。

这是因为超声波回波传感器就是这样工作的。您向GPIO_TRIGGER线路发送一个脉冲。这导致传感器开始发送一个短暂的声音脉冲。然而,这本身需要一些时间。然后它必须等待,直到它接收到该脉冲的回波。当完成发送声音脉冲时,传感器的输出变高,当<em]完成接收>声脉冲时,输出再次变低。中间的时间是声音脉冲到达某个物体并被反射回来所需的时间。

最新更新