2015-09-22 74 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的循环来说,情况也是如此,尽管该问题可能比较罕见。

相关问题