使用 Raspberry Pi 3 测试距离传感器时出错?有什么建议么?
Getting Error when testing Distance Censor with RaspberryPi3? Any suggetions?
下面是我的代码,我经常得到"NameError: name 'start' is not defined"
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(0)
tr = 4
ec = 18
GPIO.setup(tr, GPIO.OUT)
GPIO.setup(ec, GPIO.IN)
GPIO.output(tr, True)
time.sleep(0.0001)
GPIO.output(tr, False)
while GPIO.input(ec) == 0:
start = time.time()
while GPIO.input(ec) == 1:
end = time.time()
distance = (end-start) * 17200
print('Distance: {} cm'.format(distance))
GPIO.cleanup()
谁能为此提供更好的代码?
你在while循环中定义start
,如果GPIO.input(ec) != 0
执行时,start
不会被定义,你会得到那个错误。
在 while
循环之前放置 start = 0
或 start = time.time()
以确保它已定义。
end
变量也是如此
下面是我的代码,我经常得到"NameError: name 'start' is not defined"
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(0)
tr = 4
ec = 18
GPIO.setup(tr, GPIO.OUT)
GPIO.setup(ec, GPIO.IN)
GPIO.output(tr, True)
time.sleep(0.0001)
GPIO.output(tr, False)
while GPIO.input(ec) == 0:
start = time.time()
while GPIO.input(ec) == 1:
end = time.time()
distance = (end-start) * 17200
print('Distance: {} cm'.format(distance))
GPIO.cleanup()
谁能为此提供更好的代码?
你在while循环中定义start
,如果GPIO.input(ec) != 0
执行时,start
不会被定义,你会得到那个错误。
在 while
循环之前放置 start = 0
或 start = time.time()
以确保它已定义。
end
变量也是如此