-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)
你甚至可以理解错误是如何发生的吗?这是一个普遍的混乱,一点研究应该告诉你它是什么意思。顺便说一句:'打印“错误消息”'不是错误处理,而是引发异常。 –