The default program suggested for the PiHut Christmas Tree makes the lights flash rapidly, all at once. This was headache inducing, so I modded the code to provide me with something a bit more relaxing. My Pi has trouble setting one of the GPIO pins high (it’ll go high once, turn off, and then flicker weakly after that), but beyond that, this works a charm.

The general idea is to take a sine wave, remove the negative values (since a LED won’t light at -5V), and put a cap on the brightness when going positive. This code isn’t the only way, but it works pretty nicely.

#!/usr/bin/python3

from gpiozero import LEDBoard
from gpiozero.tools import random_values
from signal import pause
from typing import Generator
import math
import random
import time


def quux(start: float, stop: float, step: float) -> Generator:
    while True:
        time.sleep(random.random())
        x = start
        while x < stop:
            tx = math.sin(x)
            if tx < 0: 
                x += step
                yield 0
            elif tx > 0.3:
                yield 0.3
            else:
                yield tx
            x += step


tree = LEDBoard(*range(2,28), pwm=True)
for led in tree:
    led.source_delay = 0.1
    led.source = quux(0, 2 * math.pi, 0.05)

pause()

Stepping larger than 0.05 means pretty noticeable jumps in the lighting level of the LEDs, but it also means that the cap and dark periods last fairly long, hence the increment inside the dark period to double the stepping.

For reference, this is the PiHut’s code:


from gpiozero import LEDBoard
from gpiozero.tools import random_values
from signal import pause
tree = LEDBoard(*range(2,28),pwm=True)
for led in tree:
 led.source_delay = 0.1
 led.source = random_values()
pause()
Driving a PiHut Christmas Tree
Tagged on: