Unboundlocalerror:在赋值之前引用了局部变量“pulse_start”

2024-04-20 15:53:05 发布

您现在位置:Python中文网/ 问答频道 /正文

它说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

Tags: echofalseinputoutputgpiotimesetupsleep
2条回答

您需要在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()

编辑:

你需要先声明pulse_startpulse_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()

相关问题 更多 >