Raspberry Pi超声波传感器输出在几次循环迭代后失速

时间:2016-10-22 17:26:54

标签: python raspberry-pi raspbian gpio arduino-ultra-sonic

我使用LEGO制作了这个简单的机器人,并使用Raspberry Pi作为计算机。我写的代码是用Python编写的,基本上它用的是使用超声波传感器来测量距离。这是代码:

import RPi.GPIO as g
import time as t
g.setmode(g.BCM)
g.setwarnings(False)

# trig is the pin on the sensor which will emit a very fast pulse
trig = 21
# echo is the pin which will recieve the pulse from the trig 
echo = 20

g.setup(trig, g.OUT)
g.setup(echo, g.IN)

def distance(dur):
    global dis
    start = 0
    end = 0
    g.output(trig, False)
    t.sleep(0.01)
    g.output(trig, True)
    t.sleep(0.00001)
    g.output(False)
    while g.input(echo) == 0:
        start = t.time()
    while g.input(echo) == 1:
        start = t.time()
    duration = end - start
    dis = duration * 17150
    dis = round(dis,2)
    print "Distance: " + dis
    t.sleep(dur)

while True:
    # so the function is being called, and the time between outputs is 0.01 seconds so it is very 
    # fast and quickly showing on the screen. If the distance is less than 5, then the program 
    # will print out "Hi" to show that. s
    distance(0.01)
    if dis < 5:
        print "Hi"

非常简单吧?但是你看,代码执行完美,它显示了距离,当我把手靠近传感器并且变量dis小于5时,程序打印出来&#34;嗨&#34; ......直到这个:< / p>

Ultrasonic Sensor Distance Output Picture. 您可以看到输出流只是停顿。它确实停止了,就是这样。没有错误信息,没有。关于它的最糟糕的部分是它随机做到这一点。它只是打印出距离就会失速,它可以在打印时停止&#34;嗨&#34;但是我确实注意到它在印刷时更频繁地停滞了#34;嗨&#34;并且它在随机数量的输出之后停止。所以我接下来要做的是按ctrl + c来停止程序,这就是它看起来like. 我也忘了提到三个超声波传感器连接在一起,只使用GPIO 21和GPIO 20。虽然仍然有效,即使他们有自己独立的针脚,他们仍然有相同的停滞问题,所以它没有什么区别。

如果有人知道造成这种情况的原因,我会很高兴,因为我花了好几个小时试图修复它。

1 个答案:

答案 0 :(得分:1)

简答:在函数后的while循环中添加.01的睡眠               问题是Pi比传感器更快,导致               没有错误,只是暂停。

就像Tammo Heeren所说的那样,加入一个睡眠。超声波传感器只能如此快速地获取和发送数据(声音的速度近似),但是Pi可以更快地计算甚至只是一个天文数量很小的数量,但它足够,因为Pi和传感器将不同步。开始时的差异很小,但随着时间的推移变得越来越大。你的程序随机停止可能是因为CPU没有达到速度(a.k.a.滞后)并且只需要一点时间才能退出。