Last active
November 28, 2015 09:26
-
-
Save masasin/32240f1fcf08d2c980da to your computer and use it in GitHub Desktop.
Code cleanup for /u/SquidgeyBear. (See thread at http://redd.it/3tpv6v, and comment at https://goo.gl/G2H67c)
This file contains 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
#!/usr/bin/env python3 | |
""" | |
Runs a simulation of a traffic light cycle. | |
Written by /u/masasin as code cleanup for /u/SquidgeyBear. See the original | |
thread at https://redd.it/3tpv6v, and the explanatory comments at | |
https://goo.gl/G2H67c. | |
""" | |
from itertools import cycle | |
import logging | |
import time | |
import RPi.GPIO as GPIO | |
# Light colours and pin numbers. | |
lights = {"green": 29, | |
"amber": 31, | |
"red": 33} | |
def initialize(): | |
"""Set up GPIO and turn on the output pins.""" | |
GPIO.setmode(GPIO.BOARD) # Use physical pin numbers. | |
logging.debug("Initializing GPIO pins") | |
for colour, pin in lights.items(): | |
logging.debug("Setting {colour} (pin {pin}) to output" | |
.format(colour=colour, pin=pin)) | |
GPIO.setup(pin, GPIO.out) | |
def handle_led(colour, state): | |
""" | |
Turn a coloured LED on or off. | |
Parameters | |
---------- | |
colour : str | |
The colour of the LED. | |
state : bool | |
Whether the LED should be on or OFF. | |
""" | |
logging.debug("{colour} {state}".format(colour=colour.capitalize(), | |
state="on" if state else "off")) | |
GPIO.output(lights[colour], state) | |
def set_lights(config): | |
""" | |
Set all the LEDs to a specific configuration. | |
Parameters | |
---------- | |
config : str | |
The colours that need to be on, separated by a space. | |
""" | |
for colour in lights: | |
if colour in config.split(): # Split at the space and check. | |
handle_led(colour, True) | |
else: | |
handle_led(colour, False) | |
def main(): | |
"""Main entry point for the script.""" | |
logging.info("Started traffic light simulation") | |
configurations = ["green", "amber", "red", "amber red"] | |
main_clock, current_config = 0 | |
pedestrian_waiting = False | |
sleep_duration = 0.5 # seconds | |
try: | |
initialize() # Note that it's inside the try-except-finally block. | |
for configuration in cycle(configurations): | |
set_lights(configuration) | |
if not pedestrian_waiting: | |
if main_clock % 5 == 0: # Every five ticks (2.5 seconds) | |
continue | |
else: | |
logging.debug("There is a pedestrian!") | |
main_clock += 1 | |
time.sleep(sleep_duration) | |
except KeyboardInterrupt: # Exit cleanly by pressing Ctrl+C. | |
logging.info("Exiting simulation") | |
finally: | |
GPIO.cleanup() | |
if __name__ == "__main__": | |
logging.basicConfig(level=logging.INFO) # logging.DEBUG gives more info. | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment