UnboundLocalError: local variable 'signaloff' referenced before assignment
UnboundLocalError: local variable 'signaloff' referenced before assignment
我正在尝试在 raspberry pi 上按下按钮时读取超声波范围。
我收到一个随机错误,大约每三次发生 1 次。还尝试了 运行 'print reading(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
密码是:
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)
如果GPIO.input(27)
returns 0第一次调用,永远不会进入while循环,永远不会设置signaloff
。对于设置 signalon
的循环实际上也是如此,尽管这个问题可能比较少见。
我正在尝试在 raspberry pi 上按下按钮时读取超声波范围。
我收到一个随机错误,大约每三次发生 1 次。还尝试了 运行 'print reading(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
密码是:
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)
如果GPIO.input(27)
returns 0第一次调用,永远不会进入while循环,永远不会设置signaloff
。对于设置 signalon
的循环实际上也是如此,尽管这个问题可能比较少见。