我用LEGO製作了這個簡單的機器人,它使用Raspberry Pi作爲計算機。我寫的代碼是用Python編寫的,基本上它使用超聲波傳感器來測量距離。這裏是代碼:Raspberry Pi超聲波傳感器輸出在幾次循環迭代後失速
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,程序打印出「你好」 ......直到這個:
Ultrasonic Sensor Distance Output Picture. 你可以看到輸出流停止。它從字面上停止,就是這樣。沒有錯誤信息,沒有。關於它的最糟糕的部分是它隨機地做到這一點。當它打印出距離時它可能會停頓,當它打印「Hi」時可能會失速,但我注意到它在打印「Hi」時停頓得更頻繁,它在隨機數輸出後停頓。所以接下來我要做的是按ctrl + c來停止程序,這就是它看起來的樣子like.我也忘了提到三個超聲波傳感器作爲一個連接在一起,只使用GPIO 21和GPIO 20。即使他們有自己獨立的銷子對,他們仍然有相同的拖延問題,所以它沒有什麼不同。
如果任何人有一個想法是什麼導致這個,我會很高興,因爲我花了幾個小時試圖解決它。
你可能想在你的'distance'方法內的兩個while循環中加入一個小睡眠。目前他們只會拉動'g.input'就會消耗很多週期。 –
那麼,我在第一個while循環和第二個while循環之間添加了一個t.sleep(0.01),它將輸出搞砸爲一個負值0_o ... –
我的意思是作爲while循環的一部分,而不是在循環。 –