Actual code

This commit is contained in:
Skylten
2020-06-14 20:40:31 +02:00
parent 6ad76786b7
commit 205ccbce1d
53 changed files with 6897 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
*.pyc
*.so
build/
*.egg-info/
rpi_ws281x.py
rpi_ws281x_wrap.c
_rpi_ws281x.py
*.egg
*.zip
+49
View File
@@ -0,0 +1,49 @@
## Deprecated
This Python code is being phased out and replaced with https://github.com/rpi-ws281x/rpi-ws281x-python
If you're just looking to install the Python library, you can: `sudo pip install rpi_ws281x` or `sudo pip3 install rpi_ws281x` depending on your Python version of choice or find releases here: https://github.com/rpi-ws281x/rpi-ws281x-python/releases
For issues and bugs with (or contributions to) the Python library, please see: https://github.com/rpi-ws281x/rpi-ws281x-python/issues
----
## Build
As this is just a python wrapper for the library you must first follow
the build instructions in the parent directory.
When complete, you can build this python wrapper:
```
sudo apt-get install python-dev swig
python ./setup.py build
```
If you are rebuilding after fetching some updated commits, you might need to
remove the build directory first
```
rm -rf ./build
```
## Install
If you want to install the library (in a virtualenv or in the system), so that you can `import neopixel` from anywhere, you need to run:
```
python ./setup.py install
```
Depending on where you are installing, root privileges may be needed (prepend `sudo` to the install command).
## Run a demo
```
sudo PYTHONPATH=".:build/lib.linux-armv7l-2.7" python examples/strandtest.py
```
If you installed the library, there is no need to specify `PYTHONPATH`:
```
sudo python examples/strandtest.py
```
+75
View File
@@ -0,0 +1,75 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
# LED strip configuration:
LED_COUNT = 494 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
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 = 255 # 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
LED_STRIP = ws.SK6812_STRIP_RGBW
#LED_STRIP = ws.SK6812W_STRIP
class Led:
leds = []
def __init__(self, id, x, y):
self.x = x
self.y = y
Led.leds.append(self)
def colorFromIntensity(intensity):
#intensity should be 0-255
if intensity>20:
return Color(0,int(intensity),int(intensity/2),int(intensity/8)+20)
else:
return Color(0,0,0,20)
def intensityFromDistance(distance):
if distance<0:
return 0
intensity = 255-(distance/3)
if intensity < 0:
return 0
else:
return intensity
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
# Intialize the library (must be called once before other functions).
strip.begin()
print ('Press Ctrl-C to quit.')
with open("leds.txt", "r") as infile:
for line in infile:
entry = [int(x) for x in line.split(',')]
Led(entry[0], entry[1], entry[2])
# all LEDs now ready
edge = -500
t = 0
while True:
t+=1
for i, led in enumerate(Led.leds):
if t % 2 ==0:
strip.setPixelColor(i, Color(0b10101010,
0b10101010,
0b10101010,
0b10101010))
else:
strip.setPixelColor(i, Color(0,0,0,0))
strip.show()
time.sleep(1)
+221
View File
@@ -0,0 +1,221 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
import random
from neopixel import *
# LED strip configuration:
LED_COUNT = 494 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
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 = 255 # 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
LED_STRIP = ws.SK6812_STRIP_RGBW
#LED_STRIP = ws.SK6812W_STRIP
class Led:
leds = []
def __init__(self, id, x, y):
self.x = x
self.y = y
Led.leds.append(self)
class Star:
stars = []
def __init__(self):
self.starstate = 0
self.starBrightness = 0
self.starCountdown = 0
self.starLED = 50
Star.stars.append(self)
def update(self, strip):
if self.starstate == 0:
self.starBrightness += 3
if self.starBrightness > 120:
self.starstate = 1
if self.starstate == 1:
self.starBrightness -= self.starBrightness/100.0
if self.starBrightness < 5:
self.starstate = 2
self.starBrightness = 0
self.starCountdown = random.randint(100, 500)
if self.starstate == 2:
self.starCountdown -= 1
if self.starCountdown == 0:
self.starLED = 0
otherStars = [s.starLED for s in Star.stars]
goodPlace = False
while not goodPlace:
self.starLED = random.randint(0,493)
goodPlace = True
if self.starLED in range(236, 349):
goodPlace = False
if Led.leds[self.starLED].y < random.random():
goodPlace = False
for otherStar in otherStars:
if abs(self.starLED-otherStar)<4:
goodPlace = False
self.starstate = 0
brightness = int(self.starBrightness + (self.starBrightness * random.random())/20.0)
strip.setPixelColor(self.starLED, Color(0,0,int(brightness/2),brightness))
def wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def colorFromIntensity(intensity):
#intensity should be 0-255
if intensity>20:
return Color(0,intensity,intensity/2,intensity/8+20)
else:
return Color(0,0,0,20)
def intensityFromDistance(distance):
if distance<0:
return 0
intensity = 255-(distance/3)
if intensity < 0:
return 0
else:
return intensity
def turnOnChain(chain):
for light in chain:
strip.setPixelColor(light, Color(0,255,0,0))
strip.setPixelColor(light+1, Color(0,255,0,0))
strip.setPixelColor(light+2, Color(0,0,0,0))
strip.setPixelColor(light-1, Color(0,0,0,0))
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
# Intialize the library (must be called once before other functions).
strip.begin()
print ('Press Ctrl-C to quit.')
with open("leds.txt", "r") as infile:
for line in infile:
entry = [int(x) for x in line.split(',')]
Led(entry[0], entry[1], entry[2])
limits = [ min([l.x for l in Led.leds]), max([l.x for l in Led.leds]), min([l.y for l in Led.leds]), max([l.y for l in Led.leds])]
for l in Led.leds:
l.y = ( float(l.y - float(limits[3])) / (limits[2]-limits[3]) )
l.x = ( float(l.x - float(limits[0])) / (limits[3]-limits[2]) )
x_max = max([l.x for l in Led.leds])
print ("Maximum X: {}".format(x_max))
# all LEDs now ready
edge = -500
counter = 1
hider = 0
animation = 0
stars = []
for i in range(0, 10):
Star()
while True:
for i, led in enumerate(Led.leds):
# intensity = intensityFromDistance(edge-(led.x - led.y/3))
# strip.setPixelColor(i, colorFromIntensity(intensity))
# blueness = int(i/2)%25
if(i > 236 and i<349):
# Gör bokstaven A grön
strip.setPixelColor(i, Color(70,13,0,5))
else:
blueness = int((1.0-led.y)**3 * 60) if led.y>0.10 else 0
if blueness < 5:
blueness = 5
#redness = int((led.x / x_max)**2 * 255)
redness = int((1.0-led.y)**8 * 4)
strip.setPixelColor(i, Color(0,redness,blueness,0))
# strip.setPixelColor(440, Color(random.randint(68,72),random.randint(68,72),random.randint(68,72),random.randint(4,6)))
# lights = [257, 334, 283, 249, 290, 346, 299, 311, 242]
# for light in lights:
# strip.setPixelColor(light, Color(0,255,0,0))
# strip.setPixelColor(light+1, Color(0,255,0,0))
# strip.setPixelColor(light+2, Color(0,0,0,0))
# strip.setPixelColor(light-1, Color(0,0,0,0))
chain0 = [260, 274]
chain1 = [254, 334, 283]
chain2 = [247, 290, 346]
chain3 = [299, 314, 241]
strip.setPixelColor(264, Color(0,0,0,50))
strip.setPixelColor(265, Color(160,255,0, 20))
strip.setPixelColor(266, Color(160,255,0, 20))
strip.setPixelColor(267, Color(160,255,0, 20))
strip.setPixelColor(268, Color(0,0,0,50))
animation+=1
animation %= 400
if animation>= 0 and animation <50:
turnOnChain(chain0)
turnOnChain(chain2)
if animation >=50 and animation <100:
turnOnChain(chain1)
turnOnChain(chain2)
if animation >=100 and animation <150:
turnOnChain(chain1)
turnOnChain(chain3)
if animation >=150 and animation <200:
turnOnChain(chain2)
turnOnChain(chain3)
if animation >=200 and animation <250:
turnOnChain(chain0)
turnOnChain(chain2)
if animation >=250 and animation <300:
turnOnChain(chain0)
turnOnChain(chain3)
if animation >=300 and animation <350:
turnOnChain(chain1)
turnOnChain(chain3)
if animation >=350 and animation <400:
turnOnChain(chain1)
turnOnChain(chain0)
for star in Star.stars:
star.update(strip)
#time.sleep(0.05)
counter +=1
strip.show()
# edge+=10
# if edge>5000:
# edge = -500
# time.sleep(0.01)
+160
View File
@@ -0,0 +1,160 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import random
from neopixel import ws, Adafruit_NeoPixel, Color
# LED strip configuration:
LED_COUNT = 494 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 1200000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # Invert when using NPN transistor level shift
LED_CHANNEL = 0
LED_STRIP = ws.SK6812_STRIP_RGBW
class Led:
leds = []
def __init__(self, id, x, y):
self.x = x
self.y = y
Led.leds.append(self)
class Star:
stars = []
def __init__(self):
self.starstate = 0
self.starBrightness = 0
self.starCountdown = 0
self.starLED = 50
Star.stars.append(self)
def update(self, strip):
if self.starstate == 0:
self.starBrightness += 3
if self.starBrightness > 120:
self.starstate = 1
if self.starstate == 1:
self.starBrightness -= self.starBrightness/100.0
if self.starBrightness < 5:
self.starstate = 2
self.starBrightness = 0
self.starCountdown = random.randint(100, 500)
if self.starstate == 2:
self.starCountdown -= 1
if self.starCountdown == 0:
self.starLED = 0
otherStars = [s.starLED for s in Star.stars]
goodPlace = False
while not goodPlace:
self.starLED = random.randint(0, 493)
goodPlace = True
if Led.leds[self.starLED].y < random.random():
goodPlace = False
for otherStar in otherStars:
if abs(self.starLED-otherStar) < 4:
goodPlace = False
self.starstate = 0
brightness = int(self.starBrightness + (self.starBrightness * random.random())/20.0)
strip.setPixelColor(self.starLED, Color(0, 0, int(brightness/2), brightness))
def wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def colorFromIntensity(intensity):
# Intensity should be 0-255
if intensity > 20:
return Color(0, intensity, intensity/2, intensity/8+20)
else:
return Color(0, 0, 0, 20)
def intensityFromDistance(distance):
if distance < 0:
return 0
intensity = 255-(distance/3)
if intensity < 0:
return 0
else:
return intensity
def turnOnChain(chain):
for light in chain:
strip.setPixelColor(light, Color(0, 255, 0, 0))
strip.setPixelColor(light+1, Color(0, 255, 0, 0))
strip.setPixelColor(light+2, Color(0, 0, 0, 0))
strip.setPixelColor(light-1, Color(0, 0, 0, 0))
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,
LED_STRIP)
# Intialize the library (must be called once before other functions).
strip.begin()
print('Press Ctrl-C to quit.')
with open("leds.txt", "r") as infile:
for line in infile:
entry = [int(x) for x in line.split(',')]
Led(entry[0], entry[1], entry[2])
limits = [min([l.x for l in Led.leds]),
max([l.x for l in Led.leds]),
min([l.y for l in Led.leds]),
max([l.y for l in Led.leds])]
for l in Led.leds:
l.y = (float(l.y - float(limits[3])) / (limits[2]-limits[3]))
l.x = (float(l.x - float(limits[0])) / (limits[3]-limits[2]))
x_max = max([l.x for l in Led.leds])
print("Maximum X: {}".format(x_max))
# all LEDs now ready
edge = -500
counter = 1
hider = 0
animation = 0
stars = []
for i in range(0, 10):
Star()
while True:
for i, led in enumerate(Led.leds):
blueness = int((1.0-led.y)**3 * 60) if led.y > 0.10 else 0
if blueness < 5:
blueness = 5
redness = int((1.0-led.y)**8 * 4)
strip.setPixelColor(i, Color(0, redness, blueness, 0))
for star in Star.stars:
star.update(strip)
counter += 1
strip.show()
+160
View File
@@ -0,0 +1,160 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import random
from neopixel import ws, Adafruit_NeoPixel, Color
# LED strip configuration:
LED_COUNT = 494 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
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 = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # Invert when using NPN transistor level shift
LED_CHANNEL = 0
LED_STRIP = ws.SK6812_STRIP_RGBW
class Led:
leds = []
def __init__(self, id, x, y):
self.x = x
self.y = y
Led.leds.append(self)
class Star:
stars = []
def __init__(self):
self.starstate = 0
self.starBrightness = 0
self.starCountdown = 0
self.starLED = 50
Star.stars.append(self)
def update(self, strip):
if self.starstate == 0:
self.starBrightness += 3
if self.starBrightness > 120:
self.starstate = 1
if self.starstate == 1:
self.starBrightness -= self.starBrightness/100.0
if self.starBrightness < 5:
self.starstate = 2
self.starBrightness = 0
self.starCountdown = random.randint(100, 500)
if self.starstate == 2:
self.starCountdown -= 1
if self.starCountdown == 0:
self.starLED = 0
otherStars = [s.starLED for s in Star.stars]
goodPlace = False
while not goodPlace:
self.starLED = random.randint(0, 493)
goodPlace = True
if Led.leds[self.starLED].y < random.random():
goodPlace = False
for otherStar in otherStars:
if abs(self.starLED-otherStar) < 4:
goodPlace = False
self.starstate = 0
brightness = int(self.starBrightness + (self.starBrightness * random.random())/20.0)
strip.setPixelColor(self.starLED, Color(0, 0, int(brightness/2), brightness))
def wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def colorFromIntensity(intensity):
# Intensity should be 0-255
if intensity > 20:
return Color(0, intensity, intensity/2, intensity/8+20)
else:
return Color(0, 0, 0, 20)
def intensityFromDistance(distance):
if distance < 0:
return 0
intensity = 255-(distance/3)
if intensity < 0:
return 0
else:
return intensity
def turnOnChain(chain):
for light in chain:
strip.setPixelColor(light, Color(0, 255, 0, 0))
strip.setPixelColor(light+1, Color(0, 255, 0, 0))
strip.setPixelColor(light+2, Color(0, 0, 0, 0))
strip.setPixelColor(light-1, Color(0, 0, 0, 0))
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,
LED_STRIP)
# Intialize the library (must be called once before other functions).
strip.begin()
print('Press Ctrl-C to quit.')
with open("leds.txt", "r") as infile:
for line in infile:
entry = [int(x) for x in line.split(',')]
Led(entry[0], entry[1], entry[2])
limits = [min([l.x for l in Led.leds]),
max([l.x for l in Led.leds]),
min([l.y for l in Led.leds]),
max([l.y for l in Led.leds])]
for l in Led.leds:
l.y = (float(l.y - float(limits[3])) / (limits[2]-limits[3]))
l.x = (float(l.x - float(limits[0])) / (limits[3]-limits[2]))
x_max = max([l.x for l in Led.leds])
print("Maximum X: {}".format(x_max))
# all LEDs now ready
edge = -500
counter = 1
hider = 0
animation = 0
stars = []
for i in range(0, 10):
Star()
while True:
for i, led in enumerate(Led.leds):
blueness = int((1.0-led.y)**3 * 60) if led.y > 0.10 else 0
if blueness < 5:
blueness = 5
redness = int((1.0-led.y)**8 * 4)
strip.setPixelColor(i, Color(0, redness, blueness, 0))
for star in Star.stars:
star.update(strip)
counter += 1
strip.show()
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
sudo PYTHONPATH=".:build/lib.linux-armv7l-2.7" python3 animate.py
+82
View File
@@ -0,0 +1,82 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
# LED strip configuration:
LED_COUNT = 494 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
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 = 255 # 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
LED_STRIP = ws.SK6812_STRIP_RGBW
#LED_STRIP = ws.SK6812W_STRIP
class Led:
leds = []
def __init__(self, id, x, y):
self.x = x
self.y = y
Led.leds.append(self)
def wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def colorFromIntensity(intensity):
#intensity should be 0-255
if intensity>20:
return Color(int(intensity/2),int(intensity/2),int(intensity/2),max(int(intensity),20))
else:
return Color(0,0,0,20)
def intensityFromDistance(distance):
if distance<0:
return 0
intensity = 255-(distance/3)
if intensity < 0:
return 0
else:
return intensity
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
# Intialize the library (must be called once before other functions).
strip.begin()
print ('Press Ctrl-C to quit.')
with open("leds.txt", "r") as infile:
for line in infile:
entry = [int(x) for x in line.split(',')]
Led(entry[0], entry[1], entry[2])
# all LEDs now ready
edge = -500
while True:
# counter = 0
for i, led in enumerate(Led.leds):
intensity = intensityFromDistance(edge-(led.x - led.y/3))
strip.setPixelColor(i, colorFromIntensity(intensity))
strip.show()
edge+=10
if edge>5000:
edge = -500
# time.sleep(0.01)
+1
View File
@@ -0,0 +1 @@
aniamte_starrynight.py
+104
View File
@@ -0,0 +1,104 @@
# Example of low-level Python wrapper for rpi_ws281x library.
# Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net)
#
# This is an example of how to use the SWIG-generated _rpi_ws281x module.
# You probably don't want to use this unless you are building your own library,
# because the SWIG generated module is clunky and verbose. Instead look at the
# high level Python port of Adafruit's NeoPixel Arduino library in strandtest.py.
#
# This code will animate a number of WS281x LEDs displaying rainbow colors.
import time
import _rpi_ws281x as ws
# LED configuration.
LED_CHANNEL = 0
LED_COUNT = 16 # How many LEDs to light.
LED_FREQ_HZ = 800000 # Frequency of the LED signal. Should be 800khz or 400khz.
LED_DMA_NUM = 10 # DMA channel to use, can be 0-14.
LED_GPIO = 18 # GPIO connected to the LED signal line. Must support PWM!
LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = 0 # Set to 1 to invert the LED signal, good if using NPN
# transistor as a 3.3V->5V level converter. Keep at 0
# for a normal/non-inverted signal.
#LED_STRIP = ws.WS2811_STRIP_RGB
#LED_STRIP = ws.WS2811_STRIP_GBR
#LED_STRIP = ws.SK6812_STRIP_RGBW
LED_STRIP = ws.SK6812W_STRIP
# Define colors which will be used by the example. Each color is an unsigned
# 32-bit value where the lower 24 bits define the red, green, blue data (each
# being 8 bits long).
DOT_COLORS = [ 0x200000, # red
0x201000, # orange
0x202000, # yellow
0x002000, # green
0x002020, # lightblue
0x000020, # blue
0x100010, # purple
0x200010 ] # pink
# Create a ws2811_t structure from the LED configuration.
# Note that this structure will be created on the heap so you need to be careful
# that you delete its memory by calling delete_ws2811_t when it's not needed.
leds = ws.new_ws2811_t()
# Initialize all channels to off
for channum in range(2):
channel = ws.ws2811_channel_get(leds, channum)
ws.ws2811_channel_t_count_set(channel, 0)
ws.ws2811_channel_t_gpionum_set(channel, 0)
ws.ws2811_channel_t_invert_set(channel, 0)
ws.ws2811_channel_t_brightness_set(channel, 0)
channel = ws.ws2811_channel_get(leds, LED_CHANNEL)
ws.ws2811_channel_t_count_set(channel, LED_COUNT)
ws.ws2811_channel_t_gpionum_set(channel, LED_GPIO)
ws.ws2811_channel_t_invert_set(channel, LED_INVERT)
ws.ws2811_channel_t_brightness_set(channel, LED_BRIGHTNESS)
ws.ws2811_channel_t_strip_type_set(channel, LED_STRIP)
ws.ws2811_t_freq_set(leds, LED_FREQ_HZ)
ws.ws2811_t_dmanum_set(leds, LED_DMA_NUM)
# Initialize library with LED configuration.
resp = ws.ws2811_init(leds)
if resp != ws.WS2811_SUCCESS:
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, message))
# Wrap following code in a try/finally to ensure cleanup functions are called
# after library is initialized.
try:
offset = 0
while True:
# Update each LED color in the buffer.
for i in range(LED_COUNT):
# Pick a color based on LED position and an offset for animation.
color = DOT_COLORS[(i + offset) % len(DOT_COLORS)]
# Set the LED color buffer value.
ws.ws2811_led_set(channel, i, color)
# Send the LED color data to the hardware.
resp = ws.ws2811_render(leds)
if resp != ws.WS2811_SUCCESS:
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, message))
# Delay for a small period of time.
time.sleep(0.25)
# Increase offset to animate colors moving. Will eventually overflow, which
# is fine.
offset += 1
finally:
# Ensure ws2811_fini is called before the program quits.
ws.ws2811_fini(leds)
# Example of calling delete function to clean up structure memory. Isn't
# strictly necessary at the end of the program execution here, but is good practice.
ws.delete_ws2811_t(leds)
+107
View File
@@ -0,0 +1,107 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
# LED strip configuration:
LED_COUNT = 494 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
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 = 255 # 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
LED_STRIP = ws.SK6812_STRIP_RGBW
#LED_STRIP = ws.SK6812W_STRIP
# Define functions which animate LEDs in various ways.
def colorWipe(strip, color, wait_ms=15):
"""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=15, 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 wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def rainbow(strip, wait_ms=15, iterations=1):
"""Draw rainbow that fades across all pixels at once."""
for j in range(256*iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((i+j) & 255))
strip.show()
time.sleep(wait_ms/1000.0)
def rainbowCycle(strip, wait_ms=15, iterations=5):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256*iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel(((i * 256 // strip.numPixels()) + j) & 255))
strip.show()
time.sleep(wait_ms/1000.0)
def theaterChaseRainbow(strip, wait_ms=15):
"""Rainbow movie theater light style chaser animation."""
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, wheel((i+j) % 255))
strip.show()
time.sleep(wait_ms/1000.0)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, 0)
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
# Intialize the library (must be called once before other functions).
strip.begin()
print ('Press Ctrl-C to quit.')
while True:
# Color wipe animations.
colorWipe(strip, Color(255, 0, 0)) # Red wipe
colorWipe(strip, Color(0, 255, 0)) # Blue wipe
colorWipe(strip, Color(0, 0, 255)) # Green wipe
colorWipe(strip, Color(0, 0, 0, 255)) # White wipe
colorWipe(strip, Color(255, 255, 255)) # Composite White wipe
colorWipe(strip, Color(255, 255, 255, 255)) # Composite White + White LED wipe
# Theater chase animations.
theaterChase(strip, Color(127, 0, 0)) # Red theater chase
theaterChase(strip, Color(0, 127, 0)) # Green theater chase
theaterChase(strip, Color(0, 0, 127)) # Blue theater chase
theaterChase(strip, Color(0, 0, 0, 127)) # White theater chase
theaterChase(strip, Color(127, 127, 127, 0)) # Composite White theater chase
theaterChase(strip, Color(127, 127, 127, 127)) # Composite White + White theater chase
# Rainbow animations.
rainbow(strip)
rainbowCycle(strip)
theaterChaseRainbow(strip)
+52
View File
@@ -0,0 +1,52 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
# LED strip configuration:
LED_COUNT = 30 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
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 = 255 # 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
#LED_STRIP = ws.SK6812_STRIP_RGBW
LED_STRIP = ws.SK6812W_STRIP
# 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)
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
# Intialize the library (must be called once before other functions).
strip.begin()
print ('Press Ctrl-C to quit.')
while True:
# Color wipe animations.
colorWipe(strip, Color(255, 0, 0), 0) # Red wipe
time.sleep(2)
colorWipe(strip, Color(0, 255, 0), 0) # Blue wipe
time.sleep(2)
colorWipe(strip, Color(0, 0, 255), 0) # Green wipe
time.sleep(2)
colorWipe(strip, Color(0, 0, 0, 255), 0) # White wipe
time.sleep(2)
colorWipe(strip, Color(255, 255, 255), 0) # Composite White wipe
time.sleep(2)
colorWipe(strip, Color(255, 255, 255, 255), 0) # Composite White + White LED wipe
time.sleep(2)
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
# NeoPixel library light-painting example
# Author: Gary Servin (garyservin@gmail.com)
#
# Lightpainting example for displaying images one column at a time and capturing
# it by taking a long exposure photograph.
# Based on https://github.com/scottjgibson/PixelPi
import time
from neopixel import *
import argparse
# Button
import RPi.GPIO as GPIO
# Lightpainting
from PIL import Image
# LED strip configuration:
LED_COUNT = 128 # 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 = 255 # 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
BUTTON_CHANNEL = 19 # GPIO pin connected to the start button
def UnColor(color):
return ((color >> 24) & 0xFF , (color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)
def lightpaint(filename, frame_rate=100, column_rate=1, reverse_x=False, reverse_y=False, loop=False):
img = Image.open(filename).convert("RGB")
# Check that the height of the image is greater than or equal the number of LEDs on the strip
if(img.size[1] < LED_COUNT):
raise Exception("Image height is smaller than led strip size. Required height = {}".format(LED_COUNT))
elif(img.size[1] > LED_COUNT):
print "Resizing image"
new_width = LED_COUNT * img.size[0] / img.size[1]
img = img.resize((new_width, LED_COUNT), Image.ANTIALIAS)
input_image = img.load()
image_width = img.size[0]
column = [0 for x in range(image_width)]
for x in range(image_width):
column[x] = [None] * (LED_COUNT)
for x in range(image_width):
for y in range(LED_COUNT):
value = input_image[x, y]
column[x][y] = Color(value[1], value[0], value[2])
while True:
# Wait for button to be pressed before displaying image
if not loop:
print("Waiting for button to be pressed")
GPIO.wait_for_edge(BUTTON_CHANNEL, GPIO.FALLING)
time.sleep(0.5)
x_range = range(image_width)
if reverse_x:
x_range.reverse()
y_range = range(LED_COUNT)
if reverse_y:
y_range.reverse()
for x in x_range:
led_pos = 0
for y in y_range:
strip.setPixelColor(led_pos, column[x][y])
led_pos += 1
strip.show()
time.sleep(column_rate / 1000.0)
# Wait for `frame_rate` ms before drawing a new frame
time.sleep(frame_rate / 1000.0)
# 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)
# 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')
parser.add_argument('-f', '--file', action='store', help='Filename to display')
parser.add_argument('-r', '--frame_rate', action='store', default=100, help='Rate between each frame. Defines how fast a new frame is displayed')
parser.add_argument('-l', '--column_rate', action='store', default=1, help='Rate between each column. Defines how fast or slow you need to move the stick')
parser.add_argument('-b', '--brightness', action='store', default=10, help='Brightness of the LED. Set to 0 for darkest and 255 for brightest')
parser.add_argument('-x', '--reverse_x', action='store_true', help='Reverse the image in the X direction')
parser.add_argument('-y', '--reverse_y', action='store_true', help='Reverse the image in the Y direction')
parser.add_argument('--loop', action='store_true', help='Play frames in a loop')
args = parser.parse_args()
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, args.brightness, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()
# Button
GPIO.setmode(GPIO.BOARD)
GPIO.setup(BUTTON_CHANNEL, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print ('Press Ctrl-C to quit.')
if not args.clear:
print('Use "-c" argument to clear LEDs on exit')
try:
while True:
print ('Lightpaint.')
lightpaint(args.file, float(args.frame_rate), float(args.column_rate), args.reverse_x, args.reverse_y, args.loop)
except KeyboardInterrupt:
if args.clear:
colorWipe(strip, Color(0,0,0), 10)
GPIO.cleanup()
+98
View File
@@ -0,0 +1,98 @@
# Example of low-level Python wrapper for rpi_ws281x library.
# Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net)
#
# This is an example of how to use the SWIG-generated _rpi_ws281x module.
# You probably don't want to use this unless you are building your own library,
# because the SWIG generated module is clunky and verbose. Instead look at the
# high level Python port of Adafruit's NeoPixel Arduino library in strandtest.py.
#
# This code will animate a number of WS281x LEDs displaying rainbow colors.
import time
import _rpi_ws281x as ws
# LED configuration.
LED_CHANNEL = 0
LED_COUNT = 16 # How many LEDs to light.
LED_FREQ_HZ = 800000 # Frequency of the LED signal. Should be 800khz or 400khz.
LED_DMA_NUM = 10 # DMA channel to use, can be 0-14.
LED_GPIO = 18 # GPIO connected to the LED signal line. Must support PWM!
LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = 0 # Set to 1 to invert the LED signal, good if using NPN
# transistor as a 3.3V->5V level converter. Keep at 0
# for a normal/non-inverted signal.
# Define colors which will be used by the example. Each color is an unsigned
# 32-bit value where the lower 24 bits define the red, green, blue data (each
# being 8 bits long).
DOT_COLORS = [ 0x200000, # red
0x201000, # orange
0x202000, # yellow
0x002000, # green
0x002020, # lightblue
0x000020, # blue
0x100010, # purple
0x200010 ] # pink
# Create a ws2811_t structure from the LED configuration.
# Note that this structure will be created on the heap so you need to be careful
# that you delete its memory by calling delete_ws2811_t when it's not needed.
leds = ws.new_ws2811_t()
# Initialize all channels to off
for channum in range(2):
channel = ws.ws2811_channel_get(leds, channum)
ws.ws2811_channel_t_count_set(channel, 0)
ws.ws2811_channel_t_gpionum_set(channel, 0)
ws.ws2811_channel_t_invert_set(channel, 0)
ws.ws2811_channel_t_brightness_set(channel, 0)
channel = ws.ws2811_channel_get(leds, LED_CHANNEL)
ws.ws2811_channel_t_count_set(channel, LED_COUNT)
ws.ws2811_channel_t_gpionum_set(channel, LED_GPIO)
ws.ws2811_channel_t_invert_set(channel, LED_INVERT)
ws.ws2811_channel_t_brightness_set(channel, LED_BRIGHTNESS)
ws.ws2811_t_freq_set(leds, LED_FREQ_HZ)
ws.ws2811_t_dmanum_set(leds, LED_DMA_NUM)
# Initialize library with LED configuration.
resp = ws.ws2811_init(leds)
if resp != ws.WS2811_SUCCESS:
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, message))
# Wrap following code in a try/finally to ensure cleanup functions are called
# after library is initialized.
try:
offset = 0
while True:
# Update each LED color in the buffer.
for i in range(LED_COUNT):
# Pick a color based on LED position and an offset for animation.
color = DOT_COLORS[(i + offset) % len(DOT_COLORS)]
# Set the LED color buffer value.
ws.ws2811_led_set(channel, i, color)
# Send the LED color data to the hardware.
resp = ws.ws2811_render(leds)
if resp != ws.WS2811_SUCCESS:
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, message))
# Delay for a small period of time.
time.sleep(0.25)
# Increase offset to animate colors moving. Will eventually overflow, which
# is fine.
offset += 1
finally:
# Ensure ws2811_fini is called before the program quits.
ws.ws2811_fini(leds)
# Example of calling delete function to clean up structure memory. Isn't
# strictly necessary at the end of the program execution here, but is good practice.
ws.delete_ws2811_t(leds)
+78
View File
@@ -0,0 +1,78 @@
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
# LED strip configuration:
LED_1_COUNT = 30 # Number of LED pixels.
LED_1_PIN = 18 # GPIO pin connected to the pixels (must support PWM! GPIO 13 and 18 on RPi 3).
LED_1_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_1_DMA = 10 # DMA channel to use for generating signal (Between 1 and 14)
LED_1_BRIGHTNESS = 128 # Set to 0 for darkest and 255 for brightest
LED_1_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_1_CHANNEL = 0 # 0 or 1
LED_1_STRIP = ws.SK6812_STRIP_GRBW
LED_2_COUNT = 15 # Number of LED pixels.
LED_2_PIN = 13 # GPIO pin connected to the pixels (must support PWM! GPIO 13 or 18 on RPi 3).
LED_2_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_2_DMA = 11 # DMA channel to use for generating signal (Between 1 and 14)
LED_2_BRIGHTNESS = 128 # Set to 0 for darkest and 255 for brightest
LED_2_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_2_CHANNEL = 1 # 0 or 1
LED_2_STRIP = ws.WS2811_STRIP_GRB
def multiColorWipe(color1, color2, wait_ms=5):
global strip1
global strip2
"""Wipe color across multiple LED strips a pixel at a time."""
for i in range(strip1.numPixels()):
if i % 2:
# even number
strip1.setPixelColor(i, color1)
strip2.setPixelColor(i / 2, color2)
strip1.show()
time.sleep(wait_ms/1000.0)
strip2.show()
time.sleep(wait_ms/1000.0)
else:
# odd number
strip1.setPixelColor(i, color1)
strip1.show()
time.sleep(wait_ms/1000.0)
time.sleep(1)
def blackout(strip):
for i in range(max(strip1.numPixels(), strip1.numPixels())):
strip.setPixelColor(i, Color(0,0,0))
strip.show()
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel objects with appropriate configuration for each strip.
strip1 = Adafruit_NeoPixel(LED_1_COUNT, LED_1_PIN, LED_1_FREQ_HZ, LED_1_DMA, LED_1_INVERT, LED_1_BRIGHTNESS, LED_1_CHANNEL, LED_1_STRIP)
strip2 = Adafruit_NeoPixel(LED_2_COUNT, LED_2_PIN, LED_2_FREQ_HZ, LED_2_DMA, LED_2_INVERT, LED_2_BRIGHTNESS, LED_2_CHANNEL, LED_2_STRIP)
# Intialize the library (must be called once before other functions).
strip1.begin()
strip2.begin()
print ('Press Ctrl-C to quit.')
# Black out any LEDs that may be still on for the last run
blackout(strip1)
blackout(strip2)
while True:
# Multi Color wipe animations.
multiColorWipe(Color(255, 0, 0), Color(255, 0, 0)) # Red wipe
multiColorWipe(Color(0, 255, 0), Color(0, 255, 0)) # Blue wipe
multiColorWipe(Color(0, 0, 255), Color(0, 0, 255)) # Green wipe
multiColorWipe(Color(255, 255, 255), Color(255, 255, 255)) # Composite White wipe
multiColorWipe(Color(0, 0, 0, 255), Color(0, 0, 0)) # White wipe
multiColorWipe(Color(255, 255, 255, 255), Color(0, 0, 0)) # Composite White + White LED wipe
+72
View File
@@ -0,0 +1,72 @@
# Based on NeoPixel library and strandtest example by Tony DiCola (tony@tonydicola.com)
# To be used with a 12x1 NeoPixel LED stripe.
# Place the LEDs in a circle an watch the time go by ...
# red = hours
# blue = minutes 1-5
# green = seconds
# (To run the program permanently and with autostart use systemd.)
import time
import datetime
import math
from neopixel import *
# LED strip configuration:
LED_COUNT = 12 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
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 = 255 # Set to 0 for darkest and 255 for brightest
# True to invert the signal (when using NPN transistor level shift)
LED_INVERT = False
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(
LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
# Intialize the library (must be called once before other functions).
strip.begin()
for i in range(0, strip.numPixels(), 1):
strip.setPixelColor(i, Color(0, 0, 0))
while True:
now = datetime.datetime.now()
# Low light during 19-8 o'clock
if(8 < now.hour < 19):
strip.setBrightness(200)
else:
strip.setBrightness(25)
hour = now.hour % 12
minute = now.minute / 5
second = now.second / 5
secondmodulo = now.second % 5
timeslot_in_microseconds = secondmodulo * 1000000 + now.microsecond
for i in range(0, strip.numPixels(), 1):
secondplusone = second + 1 if(second < 11) else 0
secondminusone = second - 1 if(second > 0) else 11
colorarray = [0, 0, 0]
if i == second:
if timeslot_in_microseconds < 2500000:
colorarray[0] = int(
0.0000508 * timeslot_in_microseconds) + 126
else:
colorarray[0] = 382 - \
int(0.0000508 * timeslot_in_microseconds)
if i == secondplusone:
colorarray[0] = int(0.0000256 * timeslot_in_microseconds)
if i == secondminusone:
colorarray[0] = int(
0.0000256 * timeslot_in_microseconds) * -1 + 128
if i == minute:
colorarray[2] = 200
if i == hour:
colorarray[1] = 200
strip.setPixelColor(
i, Color(colorarray[0], colorarray[1], colorarray[2]))
strip.show()
time.sleep(0.1)
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from neopixel import *
import argparse
# LED strip configuration:
LED_COUNT = 16 # 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 = 255 # 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 wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def rainbow(strip, wait_ms=20, iterations=1):
"""Draw rainbow that fades across all pixels at once."""
for j in range(256*iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((i+j) & 255))
strip.show()
time.sleep(wait_ms/1000.0)
def rainbowCycle(strip, wait_ms=20, iterations=5):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256*iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))
strip.show()
time.sleep(wait_ms/1000.0)
def theaterChaseRainbow(strip, wait_ms=50):
"""Rainbow movie theater light style chaser animation."""
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, wheel((i+j) % 255))
strip.show()
time.sleep(wait_ms/1000.0)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, 0)
# 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()
# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(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 ('Press Ctrl-C to quit.')
if not args.clear:
print('Use "-c" argument to clear LEDs on exit')
try:
while True:
print ('Color wipe animations.')
colorWipe(strip, Color(255, 0, 0)) # Red wipe
colorWipe(strip, Color(0, 255, 0)) # Blue wipe
colorWipe(strip, Color(0, 0, 255)) # Green wipe
print ('Theater chase animations.')
theaterChase(strip, Color(127, 127, 127)) # White theater chase
theaterChase(strip, Color(127, 0, 0)) # Red theater chase
theaterChase(strip, Color( 0, 0, 127)) # Blue theater chase
print ('Rainbow animations.')
rainbow(strip)
rainbowCycle(strip)
theaterChaseRainbow(strip)
except KeyboardInterrupt:
if args.clear:
colorWipe(strip, Color(0,0,0), 10)
+332
View File
@@ -0,0 +1,332 @@
#!/usr/bin/env python
"""Bootstrap setuptools installation
To use setuptools in your package's setup.py, include this
file in the same directory and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
To require a specific version of setuptools, set a download
mirror, or use an alternate download directory, simply supply
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib
from distutils import log
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
try:
from site import USER_SITE
except ImportError:
USER_SITE = None
DEFAULT_VERSION = "5.7"
DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
def _python_cmd(*args):
"""
Return True if the command succeeded.
"""
args = (sys.executable,) + args
return subprocess.call(args) == 0
def _install(archive_filename, install_args=()):
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
def _build_egg(egg, archive_filename, to_dir):
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
class ContextualZipFile(zipfile.ZipFile):
"""
Supplement ZipFile class to support context manager for Python 2.6
"""
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __new__(cls, *args, **kwargs):
"""
Construct a ZipFile or ContextualZipFile as appropriate
"""
if hasattr(zipfile.ZipFile, '__exit__'):
return zipfile.ZipFile(*args, **kwargs)
return super(ContextualZipFile, cls).__new__(cls)
@contextlib.contextmanager
def archive_context(filename):
# extracting the archive
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
with ContextualZipFile(filename) as archive:
archive.extractall()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
yield
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir)
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
if not os.path.exists(egg):
archive = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, archive, to_dir)
sys.path.insert(0, egg)
# Remove previously-imported pkg_resources if present (see
# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
if 'pkg_resources' in sys.modules:
del sys.modules['pkg_resources']
import setuptools
setuptools.bootstrap_install_from = egg
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15):
to_dir = os.path.abspath(to_dir)
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir, download_delay)
except pkg_resources.VersionConflict as VC_err:
if imported:
msg = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""").format(VC_err=VC_err, version=version)
sys.stderr.write(msg)
sys.exit(2)
# otherwise, reload ok
del pkg_resources, sys.modules['pkg_resources']
return _do_download(version, download_base, to_dir, download_delay)
def _clean_check(cmd, target):
"""
Run the command to download target. If the command fails, clean up before
re-raising the error.
"""
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
if os.access(target, os.F_OK):
os.unlink(target)
raise
def download_file_powershell(url, target):
"""
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
"""
target = os.path.abspath(target)
ps_cmd = (
"[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
"[System.Net.CredentialCache]::DefaultCredentials; "
"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"
% vars()
)
cmd = [
'powershell',
'-Command',
ps_cmd,
]
_clean_check(cmd, target)
def has_powershell():
if platform.system() != 'Windows':
return False
cmd = ['powershell', '-Command', 'echo test']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_powershell.viable = has_powershell
def download_file_curl(url, target):
cmd = ['curl', '-L', url, '--silent', '--output', target]
_clean_check(cmd, target)
def has_curl():
cmd = ['curl', '--version']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_curl.viable = has_curl
def download_file_wget(url, target):
cmd = ['wget', url, '--quiet', '--output-document', target]
_clean_check(cmd, target)
def has_wget():
cmd = ['wget', '--version']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_wget.viable = has_wget
def download_file_insecure(url, target):
"""
Use Python to download the file, even though it cannot authenticate the
connection.
"""
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial file.
with open(target, "wb") as dst:
dst.write(data)
download_file_insecure.viable = lambda: True
def get_best_downloader():
downloaders = (
download_file_powershell,
download_file_curl,
download_file_wget,
download_file_insecure,
)
viable_downloaders = (dl for dl in downloaders if dl.viable())
return next(viable_downloaders, None)
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader):
"""
Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an sdist for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
``downloader_factory`` should be a function taking no arguments and
returning a function for downloading a URL to a target.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
zip_name = "setuptools-%s.zip" % version
url = download_base + zip_name
saveto = os.path.join(to_dir, zip_name)
if not os.path.exists(saveto): # Avoid repeated downloads
log.warn("Downloading %s", url)
downloader = downloader_factory()
downloader(url, saveto)
return os.path.realpath(saveto)
def _build_install_args(options):
"""
Build the arguments to 'python setup.py install' on the setuptools package
"""
return ['--user'] if options.user_install else []
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package (requires Python 2.6 or later)')
parser.add_option(
'--download-base', dest='download_base', metavar="URL",
default=DEFAULT_URL,
help='alternative URL from where to download the setuptools package')
parser.add_option(
'--insecure', dest='downloader_factory', action='store_const',
const=lambda: download_file_insecure, default=get_best_downloader,
help='Use internal, non-validating downloader'
)
parser.add_option(
'--version', help="Specify which version to download",
default=DEFAULT_VERSION,
)
options, args = parser.parse_args()
# positional arguments are ignored
return options
def main():
"""Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
archive = download_setuptools(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
)
return _install(archive, _build_install_args(options))
if __name__ == '__main__':
sys.exit(main())
+494
View File
@@ -0,0 +1,494 @@
0,63,408
1,57,397
2,55,387
3,50,374
4,44,356
5,41,343
6,42,330
7,42,320
8,41,308
9,41,298
10,42,286
11,41,273
12,41,264
13,41,253
14,41,239
15,41,230
16,40,219
17,40,209
18,43,192
19,49,176
20,52,164
21,57,151
22,61,143
23,64,141
24,76,136
25,89,132
26,102,128
27,115,126
28,126,126
29,137,126
30,148,126
31,159,126
32,170,128
33,182,129
34,193,128
35,203,128
36,214,128
37,226,128
38,236,129
39,249,128
40,259,126
41,272,125
42,287,128
43,299,131
44,312,135
45,323,137
46,333,141
47,334,148
48,335,164
49,336,177
50,336,190
51,334,205
52,334,209
53,324,211
54,316,213
55,305,216
56,292,219
57,279,220
58,264,221
59,251,220
60,241,221
61,230,221
62,219,221
63,207,221
64,199,221
65,193,221
66,187,222
67,181,222
68,180,222
69,180,223
70,179,224
71,180,224
72,185,224
73,192,224
74,199,223
75,206,224
76,218,224
77,228,224
78,244,226
79,260,230
80,272,233
81,283,235
82,293,237
83,304,238
84,305,243
85,305,253
86,305,267
87,305,282
88,309,293
89,301,300
90,293,301
91,284,302
92,270,306
93,257,310
94,241,315
95,229,316
96,217,315
97,206,316
98,199,316
99,192,316
100,187,316
101,181,316
102,183,317
103,182,318
104,182,319
105,186,319
106,189,319
107,197,319
108,203,319
109,211,319
110,223,319
111,234,319
112,244,318
113,255,318
114,269,318
115,280,317
116,296,318
117,307,320
118,321,322
119,330,325
120,339,329
121,345,335
122,348,346
123,349,362
124,349,376
125,349,391
126,344,401
127,334,405
128,322,408
129,310,412
130,295,416
131,280,419
132,270,420
133,259,419
134,248,420
135,238,421
136,227,419
137,215,419
138,205,419
139,193,419
140,182,419
141,171,419
142,160,419
143,149,419
144,138,420
145,127,420
146,115,420
147,103,419
148,86,416
149,73,414
150,391,397
151,388,389
152,382,374
153,378,360
154,375,348
155,374,336
156,374,324
157,374,313
158,374,302
159,373,291
160,373,279
161,373,267
162,372,256
163,372,243
164,372,234
165,372,222
166,371,212
167,371,201
168,374,185
169,378,170
170,382,156
171,385,145
172,391,135
173,402,132
174,417,128
175,434,125
176,454,127
177,467,129
178,479,133
179,490,137
180,499,142
181,502,154
182,506,166
183,508,178
184,511,192
185,511,204
186,512,216
187,512,227
188,513,239
189,513,249
190,511,263
191,513,273
192,513,281
193,514,288
194,514,294
195,514,300
196,513,305
197,519,306
198,526,305
199,533,305
200,540,305
201,550,305
202,561,304
203,573,305
204,583,305
205,596,306
206,613,310
207,624,312
208,636,315
209,647,318
210,655,322
211,658,334
212,658,347
213,659,362
214,657,378
215,656,393
216,645,399
217,633,404
218,622,408
219,606,412
220,591,415
221,580,416
222,571,416
223,559,417
224,548,417
225,537,417
226,524,417
227,514,417
228,502,417
229,491,418
230,480,418
231,470,417
232,459,417
233,448,417
234,434,415
235,420,412
236,405,407
237,685,392
238,686,380
239,686,369
240,686,354
241,689,339
242,693,326
243,696,316
244,701,305
245,706,295
246,710,285
247,714,275
248,718,264
249,723,253
250,727,243
251,732,232
252,736,223
253,741,211
254,745,202
255,749,191
256,754,181
257,760,169
258,768,157
259,776,145
260,783,135
261,795,128
262,804,125
263,817,122
264,832,119
265,844,117
266,855,115
267,869,116
268,885,118
269,898,120
270,912,123
271,922,125
272,935,136
273,942,145
274,951,158
275,958,170
276,964,182
277,969,193
278,973,203
279,978,214
280,982,224
281,987,236
282,991,246
283,996,257
284,1000,267
285,1004,276
286,1009,288
287,1013,298
288,1018,309
289,1022,320
290,1026,331
291,1028,348
292,1029,363
293,1030,376
294,1030,389
295,1028,399
296,1018,401
297,1006,404
298,991,408
299,977,414
300,959,414
301,946,412
302,933,411
303,920,409
304,913,405
305,907,400
306,898,394
307,888,393
308,879,392
309,871,391
310,862,390
311,852,391
312,843,392
313,835,393
314,825,394
315,814,395
316,805,398
317,801,403
318,791,412
319,783,410
320,770,412
321,757,414
322,742,415
323,723,409
324,711,405
325,699,403
326,688,399
327,852,285
328,855,280
329,855,277
330,855,275
331,854,273
332,855,268
333,855,263
334,856,255
335,857,255
336,857,260
337,858,267
338,858,273
339,858,275
340,857,277
341,857,279
342,859,284
343,859,287
344,857,286
345,856,286
346,856,286
347,855,286
348,853,288
349,1069,389
350,1065,376
351,1062,363
352,1059,348
353,1057,335
354,1057,323
355,1057,311
356,1058,299
357,1058,288
358,1058,277
359,1057,267
360,1058,252
361,1058,242
362,1059,232
363,1058,224
364,1058,207
365,1058,197
366,1059,184
367,1061,171
368,1064,158
369,1068,144
370,1071,131
371,1079,124
372,1090,121
373,1103,117
374,1114,114
375,1131,110
376,1146,108
377,1158,107
378,1169,108
379,1182,108
380,1194,109
381,1206,109
382,1218,110
383,1230,110
384,1239,112
385,1253,112
386,1266,114
387,1277,111
388,1289,108
389,1302,108
390,1316,108
391,1329,109
392,1341,111
393,1355,115
394,1369,120
395,1383,128
396,1395,137
397,1403,148
398,1409,162
399,1413,177
400,1413,196
401,1413,212
402,1413,223
403,1411,231
404,1406,239
405,1402,245
406,1397,249
407,1403,252
408,1407,255
409,1412,261
410,1414,269
411,1416,279
412,1418,292
413,1420,309
414,1420,327
415,1416,348
416,1413,361
417,1407,372
418,1399,383
419,1388,393
420,1374,400
421,1361,405
422,1349,408
423,1334,411
424,1320,412
425,1308,413
426,1296,414
427,1283,414
428,1271,414
429,1259,414
430,1247,413
431,1234,413
432,1222,413
433,1211,413
434,1200,414
435,1188,413
436,1176,413
437,1164,413
438,1152,413
439,1140,413
440,1125,411
441,1109,407
442,1096,403
443,1083,399
444,1072,396
445,1205,307
446,1207,306
447,1207,304
448,1206,303
449,1205,302
450,1210,300
451,1215,300
452,1221,301
453,1229,302
454,1237,300
455,1247,300
456,1255,302
457,1260,302
458,1265,303
459,1268,303
460,1270,305
461,1269,306
462,1266,307
463,1261,307
464,1254,307
465,1246,307
466,1237,307
467,1228,307
468,1223,307
469,1217,307
470,1210,307
471,1206,211
472,1207,209
473,1207,207
474,1207,206
475,1212,206
476,1218,206
477,1224,207
478,1231,207
479,1238,206
480,1245,206
481,1251,206
482,1256,207
483,1261,207
484,1264,208
485,1263,209
486,1259,209
487,1253,214
488,1247,213
489,1239,212
490,1231,210
491,1224,211
492,1217,214
493,1212,214
+151
View File
@@ -0,0 +1,151 @@
# Adafruit NeoPixel library port to the rpi_ws281x library.
# Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net)
import atexit
import _rpi_ws281x as ws
def Color(red, green, blue, white = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (red << 16)| (green << 8) | blue
class _LED_Data(object):
"""Wrapper class which makes a SWIG LED color data array look and feel like
a Python list of integers.
"""
def __init__(self, channel, size):
self.size = size
self.channel = channel
def __getitem__(self, pos):
"""Return the 24-bit RGB color value at the provided position or slice
of positions.
"""
# Handle if a slice of positions are passed in by grabbing all the values
# and returning them in a list.
if isinstance(pos, slice):
return [ws.ws2811_led_get(self.channel, n) for n in xrange(*pos.indices(self.size))]
# Else assume the passed in value is a number to the position.
else:
return ws.ws2811_led_get(self.channel, pos)
def __setitem__(self, pos, value):
"""Set the 24-bit RGB color value at the provided position or slice of
positions.
"""
# Handle if a slice of positions are passed in by setting the appropriate
# LED data values to the provided values.
if isinstance(pos, slice):
index = 0
for n in xrange(*pos.indices(self.size)):
ws.ws2811_led_set(self.channel, n, value[index])
index += 1
# Else assume the passed in value is a number to the position.
else:
return ws.ws2811_led_set(self.channel, pos, value)
class Adafruit_NeoPixel(object):
def __init__(self, num, pin, freq_hz=800000, dma=10, invert=False,
brightness=255, channel=0, strip_type=ws.WS2811_STRIP_RGB):
"""Class to represent a NeoPixel/WS281x LED display. Num should be the
number of pixels in the display, and pin should be the GPIO pin connected
to the display signal line (must be a PWM pin like 18!). Optional
parameters are freq, the frequency of the display signal in hertz (default
800khz), dma, the DMA channel to use (default 10), invert, a boolean
specifying if the signal line should be inverted (default False), and
channel, the PWM channel to use (defaults to 0).
"""
# Create ws2811_t structure and fill in parameters.
self._leds = ws.new_ws2811_t()
# Initialize the channels to zero
for channum in range(2):
chan = ws.ws2811_channel_get(self._leds, channum)
ws.ws2811_channel_t_count_set(chan, 0)
ws.ws2811_channel_t_gpionum_set(chan, 0)
ws.ws2811_channel_t_invert_set(chan, 0)
ws.ws2811_channel_t_brightness_set(chan, 0)
# Initialize the channel in use
self._channel = ws.ws2811_channel_get(self._leds, channel)
ws.ws2811_channel_t_count_set(self._channel, num)
ws.ws2811_channel_t_gpionum_set(self._channel, pin)
ws.ws2811_channel_t_invert_set(self._channel, 0 if not invert else 1)
ws.ws2811_channel_t_brightness_set(self._channel, brightness)
ws.ws2811_channel_t_strip_type_set(self._channel, strip_type)
# Initialize the controller
ws.ws2811_t_freq_set(self._leds, freq_hz)
ws.ws2811_t_dmanum_set(self._leds, dma)
# Grab the led data array.
self._led_data = _LED_Data(self._channel, num)
# Substitute for __del__, traps an exit condition and cleans up properly
atexit.register(self._cleanup)
def _cleanup(self):
# Clean up memory used by the library when not needed anymore.
if self._leds is not None:
ws.delete_ws2811_t(self._leds)
self._leds = None
self._channel = None
def begin(self):
"""Initialize library, must be called once before other functions are
called.
"""
resp = ws.ws2811_init(self._leds)
if resp != ws.WS2811_SUCCESS:
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, message))
def show(self):
"""Update the display with the data from the LED buffer."""
resp = ws.ws2811_render(self._leds)
if resp != ws.WS2811_SUCCESS:
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, message))
def setPixelColor(self, n, color):
"""Set LED at position n to the provided 24-bit color value (in RGB order).
"""
self._led_data[n] = color
def setPixelColorRGB(self, n, red, green, blue, white = 0):
"""Set LED at position n to the provided red, green, and blue color.
Each color component should be a value from 0 to 255 (where 0 is the
lowest intensity and 255 is the highest intensity).
"""
self.setPixelColor(n, Color(red, green, blue, white))
def setBrightness(self, brightness):
"""Scale each LED in the buffer by the provided brightness. A brightness
of 0 is the darkest and 255 is the brightest.
"""
ws.ws2811_channel_t_brightness_set(self._channel, brightness)
def getBrightness(self):
"""Get the brightness value for each LED in the buffer. A brightness
of 0 is the darkest and 255 is the brightest.
"""
return ws.ws2811_channel_t_brightness_get(self._channel)
def getPixels(self):
"""Return an object which allows access to the LED display data as if
it were a sequence of 24-bit RGB values.
"""
return self._led_data
def numPixels(self):
"""Return the number of pixels in the display."""
return ws.ws2811_channel_t_count_get(self._channel)
def getPixelColor(self, n):
"""Get the 24-bit RGB color value for the LED at position n."""
return self._led_data[n]
View File
+26
View File
@@ -0,0 +1,26 @@
For overclocing needs, the pulse times MEASURED on the sign were:
0:
high: 294ns
low: 954ns
1:
high: 626ns
low: 618ns
The HIGH pulse times are always the same, the LOW pulse times are shortened by increasing frequency
Current speed 800Khz
494 LED theoretical maximum framerate:
1/((494*32)/800000 + 80e-6) = 50.4Hz :(
925KHz is still fully in spec of the LEDs and provides:
58.2Hz
955KHz is only slightly out of spec and proviced a smooth
60.1fps
+48
View File
@@ -0,0 +1,48 @@
// SWIG interface file to define rpi_ws281x library python wrapper.
// Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net)
// Define module name rpi_ws281x. This will actually be imported under
// the name _rpi_ws281x following the SWIG & Python conventions.
%module rpi_ws281x
// Include standard SWIG types & array support for support of uint32_t
// parameters and arrays.
%include "stdint.i"
%include "carrays.i"
// Declare functions which will be exported as anything in the ws2811.h header.
%{
#include "../ws2811.h"
%}
// Process ws2811.h header and export all included functions.
%include "../ws2811.h"
%inline %{
uint32_t ws2811_led_get(ws2811_channel_t *channel, int lednum)
{
if (lednum >= channel->count)
{
return -1;
}
return channel->leds[lednum];
}
int ws2811_led_set(ws2811_channel_t *channel, int lednum, uint32_t color)
{
if (lednum >= channel->count)
{
return -1;
}
channel->leds[lednum] = color;
return 0;
}
ws2811_channel_t *ws2811_channel_get(ws2811_t *ws, int channelnum)
{
return &ws->channel[channelnum];
}
%}
+18
View File
@@ -0,0 +1,18 @@
# Python wrapper for the rpi_ws281x library.
# Author: Tony DiCola (tony@tonydicola.com)
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages, Extension
setup(name = 'rpi_ws281x',
version = '1.0.0',
author = 'Jeremy Garff',
author_email = 'jer@jers.net',
description = 'Userspace Raspberry Pi PWM library for WS281X LEDs.',
license = 'MIT',
url = 'https://github.com/jgarff/rpi_ws281x/',
py_modules = ['neopixel'],
ext_modules = [Extension('_rpi_ws281x',
sources=['rpi_ws281x.i'],
library_dirs=['../.'],
libraries=['ws2811', 'rt'])])