【问题标题】:Why do I get the error message "start_time is not defined"?为什么我会收到错误消息“start_time is not defined”?
【发布时间】:2019-08-01 14:30:05
【问题描述】:

我在第 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)

【问题讨论】:

  • 因为您似乎还没有定义变量start_time...您确实定义了一个变量start...也许您的意思是?
  • 您也没有定义end_time,但您定义了end

标签: python python-3.x nameerror


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

     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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 2022-08-19
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多