Last active
August 27, 2017 15:30
-
-
Save outime/c6ffe3295eb649fd224c11e83201cf79 to your computer and use it in GitHub Desktop.
Overly complicated Python script with multiple LED programs which can be changed by pressing an attached button
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum | |
from multiprocessing import Process | |
from time import sleep | |
import RPi.GPIO as GPIO | |
PINS = {'in': 19, 'out': 21} | |
class Program(Enum): | |
OFF = 1 | |
ON = 2 | |
BLINK = 3 | |
FAST_BLINK = 4 | |
def next(self): | |
cls = self.__class__ | |
members = list(cls) | |
index = members.index(self) + 1 | |
if index >= len(members): | |
index = 0 | |
return members[index] | |
def main(): | |
GPIO.setwarnings(False) | |
setup_gpio_pins(PINS) | |
start(PINS, Program.OFF) | |
def setup_gpio_pins(pins): | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(pins['in'], GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(pins['out'], GPIO.OUT) | |
def start(pins, program, program_process=None): | |
print('Activating program <{}>'.format(program.name)) | |
while True: | |
if not program_process: | |
program_process = Process(target=activate_program, args=[program, pins]) | |
program_process.start() | |
state = GPIO.input(pins['in']) | |
if state == False: # pressed | |
program_process.terminate() | |
program_process.join() | |
sleep(0.2) | |
break | |
start(pins, program.next()) | |
def activate_program(program, pins): | |
if program == Program.OFF: | |
GPIO.output(pins['out'], GPIO.LOW) | |
while True: | |
sleep(1) | |
if program == Program.ON: | |
GPIO.output(pins['out'], GPIO.HIGH) | |
while True: | |
sleep(1) | |
if program == Program.BLINK: | |
while True: | |
GPIO.output(pins['out'], GPIO.HIGH) | |
sleep(1) | |
GPIO.output(pins['out'], GPIO.LOW) | |
sleep(1) | |
if program == Program.FAST_BLINK: | |
while True: | |
GPIO.output(pins['out'], GPIO.HIGH) | |
sleep(0.1) | |
GPIO.output(pins['out'], GPIO.LOW) | |
sleep(0.1) | |
if __name__ == '__main__': | |
try: | |
main() | |
except KeyboardInterrupt: | |
print('Exiting...') | |
GPIO.cleanup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment