2017-08-27 111 views
1

因此,我開始使用hc-sr04超聲波傳感器並遇到問題。我想讀取多個傳感器(兩個用於初學者),但是我在兩者上獲得相同的距離值。下面是代碼:使用python讀取BBB的多個超聲波傳感器

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import Adafruit_BBIO.GPIO as GPIO 
import time 

def distanceMeasurement(TRIG,ECHO): 

    GPIO.output(TRIG, True) 
    time.sleep(0.00001) 
    GPIO.output(TRIG, False) 

    while GPIO.input(ECHO) == 0: 
     pulseStart = time.time() 
    while GPIO.input(ECHO) == 1: 
     pulseEnd = time.time() 

    pulseDuration = pulseEnd - pulseStart 
    distance = pulseDuration * 17150 
    distance = round(distance, 2) 
    return distance 

#Configuration 
GPIO.setup("P9_15",GPIO.OUT) #Trigger 
GPIO.setup("P9_12",GPIO.IN) #Echo 
GPIO.setup("P9_11",GPIO.OUT) 
GPIO.setup("P9_13",GPIO.IN) 

#Security 
GPIO.output("P9_11", False) 
GPIO.output("P9_15", False) 
time.sleep(0.5) 

#main Loop 
try: 
    while True: 
     for i in range(2): 
      if i == 0: 
       recoveredDistance = distanceMeasurement("P9_11","P9_13") 
       print "Distance1: ",recoveredDistance,"cm" 
      elif i == 1: 
       recoveredDIstance = distanceMeasurement("P9_15","P9_12") 
       print "Distance2: ",recoveredDistance,"cm" 
     time.sleep(1) 
except KeyboardInterrupt: 
    print "Measurement stopped by user" 
    GPIO.cleanup() 

我得到兩個不管同一個閱讀對傳感器2物體的距離,在傳感器1讀取距離是什麼都顯示;似乎傳感器2被忽略。

做一些「手動調試」(即打印TRIG,ECHO)我注意函數收到
正確的參數,這裏是輸出到「調試」:

P9_11 
P9_13 

Distance1: 20.79 cm 
P9_15 
P9_12 

Distance2: 20.79 cm 
P9_11 
P9_13 

Distance1: 20.13 cm 
P9_15 
P9_12 

我想用一個溫控功能閱讀所有的傳感器。預先感謝您

+1

'recoveredDIstance'中有一個類似的拼寫錯誤。另外'for' /'if' /'else'沒有任何意義。 –

回答

1

由於第二次測量保存爲recoveredDIstance,所以可以打印兩次相同的結果。所以recoveredDistance不變。 Python區分大小寫。

while True: 
    recoveredDistance = distanceMeasurement("P9_11","P9_13") 
    print "Distance1: ", recoveredDistance, "cm" 
    recoveredDistance = distanceMeasurement("P9_15","P9_12") 
    print "Distance2: ", recoveredDistance, "cm" 
    time.sleep(1) 
相關問題