import machine
import time
from hcsr04 import HCSR04
# initialize the ultrasonic sensor
sensor = HCSR04(trigger_pin=14, echo_pin=26)
# initialize the traffic lights
red_led = machine.Pin(19, machine.Pin.OUT)
yellow_led = machine.Pin(18, machine.Pin.OUT)
green_led = machine.Pin(4, machine.Pin.OUT)
red_led_2 = machine.Pin(23, machine.Pin.OUT)
yellow_led_2 = machine.Pin(22, machine.Pin.OUT)
green_led_2 = machine.Pin(21, machine.Pin.OUT)
# set the initial state of the traffic lights
red_led.on()
yellow_led.off()
green_led.off()
# main loop
while True:
distance = sensor.distance_cm()
print("Distance: %.2f cm" % distance)
if distance < 60:
# if there is a car nearby, switch to green light
red_led.off()
red_led_2.on()
green_led.on()
time.sleep(15) # green light time
green_led.off()
yellow_led.on()
time.sleep(2) # yellow light time
yellow_led.off()
red_led.on()
time.sleep(2)
# change to another led
green_led_2.on()
yellow_led_2.off()
red_led_2.off()
time.sleep(15) # red light time
green_led_2.off()
yellow_led_2.on()
time.sleep(2) # yellow light time
yellow_led_2.off()
red_led_2.on()
time.sleep(2)
else:
# otherwise, switch to red light
red_led.off()
red_led_2.on()
yellow_led.off()
green_led.on()
time.sleep(5) # green light time
green_led.off()
yellow_led.on()
time.sleep(2) # yellow light time
yellow_led.off()
red_led.on()
time.sleep(2)
# change to another led
red_led.on()
red_led_2.off()
yellow_led_2.off()
green_led_2.on()
time.sleep(5) # green light time
green_led_2.off()
yellow_led_2.on()
time.sleep(2) # yellow light time
yellow_led_2.off()
red_led_2.on()
time.sleep(2)
while True:
distance = sensor.distance_cm()
print("Distance: %.2f cm" % distance)
if distance < 60:
yellow_led.on()
yellow_led_2.on()
else:
yellow_led.on()
yellow_led_2.on()