Add working traffic lights
This commit is contained in:
55
main.py
Executable file
55
main.py
Executable file
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from gpiozero import Button, LED
|
||||
import time
|
||||
|
||||
# define both traffic lights in order: red, amber, green
|
||||
# set main light to green and side light to red
|
||||
MAIN_LIGHTS = [LED(p, initial_value = i == 2) for i, p in enumerate((0, 5, 6))]
|
||||
SIDE_LIGHTS = [LED(p, initial_value = i == 0) for i, p in enumerate((13, 19, 26))]
|
||||
BTN = Button(20)
|
||||
|
||||
# constants
|
||||
GREEN_BLINK_RATE = 0.5
|
||||
AMBER_STOP_DURATION = 2.5
|
||||
AMBER_GO_DURATION = 1
|
||||
SWITCH_SIDE_DELAY = 3
|
||||
SIDE_GREEN_DURATION = 5
|
||||
|
||||
def green_to_red(lights):
|
||||
# blink green
|
||||
lights[2].blink(GREEN_BLINK_RATE, GREEN_BLINK_RATE, 2, False)
|
||||
lights[2].off()
|
||||
# show amber
|
||||
lights[1].blink(AMBER_STOP_DURATION, 0, 1, False)
|
||||
# show red
|
||||
lights[0].on()
|
||||
|
||||
def red_to_green(lights):
|
||||
# show amber and red
|
||||
lights[1].blink(AMBER_GO_DURATION, 0, 1, False)
|
||||
lights[0].off()
|
||||
# show green
|
||||
lights[2].on()
|
||||
|
||||
ongoing = False
|
||||
def sequence():
|
||||
global ongoing
|
||||
if ongoing:
|
||||
return # block input if there's an ongoing sequence
|
||||
ongoing = True
|
||||
|
||||
green_to_red(MAIN_LIGHTS)
|
||||
time.sleep(SWITCH_SIDE_DELAY)
|
||||
red_to_green(SIDE_LIGHTS)
|
||||
time.sleep(SIDE_GREEN_DURATION)
|
||||
green_to_red(SIDE_LIGHTS)
|
||||
time.sleep(SWITCH_SIDE_DELAY)
|
||||
red_to_green(MAIN_LIGHTS)
|
||||
|
||||
ongoing = False
|
||||
|
||||
BTN.when_pressed = sequence
|
||||
|
||||
input()
|
||||
|
||||
Reference in New Issue
Block a user