Techno Blender
Digitally Yours.

Program Christmas Lights with Python | by Katy Hagerty | Dec, 2022

0 45


Photo by Thalia Ruiz on Unsplash

The holiday season has officially kicked off, which means plenty of shopping, baking, and of course decorating. Home improvement stores stock dozens and dozens of lights all with different shapes, colors, and special effects. But have you ever wanted to create your own holiday lights with custom colors and motions? A few simple lines of Python make that possible.

Image by author. See Results section for full demo.

This is my first Raspberry Pi project and I’m thrilled to share it with you before the holidays. I used a Raspberry Pi to control individually addressable LED strips. Unlike typical holiday lights, these strips allow custom inputs for each LED. Links to the materials are listed below.

WS2812B light emitting diodes (LED) are individually addressable LEDs, making it possible to program individual LEDs. The strip has 3 cables running to each LED:

  1. Negative power line/ground (black)
  2. Positive power line (red)
  3. Data line (green)

This brand of LED strip forked the power lines (red and black cables) to make it easier to connect to a separate power supply. Even though there are 5 cables at the end, there are only 3 paths.

Image by author.

The other end of the strip has a male connector which allows other LEDs strips to be added in series. However, adding more strips can cause overheating if there isn’t sufficient power.

  1. LED Lights. I used two 5 meter WS2812B strips. However, any WS281X LEDs should be compatible with the rpi-ws281x library.
  2. Raspberry Pi. I used a Raspberry Pi 3 but any Raspberry Pi with a ground and GPIO 18 pin will work.
  3. Male-to-female jumper cables
  4. Power Supply
  5. Wire strippers (optional)

Before starting, make sure both the Raspberry Pi and the external power supply are disconnected.

  1. Use a jumper cable to connect the LED strips ground cable (black) to a ground pin on the Raspberry Pi. The diagram below uses Pin 6 as ground.
  2. Use a jumper cable to connect the LED strip data line (green) to GPIO 18 on the Raspberry Pi. On the Raspberry Pi 3, GPIO 18 is Pin 12.
  3. Connect the LED strip to the external power supply using the connector piece. You may need to strip off some insulation from the power lines.
  4. Power on Raspberry and external power supply.
Image from https://www.raspberrypi.com/documentation/computers/raspberry-pi.html (CC BY-SA 4.0). Highlights made by author.

The following instructions assume the Raspberry Pi has the Raspian OS installed. Run the code on the Raspberry Pi terminal.

I recommend using a headless Raspberry Pi setup which will allows you to remotely access the Raspberry Pi. However, it is not necessary.

Update System

  1. Update existing packages
sudo apt-get update

2. Install git on Raspberry Pi

sudo apt install git

3. Deactivate audio by editing the following file

sudo nano /etc/modprobe.d/snd-blacklist.conf

4. Add the following line to the open file. Press Ctrl-O and Ctrl-X to save and close.

blacklist snd_bcm2835

5. Use the nano editor to open the config file.

sudo nano /boot/config.txt

6. Use Ctrl-W to search the file. Add a # to comment out the following line.

#dtparam=audio=on

7. Restart the Raspberry Pi to ensure all changes take effect.

sudo reboot

Install and Test Library

  1. Clone the library.
git clone https://github.com/rpi-ws281x/rpi-ws281x-python.git

2. Edit the input parameters in the test file.

sudo nano rpi-ws281x-python/examples/strandtest.py

My setup includes two strips of 150 LEDs for a total of 300 LEDs. LED_COUNT is the only variable I need to change.

# LED strip configuration:
LED_COUNT = 300 # Number of LED pixels.

Use Ctrl-O and Ctrl-X to save and close the file.

3. Test the setup!

sudo python3 rpi-ws281x-python/examples/strandtest.py

Customize Lights

To customize my lights, I copied strandtest.py from the rpi-ws281x-python library to create xmas.py.

# Change directory
cd rpi-ws281x-python/examples

# Copy strandtest.py and name copy xmas.py
cp strandtest.py xmas.py

This allowed me to modify existing functions and create new ones without overwriting strandtest.py. In xmas.py, I added a feature where all the lights turn off for keyboard interruptions (Ctrl-C) or if the script runs to completion. When run to completion, the script takes a little under 4 hours.

                                                      
#!/usr/bin/env python3

import time
from rpi_ws281x import PixelStrip, Color
import argparse
import numpy

# LED strip configuration:
LED_COUNT = 300 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
# LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 75 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53

# Define functions which animate LEDs in various ways.
def colorWipe(strip, color, wait_ms=50):
"""Wipe color across display a pixel at a time."""
for i in range(strip.numPixels()):
strip.setPixelColor(i, color)
strip.show()
time.sleep(wait_ms / 1000.0)

def theaterChase(strip, color, wait_ms=50, iterations=10):
"""Movie theater light style chaser animation."""
for j in range(iterations):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, color)
strip.show()
time.sleep(wait_ms / 1000.0)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, 0)

def candyCane(strip, red_start):
for i in range(strip.numPixels()):
strip.setPixelColor(i, Color(255,255,255))
for i in range(strip.numPixels()):
if i % 10 == red_start or i == 10:
for j in range(i, i + 5):
strip.setPixelColor(j, Color(255, 0, 0))
strip.show()

def candyCaneMoving(strip, iterations):
i = 0
for iter in range(iterations):
candyCane(strip,i)
if i < 9:
i += 1
else: i = 0
time.sleep(1)

# Main program logic follows:
if __name__ == '__main__':
# Process arguments
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
args = parser.parse_args()

try:
# Create NeoPixel object with appropriate configuration.
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()

print('Color wipe animations.')
candyCaneMoving(strip, 3600)
colorWipe(strip, Color(127,127,127))

LED_BRIGHTNESS = 255
# Create NeoPixel object with appropriate configuration
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()
theaterChase(strip,Color(127,0,0),1000,1000)
theaterChase(strip,Color(0,127,0),1000,1000)
theaterChase(strip,Color(127,127,127),1000,1000)
colorWipe(strip, Color(255, 0, 0)) # Red wipe
time.sleep(600)
colorWipe(strip, Color(0, 255, 0)) # Green wipe
time.sleep(600)
colorWipe(strip, Color(0, 0, 0), 10)

except KeyboardInterrupt:
colorWipe(strip, Color(0, 0, 0), 10)

Schedule Task

I wanted my lights to turn on every night without user input so I scheduled a task with Cron. Cron comes with the Raspberry Pi Raspian operating system.

  1. Open the table of Cron jobs in editor mode.
crontab -e

Choose an editor. I recommend nano.

2. Add the task to the file.

0 17 * * * sudo python3 ~/rpi-ws281x-pi/examples/xmas.py

Cron jobs follow the format [minute] [hour] [day of month] [month] [day of week] [command to execute]. The * means any value so Cron will execute the command for all the values in that field. The job above will run at 5 pm (aka 17:00) every day of every month.

Demo of the functions in xmas.py

“Connect and Control WS2812 RGB LED Strips via Raspberry Pi.” Tutorials for Raspberry Pi. https://tutorials-raspberrypi.com/connect-control-raspberry-pi-ws2812-rgb-led-strips/

“Beginners Guide to Cron Jobs and Crontab.” PiMyLifeUp. https://pimylifeup.com/cron-jobs-and-crontab/

Thank you for reading about my first Raspberry Pi project. If you have any questions, please reach out or leave a comment. I’m more than happy to help. Also, I’d love to hear what patterns you’d like to see for future LED projects.

Thank you for reading my article. If you like my content, follow me or join Medium.

Connect with me on LinkedIn, Twitter, or Instagram.

All feedback is welcome. I am always eager to learn new or better ways of doing things.

Feel free to leave a comment or reach out to me at [email protected].




Photo by Thalia Ruiz on Unsplash

The holiday season has officially kicked off, which means plenty of shopping, baking, and of course decorating. Home improvement stores stock dozens and dozens of lights all with different shapes, colors, and special effects. But have you ever wanted to create your own holiday lights with custom colors and motions? A few simple lines of Python make that possible.

Image by author. See Results section for full demo.

This is my first Raspberry Pi project and I’m thrilled to share it with you before the holidays. I used a Raspberry Pi to control individually addressable LED strips. Unlike typical holiday lights, these strips allow custom inputs for each LED. Links to the materials are listed below.

WS2812B light emitting diodes (LED) are individually addressable LEDs, making it possible to program individual LEDs. The strip has 3 cables running to each LED:

  1. Negative power line/ground (black)
  2. Positive power line (red)
  3. Data line (green)

This brand of LED strip forked the power lines (red and black cables) to make it easier to connect to a separate power supply. Even though there are 5 cables at the end, there are only 3 paths.

Image by author.

The other end of the strip has a male connector which allows other LEDs strips to be added in series. However, adding more strips can cause overheating if there isn’t sufficient power.

  1. LED Lights. I used two 5 meter WS2812B strips. However, any WS281X LEDs should be compatible with the rpi-ws281x library.
  2. Raspberry Pi. I used a Raspberry Pi 3 but any Raspberry Pi with a ground and GPIO 18 pin will work.
  3. Male-to-female jumper cables
  4. Power Supply
  5. Wire strippers (optional)

Before starting, make sure both the Raspberry Pi and the external power supply are disconnected.

  1. Use a jumper cable to connect the LED strips ground cable (black) to a ground pin on the Raspberry Pi. The diagram below uses Pin 6 as ground.
  2. Use a jumper cable to connect the LED strip data line (green) to GPIO 18 on the Raspberry Pi. On the Raspberry Pi 3, GPIO 18 is Pin 12.
  3. Connect the LED strip to the external power supply using the connector piece. You may need to strip off some insulation from the power lines.
  4. Power on Raspberry and external power supply.
Image from https://www.raspberrypi.com/documentation/computers/raspberry-pi.html (CC BY-SA 4.0). Highlights made by author.

The following instructions assume the Raspberry Pi has the Raspian OS installed. Run the code on the Raspberry Pi terminal.

I recommend using a headless Raspberry Pi setup which will allows you to remotely access the Raspberry Pi. However, it is not necessary.

Update System

  1. Update existing packages
sudo apt-get update

2. Install git on Raspberry Pi

sudo apt install git

3. Deactivate audio by editing the following file

sudo nano /etc/modprobe.d/snd-blacklist.conf

4. Add the following line to the open file. Press Ctrl-O and Ctrl-X to save and close.

blacklist snd_bcm2835

5. Use the nano editor to open the config file.

sudo nano /boot/config.txt

6. Use Ctrl-W to search the file. Add a # to comment out the following line.

#dtparam=audio=on

7. Restart the Raspberry Pi to ensure all changes take effect.

sudo reboot

Install and Test Library

  1. Clone the library.
git clone https://github.com/rpi-ws281x/rpi-ws281x-python.git

2. Edit the input parameters in the test file.

sudo nano rpi-ws281x-python/examples/strandtest.py

My setup includes two strips of 150 LEDs for a total of 300 LEDs. LED_COUNT is the only variable I need to change.

# LED strip configuration:
LED_COUNT = 300 # Number of LED pixels.

Use Ctrl-O and Ctrl-X to save and close the file.

3. Test the setup!

sudo python3 rpi-ws281x-python/examples/strandtest.py

Customize Lights

To customize my lights, I copied strandtest.py from the rpi-ws281x-python library to create xmas.py.

# Change directory
cd rpi-ws281x-python/examples

# Copy strandtest.py and name copy xmas.py
cp strandtest.py xmas.py

This allowed me to modify existing functions and create new ones without overwriting strandtest.py. In xmas.py, I added a feature where all the lights turn off for keyboard interruptions (Ctrl-C) or if the script runs to completion. When run to completion, the script takes a little under 4 hours.

                                                      
#!/usr/bin/env python3

import time
from rpi_ws281x import PixelStrip, Color
import argparse
import numpy

# LED strip configuration:
LED_COUNT = 300 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
# LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 75 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53

# Define functions which animate LEDs in various ways.
def colorWipe(strip, color, wait_ms=50):
"""Wipe color across display a pixel at a time."""
for i in range(strip.numPixels()):
strip.setPixelColor(i, color)
strip.show()
time.sleep(wait_ms / 1000.0)

def theaterChase(strip, color, wait_ms=50, iterations=10):
"""Movie theater light style chaser animation."""
for j in range(iterations):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, color)
strip.show()
time.sleep(wait_ms / 1000.0)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, 0)

def candyCane(strip, red_start):
for i in range(strip.numPixels()):
strip.setPixelColor(i, Color(255,255,255))
for i in range(strip.numPixels()):
if i % 10 == red_start or i == 10:
for j in range(i, i + 5):
strip.setPixelColor(j, Color(255, 0, 0))
strip.show()

def candyCaneMoving(strip, iterations):
i = 0
for iter in range(iterations):
candyCane(strip,i)
if i < 9:
i += 1
else: i = 0
time.sleep(1)

# Main program logic follows:
if __name__ == '__main__':
# Process arguments
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
args = parser.parse_args()

try:
# Create NeoPixel object with appropriate configuration.
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()

print('Color wipe animations.')
candyCaneMoving(strip, 3600)
colorWipe(strip, Color(127,127,127))

LED_BRIGHTNESS = 255
# Create NeoPixel object with appropriate configuration
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()
theaterChase(strip,Color(127,0,0),1000,1000)
theaterChase(strip,Color(0,127,0),1000,1000)
theaterChase(strip,Color(127,127,127),1000,1000)
colorWipe(strip, Color(255, 0, 0)) # Red wipe
time.sleep(600)
colorWipe(strip, Color(0, 255, 0)) # Green wipe
time.sleep(600)
colorWipe(strip, Color(0, 0, 0), 10)

except KeyboardInterrupt:
colorWipe(strip, Color(0, 0, 0), 10)

Schedule Task

I wanted my lights to turn on every night without user input so I scheduled a task with Cron. Cron comes with the Raspberry Pi Raspian operating system.

  1. Open the table of Cron jobs in editor mode.
crontab -e

Choose an editor. I recommend nano.

2. Add the task to the file.

0 17 * * * sudo python3 ~/rpi-ws281x-pi/examples/xmas.py

Cron jobs follow the format [minute] [hour] [day of month] [month] [day of week] [command to execute]. The * means any value so Cron will execute the command for all the values in that field. The job above will run at 5 pm (aka 17:00) every day of every month.

Demo of the functions in xmas.py

“Connect and Control WS2812 RGB LED Strips via Raspberry Pi.” Tutorials for Raspberry Pi. https://tutorials-raspberrypi.com/connect-control-raspberry-pi-ws2812-rgb-led-strips/

“Beginners Guide to Cron Jobs and Crontab.” PiMyLifeUp. https://pimylifeup.com/cron-jobs-and-crontab/

Thank you for reading about my first Raspberry Pi project. If you have any questions, please reach out or leave a comment. I’m more than happy to help. Also, I’d love to hear what patterns you’d like to see for future LED projects.

Thank you for reading my article. If you like my content, follow me or join Medium.

Connect with me on LinkedIn, Twitter, or Instagram.

All feedback is welcome. I am always eager to learn new or better ways of doing things.

Feel free to leave a comment or reach out to me at [email protected].

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment