我目前正在研究一個基于 Raspberry Pi 的關于汽車速度檢測原型的專案。我使用了 2 個紅外接近傳感器作為觸發器。prox1 是用于觸發啟動秒表的傳感器 1。prox2 是用于觸發秒表停止的傳感器 2。給定的距離是 50 厘米。當汽車通過這兩個傳感器時,Raspberry Pi 必須測量速度(距離/(stop_time - start_time)。如果速度超過 60 cm/s,相機將捕獲汽車影像并將其保存在 pi 檔案夾中。我希望 prox1 和 prox2 成為啟動和停止秒表的觸發器。我的問題是,我一直收到警告說 Name 'start_time' can be undefined。我應該怎么做才能使這項作業?或者有沒有其他方法可以獲取傳感器觸發的經過時間而不在?? if 條件陳述句中宣告變數?
import time
from pint import UnitRegistry
from picamera import PiCamera
ureg = UnitRegistry()
camera = PiCamera()
camera.resolution = (1280, 720)
camera.exposure_mode = 'sports'
camera.iso = 0
camera.shutter_speed = 7500
GPIO.setwarnings(False)
prox1 = 12
prox2 = 18
led = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(prox1, GPIO.IN)
GPIO.setup(prox2, GPIO.IN)
GPIO.setup(led, GPIO.OUT)
distance = 50 * ureg.cm
try:
while True:
if (GPIO.input(prox1) == False): # object in front of the sensor = false
start_time = time.time()
GPIO.output(led, GPIO.HIGH)
print('Calculating Speed')
time.sleep(0.3)
else:
print('No Car Detected')
time.sleep(1)
if (GPIO.input(prox2) == False):
stop_time = time.time()
GPIO.output(led, GPIO.LOW)
timer: float = stop_time - start_time
print('Time = ', timer)
time.sleep(0.3)
speed: float = distance / timer
print('Speed = ', speed)
time.sleep(0.3)
if speed > 60 and timer < 1 * ureg.second :
try:
camera.capture('test1.jpg')
time.sleep(2)
pass
finally:
camera.close()
except KeyboardInterrupt:
GPIO.cleanup()
uj5u.com熱心網友回復:
問題是 start_time 不存在,除非 GPIO.input(prox1) 回傳 False。這在現實中可能是不可能的,但從代碼分析的角度來看,它可能會發生。只需在while True回圈內立即將 start_time 設定為零(或其他任意值)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491756.html
上一篇:雖然,不在Python中回圈
下一篇:雖然,不在Python中回圈
