Skip to content

Instantly share code, notes, and snippets.

@tsengia
Created March 12, 2020 17:53
Show Gist options
  • Save tsengia/43bc36c0c0598b7acd1878120cd1a482 to your computer and use it in GitHub Desktop.
Save tsengia/43bc36c0c0598b7acd1878120cd1a482 to your computer and use it in GitHub Desktop.
Cycles through traffic light LEDs until paused by a button.
from gpiozero import LED, Button
from time import sleep
from gpiozero import PushButton
red = LED(25)
yellow = LED(8)
green = LED(7)
button = Button(21)
# On the first press, start the loop, second press pause the loop, and third press resume the loop
paused = True
#This keeps track of what color we are on
color = "yellow"
#This keeps track of how long we've been on a color (value is in milliseconds)
t = 3000
#This is how long each LED will be on for
DURATION = 3000
#When the button is pressed, toggle the paused state
def pressed(button):
if paused:
paused = False
else:
paused = True
#Here is our main loop that will run forever
while True:
sleep(0.01) #Sleep for only 10 milliseconds
if not paused:
if t < DURATION: #Are we still on the same LED as last time we ran the loop?
t += 0.01 # Increase the counter by the 10 milliseconds we slept for, notice that we do not increase the counter while paused
else: # We should move to the next LED
t = 0 #Restart the count
if color == "yellow": #Current color is yellow, next is red
color = "red"
yellow.off()
red.on()
elif color == "red": #Current color is red, next is green
color = "green"
red.off()
green.on()
elif color == "green": #Current color is green, next is yellow
color = "yellow"
green.off()
yellow.on()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment