From 93bb45617ea5fc46f0303b966ae8dfbf65de75a9 Mon Sep 17 00:00:00 2001 From: Josh Peedimaa Date: Thu, 15 Oct 2020 18:31:38 +0300 Subject: [PATCH] Add working traffic lights --- main.py | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100755 main.py diff --git a/main.py b/main.py new file mode 100755 index 0000000..60174cc --- /dev/null +++ b/main.py @@ -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() +