# P3H - Intelligent Pedestrian Crossing Traffic Light
from machine import Pin, PWM
import time
time.sleep(0.1)
# Pins
car_green = Pin(15, Pin.OUT)
car_yellow = Pin(14, Pin.OUT)
car_red = Pin(13, Pin.OUT)
rgb_red = PWM(Pin(10))
rgb_green = PWM(Pin(12))
rgb_blue = PWM(Pin(11))
for pwm in (rgb_red, rgb_green, rgb_blue):
pwm.freq(1000)
button = Pin(16, Pin.IN, Pin.PULL_UP)
# Timing (seconds)
GREEN_TIME = 5
YELLOW_TIME = 2.5
RED_TIME = 7.5
WALK_TIME = 4
BLINK_DURATION = 2
BLINK_INTERVAL = 0.25
# Colors (common cathode: 65535 = full on)
WHITE = (65535, 65535, 65535)
OFF = (0, 0, 0)
DONT_WALK = (65535, 0, 0) # red channel only
def set_ped(r, g, b):
rgb_red.duty_u16(r)
rgb_green.duty_u16(g)
rgb_blue.duty_u16(b)
def all_off():
car_green.off()
car_yellow.off()
car_red.off()
set_ped(*OFF)
all_off()
ped_request = False
while True:
# Green phase
car_green.on()
set_ped(*OFF)
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < GREEN_TIME * 1000:
if button.value() == 0:
ped_request = True
time.sleep_ms(200)
break
time.sleep_ms(50)
car_green.off()
# Yellow phase
car_yellow.on()
time.sleep(YELLOW_TIME)
car_yellow.off()
# Red + pedestrian phase
car_red.on()
set_ped(*WHITE)
time.sleep(WALK_TIME)
for _ in range(int(BLINK_DURATION / BLINK_INTERVAL)):
set_ped(*DONT_WALK)
time.sleep(BLINK_INTERVAL)
set_ped(*OFF)
time.sleep(BLINK_INTERVAL)
set_ped(*DONT_WALK)
remaining = RED_TIME - WALK_TIME - BLINK_DURATION
if remaining > 0:
time.sleep(remaining)
car_red.off()
ped_request = False