I'm currently working on a Raspberry Pi-based project about a car speed detection prototype. I used 2 Infrared Proximity sensors as a trigger. prox1 is Sensor 1 to trigger start stopwatch. prox2 is sensor 2 to trigger stop the stopwatch. The given distance is 50 cm. When a car passes both of the sensors, Raspberry Pi has to measure the speed (distance / (stop_time - start_time). And if the speed is above 60 cm/s, the camera would capture the car image and save it in pi folder. I want the prox1 and prox2 to be a trigger to start and stop the stopwatch. My question is, I keep getting warnings saying Name 'start_time' can be undefined. What should I do to make this work? Or is there any other way to get elapsed time triggered by the sensor without declaring the variable in the if-condition statement?
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()
CodePudding user response:
The problem is that start_time doesn't exist unless and until GPIO.input(prox1) returns False. This may not be possible in reality but from the code analysis perspective it could happen. Just set start_time to zero (or some other arbitrary value) immediately inside the while True loop