下面是我在 Intel Galileo Gen2 上运行的代码。我只是想知道为什么当物体真正靠近超声波传感器时,程序会停止并抱怨变量 sig “分配前引用的局部变量‘sig’”?
import mraa
import time
trig = mraa.Gpio(0)
echo = mraa.Gpio(1)
trig.dir(mraa.DIR_OUT)
echo.dir(mraa.DIR_IN)
def distance(measure='cm'):
trig.write(0)
time.sleep(0.2)
trig.write(1)
time.sleep(0.00001)
trig.write(0)
while echo.read() == 0:
nosig = time.time()
while echo.read() == 1:
sig = time.time()
# et = Elapsed Time
et = sig - nosig
if measure == 'cm':
distance = et * 17150
elif measure == 'in':
distance = et / 0.000148
else:
print('improper choice of measurement!!')
distance = None
return distance
while True:
print(distance('cm'))