2015-09-22 76 views
-1

我試圖在覆盆子pi上按下按鈕時讀取超聲波範圍。UnboundLocalError:分配前引用的局部變量'signaloff'

我收到一個隨機錯誤,發生三次約1次。也曾嘗試在每次嘗試之間等待2秒鐘運行「打印讀取(0)」三次,有時它會起作用,有時會在第一次嘗試時失敗。

的錯誤是:

Traceback (most recent call last): 
    File "test.py", line 37, in <module> 
    print reading(0) 
    File "test.py", line 30, in reading 
    timepassed = signalon - signaloff 
UnboundLocalError: local variable 'signaloff' referenced before assignment 

的代碼是:

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

# btn on pin 18 
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) 
# LED on pin 24 
GPIO.setup(24, GPIO.OUT) 
# GPIO output = the pin that's connected to "Trig" on the sensor 
# GPIO input = the pin that's connected to "Echo" on the sensor 
GPIO.setup(17,GPIO.OUT) 
GPIO.setup(27,GPIO.IN) 

def reading(sensor): 

    if sensor == 0: 
     GPIO.output(17, GPIO.LOW) 
     time.sleep(0.3) 

     GPIO.output(17, True) 
     time.sleep(0.00001) 
     GPIO.output(17, False) 
     while GPIO.input(27) == 0: 
      signaloff = time.time() 

     while GPIO.input(27) == 1: 
      signalon = time.time() 

     timepassed = signalon - signaloff 
     distance = timepassed * 17000 

     return distance 
    else: 
     print "Incorrect usonic() function varible." 

while True: 
    input_state = GPIO.input(18) 
    if input_state == False: 
     print('Button Pressed') 
     GPIO.output(24, True) 
     print reading(0) 
     time.sleep(2) 
     GPIO.output(24, False) 
+0

你甚至可以理解錯誤是如何發生的嗎?這是一個普遍的混亂,一點研究應該告訴你它是什麼意思。順便說一句:'打印「錯誤消息」'不是錯誤處理,而是引發異常。 –

回答

1

如果GPIO.input(27)返回0,你第一次調用它,while循環將永遠不會進入,並signaloff決不會組。對於設置爲signalon的循環來說,情況也是如此,儘管該問題可能比較罕見。

相關問題