import machine
import utime
# GPIO pins for the HC-SR04 sensor
trigger_pin = machine.Pin(2, machine.Pin.OUT) # Connect to the sensor's trigger pin
echo_pin = machine.Pin(3, machine.Pin.IN) # Connect to the sensor's echo pin
# Traffic light control pins (simulated)
red_light = machine.Pin(10, machine.Pin.OUT)
yellow_light = machine.Pin(11, machine.Pin.OUT)
green_light = machine.Pin(12, machine.Pin.OUT)
# Function to measure distance using the HC-SR04 sensor
def measure_distance():
trigger_pin.value(0)
utime.sleep_us(2)
trigger_pin.value(1)
utime.sleep_us(10)
trigger_pin.value(0)
while echo_pin.value() == 0:
pulse_start = utime.ticks_us()
while echo_pin.value() == 1:
pulse_end = utime.ticks_us()
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
distance = (pulse_duration * 0.0343) / 2 # Speed of sound is approximately 343 meters per second
return distance
# Traffic light control function
def control_traffic_lights(distance):
if distance < 10: # If a vehicle is very close
red_light.value(0)
yellow_light.value(1)
green_light.value(0)
elif 10 <= distance < 20: # If a vehicle is moderately close
red_light.value(1)
yellow_light.value(0)
green_light.value(0)
else: # If no vehicle is detected
red_light.value(0)
yellow_light.value(0)
green_light.value(1)
while True:
distance = measure_distance()
# Control traffic lights based on the distance measurements
control_traffic_lights(distance)
# For simulation purposes, print the distance and the traffic light state
print("Distance: {:.2f} cm".format(distance))
utime.sleep(2) # Wait for a few seconds before taking the next measurement