Lightsaber

Just using spare time to put together a tutorial for the Autumn Cotswold Raspberry Jam.

import RPi.GPIO as GPIO
import time

RED_LED = 35
GREEN_LED = 33
BLUE_LED = 37

GPIO.setmode(GPIO.BOARD)

GPIO.setup(RED_LED, GPIO.OUT)
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(BLUE_LED, GPIO.OUT)

GPIO.output(RED_LED, GPIO.LOW)
GPIO.output(GREEN_LED, GPIO.LOW)
GPIO.output(BLUE_LED, GPIO.LOW)

#---------------------------------------------------------------
# All the LEDs are turned on every 1/100 of a second or 0.01s.
#---------------------------------------------------------------
pulse_period = 0.01

#---------------------------------------------------------------
# This is how much of the pulse period each LED stays turned on.
# After that, it gets turned off again.
#---------------------------------------------------------------
red_fraction = 0.002
red_on = red_fraction

blue_fraction = 0.003
blue_on = blue_fraction

green_fraction = 0.005
green_on = green_fraction

#---------------------------------------------------------------
# Remember the time this all started so we can work out how long
# we've been going since we started. 
#---------------------------------------------------------------
start_time = time.time()

try:
    while True:
        time.sleep(0.001)
        clock_time = (time.time() - start_time) % pulse_period


        #========================== RED =======================#

        if clock_time < red_on * pulse_period: GPIO.output(RED_LED, GPIO.HIGH) else: GPIO.output(RED_LED, GPIO.LOW) red_on += red_fraction if red_on > 1 or red_on < 0:
            red_fraction = -red_fraction
            red_on += red_fraction


        #========================= GREEN ======================#

        if clock_time < green_on * pulse_period: GPIO.output(GREEN_LED, GPIO.HIGH) else: GPIO.output(GREEN_LED, GPIO.LOW) green_on += green_fraction if green_on > 1 or green_on < 0:
            green_fraction = -green_fraction
            green_on += green_fraction


        #========================= BLUE =======================#

        if clock_time < blue_on * pulse_period: GPIO.output(BLUE_LED, GPIO.HIGH) else: GPIO.output(BLUE_LED, GPIO.LOW) blue_on += blue_fraction if blue_on > 1 or blue_on < 0:
            blue_fraction = -blue_fraction
            blue_on += blue_fraction

except KeyboardInterrupt as e:
    pass

GPIO.output(RED_LED, GPIO.LOW)
GPIO.output(GREEN_LED, GPIO.LOW)
GPIO.output(BLUE_LED, GPIO.LOW)

GPIO.cleanup()

Leave a Reply

Your email address will not be published. Required fields are marked *