Sunday 13 December 2015

Christmas Lights with Raspberry Pi and GPIOZERO

We were in Wilco yesterday and spotted some battery powered LED xmas lights for the bargain price of £2.50. They seemed ideal for a bit of festive hacking


There were a few types available and I picked up 3 different ones: warm white LEDs on a flexible but fairly rigid wire, some brighter white LEDs encapsulated in a snowflake housing and some traditional multi-colour LEDs.

The strings of LEDs come attached to  two AA cells in a neat enclosure with an on/off switch. I snipped the wires fitted jumper wire housings to the end of each so I could plug them straight onto the GPIO header. As the LEDs run on 3v and I was intending to drive them using an 'expendable' model B, I decided not to bother with a series resistor. 


I kept the batteries and the holders - these are bound to be useful for other projects (similar boxes can cost almost as much as the whole LED set).


Then I knocked up a quick Python program to run a mixed illuminate sequence for each of the lights. 

from gpiozero import PWMLED
from time import sleep
import random
import threading

white = PWMLED(23)
snowflakes = PWMLED(18)
colours = PWMLED(25)

LIGHTS = [white,snowflakes,colours]

def gentle(lights):
    for x in range(1,100):
        lights.value = x/100
        sleep(0.05)

def randomblink(lights): 
    lights.blink(random.randint(1,10)/10,random.randint(1,10)/10,10,False)

def sequence(lights):
    while True:
        print('gentle')
        gentle(lights)
        print('sleep')
        sleep(random.randint(1,10)/10)
        print('blink')
        randomblink(lights)
        print('sleep')
        sleep(random.randint(1,10)/10)
        print('on')
        lights.on()
        print('sleep')
        sleep(random.randint(1,10))

for i in LIGHTS:
    t = threading.Thread(target=sequence, args=(i,))
    t.start()


I then added a line to the /etc/rc.local file on the Pi so that the Python code runs automatically at startup.

Our Christmas tree was already quite covered with decorations so I decided to use these new lights on our spiky cactus!




2 comments:

  1. Hi Richard, that's a nice little and creative project! ;) How many LEDs do you have on each string? Are they solely powered via the GPIO header? Which GPIO pins are you using?
    Thx in advance, Alex

    ReplyDelete
  2. Thank you so much for this article. I had some of these led strings laying around as well. So dull. But you made it possible for me to change that.

    I had some difficulty activating the gpiozero modules. Found several different ways to do that and only one seems to have worked.
    Merry Christmas to you!

    ReplyDelete