它说unboundlocalerror: local variable 'pulse_start' referenced before assignment
。我以前运行它,所以突然发生错误。
import RPi.GPIO as GPIO, time
GPIO.setwarnings(False)
def ultrasonicfunction(DistanceOfWaterLevelFromSensor):
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 18
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.output(TRIG, False)
time.sleep(1)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17000
if distance > 44:
DistanceOfWaterLevelFromSensor = "0"
print
'Please place the ultrasonic sensor near the water tank'
# Watertank height = 44cm,
else:
DistanceOfWaterLevelFromSensor = 44 - distance
DistanceOfWaterLevelFromSensor = "%.2f" % round(DistanceOfWaterLevelFromSensor, 2)
return DistanceOfWaterLevelFromSensor
答案 0 :(得分:0)
修改强>
你需要先声明 pulse_start 和 pulse_end ,以防万一你没有进入循环
pulse_start = 0
pulse_end = 0
while GPIO.input(ECHO) == 0:
pulse_start = time.time() loop
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
答案 1 :(得分:0)
您需要在while
循环之前声明变量,如下所示:
pulse_start = 0
pulse_end = 0
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()