2016-02-05 78 views
1

我一直在使用4針HC-SRO4超聲波傳感器,一次最多四個。我一直在開發代碼,以使這些傳感器中的4個同時工作,並且在重新組織用於項目安裝的導線並使用基本代碼運行之後,我無法使傳感器正常工作。碼如下:Raspberry pi 2B +的單超聲波傳感器不能從Pi端子運行

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("also here")沒有,並且我在解釋損失。換句話說,爲什麼第二個while循環沒有被執行?其他問題在這裏沒有解決我的問題。任何幫助將不勝感激。

感謝, H.

回答

0

下面是Gaven麥克唐納的教程,可能這方面的幫助:https://www.youtube.com/watch?v=xACy8l3LsXI

首先,與ECHO1 == 0會循環的,而永遠阻止,直到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() 
+0

我已經使用過YouTube視頻,但是感謝代碼幫助,它解決了這個問題。再次感謝,Haydon –