Just playing with my Pico and practising doing some codes without looking up stuff. Thought I would tackle something "simple" like a traffic light sequence. I expanded it to a pedestrian crossing lights as well. And to make it even more complex, I added a pedestrian request button so that it will shorten the green light duration for the traffic (so pedestrian can cross).
In the video, the 1st sequence is "normal". 2nd sequence is pressing button early, but traffic still has built in 5 sec green time minimum. 3rd sequence is pressing button after the 5 seconds will immediately force a change from traffic green to traffic yellow and red.
(The kit I bought didn't have a green LED!)
https://youtu.be/ZDPbHfOmbAU
And this is my code. Not the most elegant, not OOP, but it works as intended.
Code: Select all
from machine import Pin
from utime import sleep
t_red = Pin(0, Pin.OUT)
t_yel = Pin(1, Pin.OUT)
t_grn = Pin(2, Pin.OUT)
p_red = Pin(3, Pin.OUT)
p_grn = Pin(4, Pin.OUT)
btn_irq = Pin(15, Pin.IN, Pin.PULL_UP)
button_down = False
ped = 0 #pedestrian or traffic go green
w = 1 # wait time before traffic change from green to yellow
# car traffic sequence
def traffic():
t_red.on()
sleep(5)
t_yel.on()
sleep(2)
t_red.off()
t_yel.off()
t_grn.on()
sleep(5) # minimium 5 secs green time before change to yellow
global w
sleep(w) # points to allow IRQ to shorten green to yellow time
print("5")
sleep(w)
print("4")
sleep(w)
print("3")
sleep(w)
print("2")
sleep(w)
print("1")
t_grn.off()
t_yel.on()
sleep(2)
t_yel.off()
t_red.on()
sleep(5)
ped = 1
# pedestrian traffic sequence
def pedes():
p_red.off()
p_grn.on()
sleep(10)
for x in range(20):
p_grn.toggle()
sleep(0.3)
p_grn.off()
p_red.on()
global w
w = 1
ped = 0
# pedestrian crossing button to speed up change from traffic green to yellow and then red
def Interrupt(pin):
print("IRQ")
global w
w = 0 # sleep time becomes zero during traffic green, forcing it to change to yellow and red on IRQ
print(w)
# debounce
if btn_irq.value() == False and not button_down:
button_down = True
if btn.irq.value() == True and button_down:
button_down = False
btn_irq.irq(trigger=Pin.IRQ_RISING, handler=Interrupt)
t_yel.off()
t_grn.off()
p_red.on()
p_grn.off()
while ped == 0:
traffic()
pedes()
Thanks!
Adrian