为什么会收到错误消息“未定义start_time”?

时间:2019-08-01 14:30:05

标签: python python-3.x nameerror

我在第20行(pulse_duration = end_time-start_time)出错,提示:

NameError: name 'start_time' is not defined
import gpiozero
import time

TRIG = 23
ECHO = 24

trigger = gpiozero.OutputDevice(TRIG)
echo = gpiozero.DigitalInputDevice(ECHO)

trigger.on()
time.sleep(0.00001)
trigger.off()

while echo.is_active == False:
        start = time.time()

while echo.is_active == True:
        end = time.time()

pulse_duration = end_time - start_time

distance = 34300 * (pulse_duration/2)

round_distance = round(distance, 1)

print("Distance: ", round_distance)

2 个答案:

答案 0 :(得分:0)

因为尚未在代码中定义end_timestart_time。您将它们分别命名为startend。您将遇到的另一个问题是定义这些变量的范围。使用默认值在循环之外定义它们。

答案 1 :(得分:0)

如上所述,似乎您正在调用其他未定义的变量,并且会遇到没有默认值的问题。试试这个:

 import gpiozero
 import time

 TRIG = 23
 ECHO = 24

 trigger = gpiozero.OutputDevice(TRIG)
 echo = gpiozero.DigitalInputDevice(ECHO)

 trigger.on()
 time.sleep(0.00001)
 trigger.off()
 start = 0
 end = 0
 while echo.is_active == False:
    start = time.time()

 while echo.is_active == True:
    end = time.time()

 pulse_duration = end - start

 distance = 34300 * (pulse_duration/2)

 round_distance = round(distance, 1)

 print("Distance: ", round_distance)