Created
May 22, 2016 01:06
-
-
Save ivazqueznet/fde087bf3dbbef877a7ef3aecf9d8870 to your computer and use it in GitHub Desktop.
USB WS2812B Python control script
This file contains 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
#!/usr/bin/python | |
import sys | |
import random | |
import time | |
import struct | |
import usb1 | |
USB_GET_VERSION = 0 | |
USB_SET_LED_COUNT = 1 | |
USB_SET_LED_RGB = 2 | |
USB_UPDATE_LEDS = 3 | |
NUMLEDS = 8 | |
STANDARD_COLORS = ( | |
'\0\0\0', | |
'\xff\0\0', | |
'\0\xff\0', | |
'\xff\xff\0', | |
'\0\0\xff', | |
'\xff\0\xff', | |
'\0\xff\xff', | |
'\xff\xff\xff', | |
) | |
context = usb1.USBContext() | |
devicelist = context.getDeviceList(skip_on_error=True) | |
handle = None | |
for device in devicelist: | |
try: | |
if device.getProduct() == u'usbled': | |
handle = device.open() | |
break | |
except usb1.USBErrorAccess: | |
pass | |
else: | |
raise RuntimeError('usbled not found!') | |
try: | |
verraw = handle.controlRead(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_GET_VERSION, 0, 0, 2) | |
version = struct.unpack('H', verraw)[0] | |
if version < 0x0100: | |
raise RuntimeError('Version of usbled (0x%4h) not supported!' | |
% (version,)) | |
handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_SET_LED_COUNT, NUMLEDS, 0, '') | |
for c in STANDARD_COLORS: | |
for ix in range(NUMLEDS): | |
handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_SET_LED_RGB, 0, ix, c) | |
handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_UPDATE_LEDS, 0, 0, '') | |
time.sleep(0.3) | |
time.sleep(2) | |
while True: | |
for i in range(len(STANDARD_COLORS)): | |
for ix, color in enumerate(STANDARD_COLORS): | |
if (i + ix) % len(STANDARD_COLORS) < NUMLEDS: | |
handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_SET_LED_RGB, 0, (i + ix) % len(STANDARD_COLORS), color) | |
handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_UPDATE_LEDS, 0, 0, '') | |
time.sleep(0.05) | |
except KeyboardInterrupt: | |
for x in range(NUMLEDS): | |
handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_SET_LED_RGB, 0, x, '\0\0\0') | |
handle.controlWrite(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, | |
USB_UPDATE_LEDS, 0, 0, '') | |
finally: | |
handle.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment