Skip to content

Instantly share code, notes, and snippets.

@froggomad
Created January 15, 2021 06:57
Show Gist options
  • Save froggomad/e23cd0eed5c59bd8ef1d3a008f578682 to your computer and use it in GitHub Desktop.
Save froggomad/e23cd0eed5c59bd8ef1d3a008f578682 to your computer and use it in GitHub Desktop.
Raspberry pi - Flash 2 LEDs on and off triggered by a button press (button is wired with pulldown resistor)
# Write your code here :-)
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
# Define LEDs
GREEN_LED=14
RED_LED=4
# Setup LEDs
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)
# Define Button
BUTTON = 15
# Setup Button
GPIO.setup(BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# Set initial state for run loop
pressed = False
def button_pressed(channel):
global pressed
pressed = not pressed
GPIO.add_event_detect(BUTTON, GPIO.RISING, callback=button_pressed, bouncetime=500) # setup the callback for the button pressed event
def lights_out():
GPIO.output(GREEN_LED, False)
GPIO.output(RED_LED, False)
i=0
while True:
if pressed:
# set pin to other pin every iteration
if i%2 == 0:
pin=GREEN_LED
else:
pin=RED_LED
GPIO.output(pin, True)
time.sleep(0.25)
GPIO.output(pin, False)
time.sleep(0.25)
i+=1
else:
lights_out()
i=0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment