Created
April 27, 2013 09:27
-
-
Save redspider/5472485 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time, os | |
try: | |
import RPi.GPIO as GPIO | |
except ImportError: | |
GPIO = None | |
class Color(object): | |
def __init__(self, r, g, b): | |
self.r = r | |
self.g = g | |
self.b = b | |
def as_int(self): | |
return ((self.r & 0xFF) << 16) | ((self.g & 0xFF) << 8) | (self.b & 0xFF) | |
class Lights(object): | |
def __init__(self, pixel_count, mode="hardware"): | |
self.pixels = [Color(0 ,0 ,0)] * pixel_count | |
self.mode = mode | |
if not GPIO: | |
print "Cannot render hardware, no GPIO module, rendering screen" | |
self.mode = "screen" | |
def set(self, offset, color): | |
self.pixels[offset] = color | |
def render(self): | |
if self.mode == "hardware": | |
spidev = file("/dev/spidev0.0", "w") | |
for i in range(len(self.pixels)): | |
spidev.write(chr((self.pixels[i].as_int() >> 16) & 0xFF)) | |
spidev.write(chr((self.pixels[i].as_int() >> 8) & 0xFF)) | |
spidev.write(chr(self.pixels[i].as_int() & 0xFF)) | |
spidev.close() | |
time.sleep(0.002) | |
else: | |
line = "" | |
for i in range(len(self.pixels)): | |
line += "%02x" % self.pixels[i].r | |
print line | |
time.sleep(0.002) | |
class KittEffect(object): | |
def __init__(self, lights): | |
self.lights = lights | |
self.pos = 0 | |
self.vector = 1 | |
self.brightness = [0] * len(lights.pixels) | |
self.fade_speed = 16 | |
def step(self): | |
if self.pos >= len(self.brightness)-1: | |
self.pos = len(self.brightness) - 1 | |
self.vector = -1 | |
if self.pos <= 0: | |
self.pos = 0 | |
self.vector = 1 | |
self.pos += self.vector | |
for i,v in enumerate(self.brightness): | |
if v > self.fade_speed: | |
self.brightness[i] -= self.fade_speed | |
else: | |
self.brightness[i] = 0 | |
self.brightness[self.pos] = 255 | |
for i,v in enumerate(self.brightness): | |
self.lights.set(i, Color(v,0,0)) | |
self.lights.render() | |
def loop(self): | |
while True: | |
self.step() | |
time.sleep(0.05) | |
lights = Lights(40, "screen") | |
kitt = KittEffect(lights) | |
kitt.loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment