Skip to content

Instantly share code, notes, and snippets.

@brandenhall
Created September 13, 2016 21:44
Show Gist options
  • Save brandenhall/8ce69e6a096cb39244283a8bb4e524bb to your computer and use it in GitHub Desktop.
Save brandenhall/8ce69e6a096cb39244283a8bb4e524bb to your computer and use it in GitHub Desktop.
Library for talking to APA102 "DotStar" RGB LED strips via SPI
"""
Library for talking to APA102 "DotStar" RGB LED strips via SPI
Requires external package spidev
Developed by Branden Hall (bhall@automatastudios.com)
"""
import math
import spidev
class APA102():
def __init__(self, bus, device, speed, num_leds):
"""
Initialize an LED strip
5000000 (5mHz) seems to work well on RPi2 for speed
"""
self.bus = bus
self.device = device
self.speed = speed
self.spi = spidev.SpiDev()
self.spi.open(self.bus, self.device)
self.spi.max_speed_hz = self.speed
self.num_leds = num_leds
self.header = [0, 0, 0, 0]
self.footer = [0, ] * int(math.ceil(self.num_leds / 16.0))
self.clear_state = self.header + [255, 0, 0, 0] * self.num_leds + self.footer
self.clear()
def clear(self):
""" Clear the strip """
self.data = self.clear_state[:]
def darken(self):
""" Darken the strip - good for fading out """
for i in range(self.num_leds):
index = 4 * (i + 1)
self.data[index + 1] >>= 1
self.data[index + 2] >>= 1
self.data[index + 3] >>= 1
def close(self):
""" Set all pixels to black and close hardware connection """
self.clear()
self.update()
self.spi.close()
def show_color(self, color):
"""
Set all pixes to specified color
color - tuple in (r, g, b) format
"""
self.data = self.header + [255, color[2], color[1], color[0]] * self.num_leds + self.footer
def add_color(self, pixel, color):
""" Add color to the specified pixel """
index = 4 * (pixel + 1)
self.data[index + 1] += min(255, color[2])
self.data[index + 2] += min(255, color[1])
self.data[index + 3] += min(255, color[0])
def get_pixel(self, pixel):
""" Get the color at the specified pixel """
if pixel > -1 and pixel < self.num_leds:
index = 4 * (pixel + 1)
return (self.data[index + 3], self.data[index + 2], self.data[index + 1])
else:
return None
def set_pixel(self, pixel, color):
""" Set the color at the specified pixel """
if pixel > -1 and pixel < self.num_leds:
index = 4 * (pixel + 1)
self.data[index + 1] = color[2]
self.data[index + 2] = color[1]
self.data[index + 3] = color[0]
def update(self):
""" Update the LEDs """
try:
self.spi.writebytes(self.data)
except:
self.spi.close()
self.spi = spidev.SpiDev()
self.spi.open(self.bus, self.device)
self.spi.max_speed_hz = self.speed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment