Python UnboundLocalError:局部变量';信号关闭';分配前参考

Python UnboundLocalError:局部变量';信号关闭';分配前参考,python,raspberry-pi,Python,Raspberry Pi,当按下树莓皮上的按钮时,我试图读取超声波范围 我得到一个随机错误,大约三次发生一次。还尝试运行“打印读取(0)”三次,每次尝试之间等待2秒,有时有效,有时第一次尝试失败 错误是: Traceback (most recent call last): File "test.py", line 37, in <module> print reading(0) File "test.py", line 30, in reading timepassed = sign

当按下树莓皮上的按钮时,我试图读取超声波范围

我得到一个随机错误,大约三次发生一次。还尝试运行“打印读取(0)”三次,每次尝试之间等待2秒,有时有效,有时第一次尝试失败

错误是:

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

如果第一次调用时
GPIO.input(27)
返回0,则永远不会进入while循环,也永远不会设置
signaloff
。对于设置
signalon
的循环,事实上也是如此,尽管这个问题可能更为罕见

你知道错误是怎么发生的吗?这是一个常见的困惑,只要做一点研究,你就会明白这是什么意思。顺便说一句:
打印“错误消息”
不是错误处理,而是引发异常。
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)