class PiWS281X(DriverBase): """ Driver for controlling WS281X LEDs via the rpi_ws281x C-extension. Only supported on the Raspberry Pi 2 & 3 """ def __init__(self, num, gamma=gamma.NEOPIXEL, c_order=ChannelOrder.RGB, gpio=18, ledFreqHz=800000, ledDma=5, ledInvert=False, **kwds): """ num - Number of LED pixels. gpio - GPIO pin connected to the pixels (must support PWM! GPIO 13 or 18 (pins 33 or 12) on RPi 3). ledFreqHz - LED signal frequency in hertz (800khz or 400khz) ledDma - DMA channel to use for generating signal (Between 1 and 14) ledInvert - True to invert the signal (when using NPN transistor level shift) """ super().__init__(num, c_order=c_order, gamma=gamma, **kwds) self.gamma = gamma self._strip = Adafruit_NeoPixel(num, gpio, ledFreqHz, ledDma, ledInvert, 255, 0, 0x081000) # Intialize the library (must be called once before other functions). self._strip.begin() def set_brightness(self, brightness): self._strip.setBrightness(brightness) return True def _compute_packet(self): self._render() data = self._buf self._packet = [tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3)] def _send_packet(self): for i, p in enumerate(self._packet): self._strip.setPixelColor(i, NeoColor(*p)) self._strip.show()
class LEDStrip(object): def __init__(self, array: TileArray): from neopixel import Adafruit_NeoPixel # Create NeoPixel object with appropriate configuration. self.strip = Adafruit_NeoPixel(array.size(), LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) # Intialize the library (must be called once before other functions). self.strip.begin() self.array = array def draw(self, image: np.ndarray, delay: float = 0.001): """ Draws a matrix of color values to the dancefloor tiles. Handles the math of calculating what pixels correspond to which LEDs in the chain of LED strips. The input image should have a shape of (height, width, 3) where height is the LEDs in the vertical direction and width is the total LEDs in the horizontal direction. :param image: Matrix of colors to display on the dancefloor :param delay: Seconds to wait after finishing writing to the LED strips """ from neopixel import Color start = time.time() for y in range(image.shape[0]): for x in range(image.shape[1]): idx = self.array.index(x, y) r = int(image[y][x][0]) g = int(image[y][x][1]) b = int(image[y][x][2]) color = Color(g, r, b) self.strip.setPixelColor(idx, color) self.strip.show() end = time.time() delta = end - start if delay > delta: time.sleep(delay - delta)
def init_strip(): strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) strip.begin() logging.info('neopixel LED strip initialized') return strip
class NeoPixels(object): LED_COUNT = 256 # Number of LED pixels. LED_PIN = 21 # GPIO pin connected to the pixels (must support PWM!). 18=PWM, 21=PCM, 10=SPI-MOSI LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 5 # DMA channel to use for generating signal (try 5) 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) def __init__(self): from neopixel import Adafruit_NeoPixel as NeoPixel self._pixels = NeoPixel(num=self.LED_COUNT, pin=self.LED_PIN, freq_hz=self.LED_FREQ_HZ, dma=self.LED_DMA, invert=self.LED_INVERT, brightness=self.LED_BRIGHTNESS) try: self._pixels.begin() _logger.info("Initialized NeoPixel OK") except RuntimeError: _logger.error("Failed to initialize NeoPixels") raise self.write_pixels(np.zeros((16, 16, 3))) def write_pixels(self, data): for y, row in enumerate((data * 255).astype(np.uint8)): for x, color in enumerate(row): self._pixels.setPixelColorRGB(y * 16 + x, *color) self._pixels.show()
class StripController: def __init__(self): self.ledCount_ = 100 self.height_ = 10 self.neopixel_ = Adafruit_NeoPixel( self.ledCount_, # LED count 18, # LED pin 800000, # LED signal frequency (Hz) 10, # DMA channel False, # Invert signal 100, # Brightness (0, 255) 0) # LED channel self.neopixel_.begin() def set(self, index, color): if index >= self.ledCount_: raise Exception('setting out of bounds pixel', index) self.neopixel_.setPixelColor(index, color) def show(self): self.neopixel_.show() def cleanUpGrid(self): width = self.ledCount_ / self.height_ return [[BLACK] * width] * self.height_
class LEDStripPWM(LEDStrip): def __init__(self, array: TileArray): super().__init__(array) from neopixel import Adafruit_NeoPixel # Create NeoPixel object with appropriate configuration. self.strip = Adafruit_NeoPixel(array.size(), LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) # Intialize the library (must be called once before other functions). self.strip.begin() def draw(self, image: np.ndarray, delay: float = 0.001): from neopixel import Color start = time.time() for y in range(image.shape[0]): for x in range(image.shape[1]): idx = self.array.index(x, y) r = int(image[y][x][0]) g = int(image[y][x][1]) b = int(image[y][x][2]) color = Color(g, r, b) self.strip.setPixelColor(idx, color) self.strip.show() end = time.time() delta = end - start if delay > delta: time.sleep(delay - delta)
class DriverPiWS281X(DriverBase): def __init__(self, num, gamma=gamma.NEOPIXEL, c_order=ChannelOrder.RGB, ledPin=18, ledFreqHz=800000, ledDma=5, ledInvert=False): """ num - Number of LED pixels. ledPin - GPIO pin connected to the pixels (must support PWM! pin 13 or 18 on RPi 3). ledFreqHz - LED signal frequency in hertz (800khz or 400khz) ledDma - DMA channel to use for generating signal (Between 1 and 14) ledInvert - True to invert the signal (when using NPN transistor level shift) """ super(DriverPiWS281X, self).__init__(num, c_order=c_order, gamma=gamma) self.gamma = gamma self._strip = Adafruit_NeoPixel(num, ledPin, ledFreqHz, ledDma, ledInvert, 255, 0, 0x081000) # Intialize the library (must be called once before other functions). self._strip.begin() # Set Brightness of the strip. A brightness of 0 is the darkest and 255 is # the brightest def setMasterBrightness(self, brightness): self._strip.setBrightness(brightness) # Push new data def update(self, data): # handle channel order and gamma correction self._fixData(data) data = self._buf pixels = [tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) / 3)] for i in range(len(data) / 3): self._strip.setPixelColor(i, NeoColor(pixels[i][0], pixels[i][1], pixels[i][2])) self._strip.show()
class NeoPixelRenderer(Renderer): def __init__(self, led_dma=10, led_strip=ws.WS2811_STRIP_GRB): super(NeoPixelRenderer, self).__init__() self.led_dma = 10 self.led_strip = led_strip self.strip = None def setup(self, pixel_count, world): super(NeoPixelRenderer, self).setup(pixel_count, world) self.strip = Adafruit_NeoPixel( pixel_count, LED_PIN, LED_FREQ_HZ, self.led_dma, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, self.led_strip) self.strip.begin() self.log.debug("LED strip initialized") for idx in range(0, pixel_count): self.strip.setPixelColorRGB(idx, 0, 0, 0, 0) self.strip.show() self.log.debug("LED strip cleared") def render_buffer(self, pixel_buffer): super(NeoPixelRenderer, self).render_buffer(pixel_buffer) if self._is_buffer_changed(pixel_buffer): for idx, pixel in enumerate(pixel_buffer): self.strip.setPixelColorRGB(idx, int(pixel.r), int(pixel.g), int(pixel.b)) # , int(pixel.w)) self.strip.show()
class Matrix: def __init__(self): # LED strip configuration: self.led_count = 256 # Number of LED pixels. self.led_pin = 18 # GPIO pin connected to the pixels (18 uses PWM!). self.led_freq_hz = 800000 # LED signal frequency in hertz (usually 800khz) self.led_dma = 10 # DMA channel to use for generating signal (try 10) self.led_brightness = 15 # Set to 0 for darkest and 255 for brightest self.led_invert = False # True to invert the signal (when using NPN transistor level shift) self.led_channel = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 self.matrix = Adafruit_NeoPixel(self.led_count, self.led_pin, self.led_freq_hz, self.led_dma, self.led_invert, self.led_brightness, self.led_channel) self.matrix.begin() self.frame = Frame(rows=8, cols=32) def color_wipe(self, color: Color = Color()): for x, y, pixel in self.frame.fill(): pixel.color = color def display_text(self, color: Color = Color(), row_1=""): t = Text(row_1) t = t.array for i in range(self.frame.cols()): for x, y, pixel in self.frame.fill(): if t[x][y]: pixel.color = color def scrolling_text(self, color: Color = Color(), repetitions=1, row_1="", row_2=""): t = Text(row_1) t = t.array for rep in range(repetitions): for i in range(len(t)): for x, y, pixel in self.frame.fill(): if t[y][x]: pixel.color = color self.render() t[i].append(t[i].pop(0)) time.sleep(1) self.cleanup() def render(self): for position, color in self.frame.canvas(): self.matrix.setPixelColor(position, color) self.matrix.show() def cleanup(self): self.color_wipe()
class LEDStrip: axis = None green = None red = None blue = None neopixel_Object = None LED_COUNT = 38 # Number of LED pixels. LED_PIN = None # GPIO pin connected to the pixels (18 uses 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 # set to '1' for GPIOs 13, 19, 41, 45 or 53 limitHeight = LED_COUNT def __init__(self, axis, GPIO_Pin, LED_COUNT=38, LED_FREQ_HZ=800000, LED_DMA=10, LED_BRIGHTNESS=255, LED_INVERT=False, LED_CHANNEL=0): print("Initializing LED Strip on GPIO Pin " + str(GPIO_Pin)) from neopixel import Adafruit_NeoPixel self.LED_COUNT = LED_COUNT self.LED_PIN = GPIO_Pin self.LED_FREQ_HZ = LED_FREQ_HZ self.LED_DMA = LED_DMA self.LED_BRIGHTNESS = LED_BRIGHTNESS self.LED_INVERT = LED_INVERT self.LED_CHANNEL = LED_CHANNEL self.green = 0 self.red = 0 self.blue = 0 self.neopixel_Object = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS, self.LED_CHANNEL) self.neopixel_Object.begin() updateColorsThread = Thread(target=self.updateColors) updateColorsThread.start() print("Started updateColors Thread") def updateColors(self): oldGreen = self.green oldRed = self.red oldBlue = self.blue limit = 40 while True: if self.green != oldGreen or self.red != oldRed or self.blue != oldBlue: oldGreen = self.green oldRed = self.red oldBlue = self.blue print("Green: " + "{:>3}".format(str(self.green)) + ", Red: " + "{:>3}".format( str(self.red)) + ", Blue: " + "{:>3}".format(str(self.blue)) + "\n") color = Color(self.green, self.red, self.blue) for i in range(self.neopixel_Object.numPixels()): if i < self.limitHeight: self.neopixel_Object.setPixelColor(i, color) self.neopixel_Object.show() time.sleep(50 / 1000.0)
class Led_Array(object): def __init__(self): self.LED_COUNT = 256 # Number of LED pixels. self.LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). self.LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) self.LED_DMA = 5 # DMA channel to use for generating signal (try 5) self.LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest self.LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) self.ROW_WIDTH = 8 # Number of LEDs in each row of the array # Create NeoPixel object with appropriate configuration. self.led_array = Adafruit_NeoPixel( self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS) # Intialize the library (must be called once before other functions). self.led_array.begin() def _info(self): return self.LED_COUNT, self.LED_PIN, self.LED_BRIGHTNESS, self.ROW_WIDTH def setRowColor(self, row_number, color): strip = self.led_array start = 0 + row_number*self.ROW_WIDTH end = start + self.ROW_WIDTH for i in range(start, end): strip.setPixelColor(i, color) # strip.show() def fill_up_to(self, row, color): #strip = self.led_array for i in range(row+1): self.setRowColor(i,color) def empty_array(self): strip = self.led_array for i in range(256): strip.setPixelColorRGB(i,0,0,0) # strip.show() def render(self): strip = self.led_array strip.show() def fill_rect(self, i, width, color): start = i end = start + width if (end < start): raise NameError('cant create a negative rectangle') if(start > 31): start = 31 end = 31 for i in range(start,end): self.setRowColor(i,color)
class __Instance: # LED strip configuration: LED_COUNT = 150 - 27 # 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 = 5 # DMA channel to use for generating signal (try 5) 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) def __init__(self): random.seed() self.__strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS) self.__strip.begin() LIT_COUNT = 10 last = [0] * LIT_COUNT def twinkle(self): while True: for i in range(0, self.LIT_COUNT): self.__strip.setPixelColor(self.last[i], color.Black()) self.last[i] = random.randint(0, self.__strip.numPixels()) self.__strip.setPixelColor(self.last[i], color.Random()) self.__strip.show() util.delay(150) def walk(self): while True: for i in range(0, self.__strip.numPixels()): self.__strip.setPixelColor(i, color.Random()) self.__strip.show() util.delay(100.0) util.delay(750.0) def set_color(self, color): for i in range(0, self.__strip.numPixels()): self.__strip.setPixelColor(i, color) self.__strip.show() def cylon(self): red = 0 for i in range(0, self.__strip.numPixels()): self.__strip.setPixelColor(i, color.Color(red, 0, 0)) red += 1 self.__strip.show()
class Lightstrip(object): def __init__(self, cfg): nps = cfg['neopixel'] self.strip = Adafruit_NeoPixel(nps['led-count'], \ nps['led-pin'], nps['led-freq-hz'], nps['led-dma'], \ nps['led-invert'], nps['led-brightness'], nps['led-channel']) self.reversed = cfg['custom']['reversed'] self.strip.begin() def _cleanup(self): self.strip._cleanup() def show(self): self.strip.show() # Sets the pixel without updating the strip # Allows reversal of direction of the strip # Ensures bounded pixel index from [0, numPixels) def setPixel(self, n, color): pixelNum = self.strip.numPixels() - 1 - n if self.reversed else n pixelNum %= self.strip.numPixels() self.strip.setPixelColor(pixelNum, color) # Sets the pixel and immediately updates the lightstrip visually def setPixelUpdate(self, n, color): self.setPixel(n, color) self.show() def setBrightness(self, n): self.strip.setBrightness(n) def getBrightness(self): self.strip.getBrightness() def setReversed(self, rev): self.reversed = rev def getReversed(self): return self.reversed def numPixels(self): return self.strip.numPixels() # The only animation I am baking into the lightstrip class because # it has pretty universal importance among other animations and # the runner class too def clear(self): for i in range(self.strip.numPixels()): self.setPixel(i, Color(0, 0, 0)) self.show() def clearPixel(self, n): self.setPixel(n, Color(0, 0, 0))
def _get_strip(): strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) strip.begin() for i in range(0, strip.numPixels(), 1): strip.setPixelColor(i, Color(0, 0, 0)) strip.setBrightness(100) return strip
class Control: def __init__(self): self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 0, ws.WS2812_STRIP) self.strip.begin() self.running = True def color_temp(self, temp, brightness=1.0): r, g, b = convert_K_to_RGB(temp) r = int(r * brightness) g = int(g * brightness) b = int(b * brightness) self.color(r, g, b) def color(self, r, g, b): color = Color(r, g, b) for i in range(self.strip.numPixels()): self.strip.setPixelColor(i, color) while True: self.strip.show() if self.running: time.sleep(20 / 1000.0) else: return def rainbow(self): while True: for j in range(256): for i in range(self.strip.numPixels()): self.strip.setPixelColor(i, wheel((i + j) & 255)) self.strip.show() if self.running: time.sleep(20 / 1000.0) else: return def rainbow_onecolor(self): while True: for j in range(256): for i in range(self.strip.numPixels()): self.strip.setPixelColor(i, wheel(j & 255)) self.strip.show() if self.running: time.sleep(20 / 1000.0) else: return
class LightController(object): LED_COUNT = 43 # 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 = 5 # DMA channel to use for generating signal (try 5) 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) def __init__(self): self.led_count = 43 self.led_pin = 18 self.leds = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS) def cut_light_ranges(self, hue, disable_range): x = disable_range[0] * 255. / (255 - disable_range[1] + disable_range[0]) if hue < x: hue *= (255 - disable_range[1] + disable_range[0]) / 255. else: hue = disable_range[1] + ((hue - x) * (255. - disable_range[1])) / (255. - x) return hue def cb_light(self, msg): disabled_range = [30, 100] hue = self.cut_light_ranges(msg.data, disabled_range) hue = hue / 255. # Hue between (0., 1.) #r, g, b = map(int, hsv_to_rgb(hue, 1, 255)) r, g, b = map(int, hsv_to_rgb(0, 0, msg.data)) self.set_all(r, g, b) def set_all(self, r, g, b): for i in range(self.LED_COUNT): self.leds.setPixelColor(i, Color(g, r, b)) self.leds.show() def run(self): try: self.leds.begin() except RuntimeError as e: raise RuntimeError( repr(e) + "\nAre you running this script with root permissions?") else: self.set_all(0, 0, 0) rospy.Subscriber("apex_playground/environment/light", UInt8, self.cb_light) rospy.spin()
class PiWS281X(DriverBase): """ Driver for controlling WS281X LEDs via the rpi_ws281x C-extension. Only supported on the Raspberry Pi 2 & 3 """ def __init__(self, num, gamma=gamma.NEOPIXEL, c_order=ChannelOrder.RGB, gpio=18, ledFreqHz=800000, ledDma=5, ledInvert=False, **kwds): """ num - Number of LED pixels. gpio - GPIO pin connected to the pixels (must support PWM! GPIO 13 or 18 (pins 33 or 12) on RPi 3). ledFreqHz - LED signal frequency in hertz (800khz or 400khz) ledDma - DMA channel to use for generating signal (Between 1 and 14) ledInvert - True to invert the signal (when using NPN transistor level shift) """ super().__init__(num, c_order=c_order, gamma=gamma, **kwds) self.gamma = gamma if gpio not in PIN_CHANNEL.keys(): raise ValueError('{} is not a valid gpio option!') self._strip = Adafruit_NeoPixel(num, gpio, ledFreqHz, ledDma, ledInvert, 255, PIN_CHANNEL[gpio], 0x081000) # Intialize the library (must be called once before other functions). self._strip.begin() def set_brightness(self, brightness): self._strip.setBrightness(brightness) return True def _compute_packet(self): self._render() data = self._buf self._packet = [ tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3) ] def _send_packet(self): for i, p in enumerate(self._packet): self._strip.setPixelColor(i, NeoColor(*p)) self._strip.show()
def main(): global radien global streifen global pix global T n = 0 #Zählervariable neuesBild(path) gp.setmode(gp.BCM) # Welche Nummern für die Pins verwendet werden gp.setwarnings(False) # Keine Warnungen gp.setup(MAGNET_PIN, gp.IN) # Anschluss #Erschaffen des Led-Streifen-Objekts streifen = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) streifen.begin() #initialisieren des LED-Streifens startPrint() #Drucken der Anfangseinstellungen while True: t1 = time() #Startzeit der Umdrehung t1 if gp.input(MAGNET_PIN) == False: #Zeitmessung einmal je Umdrehung w = 2 * pi / T #Berrechnen der Aktuellen Winkelgeschwindigkeit while gp.input(MAGNET_PIN) == False: t = time() - t1 #Ausrechnen der größe des Zeitabschnitts if t < 5: streifenBedienen(t, w) streifen.show() else: for i in range(0, LED_COUNT): streifen.setPixelColor(i, Color(0,0,0)) streifen.show() n +=1 if n > 3: #jede dritte Umdrehung wird das bild neu in den Zwischenspeicher gepackt n = 0 neuesBild("/home/pi/Bilder/Bild.") print("\b\b\b\b\b\b\b" + str(int(w * 0.3*3.6)) + " km/h") T = time() - t1 #Ausrechnen von T nach T = t2 - t1
class NeopixelSequencePlayer(SequencePlayer): def __init__(self): super().__init__() self.strip = Adafruit_NeoPixel(cfg.LED_COUNT, cfg.LED_DATA_PIN, cfg.LED_FREQ_HZ, cfg.LED_DMA, cfg.LED_INVERT, cfg.LED_BRIGHTNESS, cfg.LED_CHANNEL, cfg.LED_STRIP) self.strip.begin() def setrangecolor(self, start, end, color, write=True): super().setrangecolor(start, end, color, write) if write: self.strip.show() def setcolor(self, led, color, write=True): self.strip.setPixelColor(led, color.topixel()) if write: self.strip.show()
class Led_Array(object): def __init__(self): self.LED_COUNT = 256 # Number of LED pixels. self.LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). self.LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) self.LED_DMA = 5 # DMA channel to use for generating signal (try 5) self.LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest self.LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) self.ROW_WIDTH = 8 # Number of LEDs in each row of the array # Create NeoPixel object with appropriate configuration. self.led_array = Adafruit_NeoPixel( self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS ) # Intialize the library (must be called once before other functions). self.led_array.begin() def _info(self): return self.LED_COUNT, self.LED_PIN, self.LED_BRIGHTNESS, self.ROW_WIDTH def setRowColor(self, row_number, color): strip = self.led_array start = 0 + row_number * self.ROW_WIDTH end = start + self.ROW_WIDTH for i in range(start, end): strip.setPixelColor(i, color) # strip.show() def fill_up_to(self, row, color): # strip = self.led_array for i in range(row + 1): self.setRowColor(i, color) def empty_array(self): strip = self.led_array for i in range(256): strip.setPixelColorRGB(i, 0, 0, 0) # strip.show() def render(self): strip = self.led_array strip.show()
def main(): global radien global streifen global pix global T n = 0 #Zählervariable neuesBild(path) gp.setmode(gp.BCM) # Welche Nummern für die Pins verwendet werden gp.setwarnings(False) # Keine Warnungen gp.setup(MAGNET_PIN, gp.IN) # Anschluss #Erschaffen des Led-Streifen-Objekts streifen = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) streifen.begin() #initialisieren des LED-Streifens startPrint() #Drucken der Anfangseinstellungen while True: t1 = time() #Startzeit der Umdrehung t1 if gp.input(MAGNET_PIN) == False: #Zeitmessung einmal je Umdrehung w = 2 * pi / T #Berrechnen der Aktuellen Winkelgeschwindigkeit while gp.input(MAGNET_PIN) == False: t = time() - t1 #Ausrechnen der größe des Zeitabschnitts if t < 5: streifenBedienen(t, w) streifen.show() else: for i in range(0, LED_COUNT): streifen.setPixelColor(i, Color(0, 0, 0)) streifen.show() n += 1 if n > 3: #jede dritte Umdrehung wird das bild neu in den Zwischenspeicher gepackt n = 0 neuesBild("/home/pi/Bilder/Bild.") print("\b\b\b\b\b\b\b" + str(int(w * 0.3 * 3.6)) + " km/h") T = time() - t1 #Ausrechnen von T nach T = t2 - t1
def fill_up_to(strip, row, color): for i in range(row + 1): setRowColor(strip, i, color) def empty_array(strip): for i in range(256): strip.setPixelColorRGB(i, 0, 0, 0) strip.show() # Main program logic follows: if __name__ == '__main__': # Create NeoPixel object with appropriate configuration. led_array = 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). led_array.begin() while True: color = Color(0, 0, 60) # setRowColor(led_array,1,color) # fill_up_to(led_array,0,color) # sleep(0.1) fill_up_to(led_array, 7, color) sleep(5) empty_array(led_array) sleep(3)
class wordclock_display: """ Class to display any content on the wordclock display Depends on the (individual) wordclock layout/wiring """ def __init__(self, config, wci): """ Initialization """ # Get the wordclocks wiring-layout self.wcl = wiring.wiring(config) self.wci = wci try: default_brightness = config.getint('wordclock_display', 'brightness') except: default_brightness = 255 print( 'WARNING: Default brightness value not set in config-file: ' 'To do so, add a "brightness" between 1..255 to the [wordclock_display]-section.') if config.getboolean('wordclock', 'developer_mode'): from GTKstrip import GTKstrip self.strip = GTKstrip(wci) self.default_font = os.path.join('/usr/share/fonts/TTF/', config.get('wordclock_display', 'default_font') + '.ttf') else: try: from neopixel import Adafruit_NeoPixel, ws self.strip = Adafruit_NeoPixel(self.wcl.LED_COUNT, self.wcl.LED_PIN, self.wcl.LED_FREQ_HZ, self.wcl.LED_DMA, self.wcl.LED_INVERT, default_brightness , 0, ws.WS2811_STRIP_GRB) except: print('Update deprecated external dependency rpi_ws281x. ' 'For details see also https://github.com/jgarff/rpi_ws281x/blob/master/python/README.md') self.default_font = os.path.join('/usr/share/fonts/truetype/freefont/', config.get('wordclock_display', 'default_font') + '.ttf') # Initialize the NeoPixel object self.strip.begin() self.default_fg_color = wcc.WWHITE self.default_bg_color = wcc.BLACK self.base_path = config.get('wordclock', 'base_path') # Choose language try: language = ''.join(config.get('wordclock_display', 'language')) except: # For backward compatibility language = ''.join(config.get('plugin_time_default', 'language')) print(' Setting language to ' + language + '.') if language == 'dutch': self.taw = time_dutch.time_dutch() elif language == 'english': self.taw = time_english.time_english() elif language == 'german': self.taw = time_german.time_german() elif language == 'german2': self.taw = time_german2.time_german2() elif language == 'swabian': self.taw = time_swabian.time_swabian() elif language == 'swabian2': self.taw = time_swabian2.time_swabian2() elif language == 'bavarian': self.taw = time_bavarian.time_bavarian() elif language == 'swiss_german': self.taw = time_swiss_german.time_swiss_german() elif language == 'swiss_german2': self.taw = time_swiss_german2.time_swiss_german2() else: print('Could not detect language: ' + language + '.') print('Choosing default: german') self.taw = time_german.time_german() def setPixelColor(self, pixel, color): """ Sets the color for a pixel, while considering the brightness, set within the config file """ self.strip.setPixelColor(pixel, color) def getBrightness(self): """ Sets the color for a pixel, while considering the brightness, set within the config file """ return self.strip.getBrightness() def setBrightness(self, brightness): """ Sets the color for a pixel, while considering the brightness, set within the config file """ self.strip.setBrightness(brightness) self.show() def setColorBy1DCoordinates(self, *args, **kwargs): """ Sets a pixel at given 1D coordinates """ return self.wcl.setColorBy1DCoordinates(*args, **kwargs) def setColorBy2DCoordinates(self, *args, **kwargs): """ Sets a pixel at given 2D coordinates """ return self.wcl.setColorBy2DCoordinates(*args, **kwargs) def get_wca_height(self): """ Returns the height of the WCA """ return self.wcl.WCA_HEIGHT def get_wca_width(self): """ Returns the height of the WCA """ return self.wcl.WCA_WIDTH def get_led_count(self): """ Returns the overall number of LEDs """ return self.wcl.LED_COUNT def dispRes(self): """ Returns the resolution of the wordclock array as string E.g. to choose the correct resolution of animations and icons """ return str(self.wcl.WCA_WIDTH) + 'x' + str(self.wcl.WCA_HEIGHT) def setColorToAll(self, color, includeMinutes=True): """ Sets a given color to all leds If includeMinutes is set to True, color will also be applied to the minute-leds. """ if includeMinutes: for i in range(self.wcl.LED_COUNT): self.setPixelColor(i, color) else: for i in self.wcl.getWcaIndices(): self.setPixelColor(i, color) def setColorTemperatureToAll(self, temperature, includeMinutes=True): """ Sets a color to all leds based on the provided temperature in Kelvin If includeMinutes is set to True, color will also be applied to the minute-leds. """ self.setColorToAll(wcc.color_temperature_to_rgb(temperature), includeMinutes) def resetDisplay(self): """ Reset display """ self.setColorToAll(wcc.BLACK, True) def showIcon(self, plugin, iconName): """ Dispays an icon with a specified name. The icon needs to be provided within the graphics/icons folder. """ self.setImage( self.base_path + '/wordclock_plugins/' + plugin + '/icons/' + self.dispRes() + '/' + iconName + '.png') def setImage(self, absPathToImage): """ Set image (provided as absolute path) to current display """ img = Image.open(absPathToImage) width, height = img.size for x in range(0, width): for y in range(0, height): rgb_img = img.convert('RGB') r, g, b = rgb_img.getpixel((x, y)) self.wcl.setColorBy2DCoordinates(self.strip, x, y, wcc.Color(r, g, b)) self.show() def animate(self, plugin, animationName, fps=10, count=1, invert=False): """ Runs an animation plugin: Plugin-name num_of_frames: Number of frames to be displayed count: Number of runs fps: frames per second invert: Invert order of animation """ animation_dir = self.base_path + '/wordclock_plugins/' + plugin + '/animations/' + self.dispRes() + '/' + animationName + '/' num_of_frames = len([file_count for file_count in os.listdir(animation_dir)]) if invert: animation_range = range(num_of_frames - 1, -1, -1) else: animation_range = range(0, num_of_frames) for _ in range(count): for i in animation_range: self.setImage(animation_dir + str(i).zfill(3) + '.png') if self.wci.waitForExit(1.0 / fps): return def showText(self, text, font=None, fg_color=None, bg_color=None, fps=10, count=1): """ Display text on display """ if font is None: font = self.default_font if fg_color is None: fg_color = self.default_fg_color if bg_color is None: bg_color = self.default_bg_color text = ' ' + text + ' ' fnt = fontdemo.Font(font, self.wcl.WCA_HEIGHT) text_width, text_height, text_max_descent = fnt.text_dimensions(text) text_as_pixel = fnt.render_text(text) # Display text count times for i in range(count): # Erase previous content self.setColorToAll(bg_color, includeMinutes=True) # Assure here correct rendering, if the text does not fill the whole display render_range = self.wcl.WCA_WIDTH if self.wcl.WCA_WIDTH < text_width else text_width for y in range(text_height): for x in range(render_range): self.wcl.setColorBy2DCoordinates(self.strip, x, y, fg_color if text_as_pixel.pixels[y * text_width + x] else bg_color) # Show first frame for 0.5 seconds self.show() if self.wci.waitForExit(0.5): return # Shift text from left to right to show all. for cur_offset in range(text_width - self.wcl.WCA_WIDTH + 1): for y in range(text_height): for x in range(self.wcl.WCA_WIDTH): self.wcl.setColorBy2DCoordinates(self.strip, x, y, fg_color if text_as_pixel.pixels[ y * text_width + x + cur_offset] else bg_color) self.show() if self.wci.waitForExit(1.0 / fps): return def setMinutes(self, time, color): if time.minute % 5 != 0: for i in range(1, time.minute % 5 + 1): self.setPixelColor(self.wcl.mapMinutes(i), color) def show(self): """ This function provides the current color settings to the LEDs """ self.strip.show()
class PiWS281X(DriverBase): """ Driver for controlling WS281X LEDs via the rpi_ws281x C-extension. Only supported on the Raspberry Pi 2, 3, and Zero This driver needs to be run as sudo and requires the rpi_ws281x C extension. Install rpi_ws281x with the following shell commands: git clone https://github.com/jgarff/rpi_ws281x.git cd rpi_ws281x sudo apt-get install python-dev swig scons sudo scons cd python # If using default system python3 sudo python3 setup.py build install # If using virtualenv, enter env then run python setup.py build install Provides the same parameters of :py:class:`.driver_base.DriverBase` as well as those below: :param int gpio: GPIO pin to output to. Typically 18 or 13 :param int ledFreqHz: WS2812B base data frequency in Hz. Only change to 400000 if using very old WS218B LEDs :param int ledDma: DMA channel to use for generating signal (between 1 and 14) :param bool ledInvert: True to invert the signal (when using NPN transistor level shift) """ def __init__(self, num, gamma=gamma.NEOPIXEL, c_order="RGB", gpio=18, ledFreqHz=800000, ledDma=5, ledInvert=False, color_channels=3, brightness=255, **kwds): if not NeoColor: raise ValueError(WS_ERROR) super().__init__(num, c_order=c_order, gamma=gamma, **kwds) self.gamma = gamma if gpio not in PIN_CHANNEL.keys(): raise ValueError('{} is not a valid gpio option!') try: strip_type = STRIP_TYPES[color_channels] except: raise ValueError('In PiWS281X, color_channels can only be 3 or 4') self._strip = Adafruit_NeoPixel(num, gpio, ledFreqHz, ledDma, ledInvert, brightness, PIN_CHANNEL[gpio], strip_type) # Intialize the library (must be called once before other functions). try: self._strip.begin() except RuntimeError as e: if os.geteuid(): if os.path.basename(sys.argv[0]) in ('bp', 'bibliopixel'): command = ['bp'] + sys.argv[1:] else: command = ['python'] + sys.argv error = SUDO_ERROR.format(command=' '.join(command)) e.args = (error, ) + e.args raise def set_brightness(self, brightness): self._strip.setBrightness(brightness) return True def _compute_packet(self): self._render() data = self._buf self._packet = [ tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3) ] def _send_packet(self): for i, p in enumerate(self._packet): self._strip.setPixelColor(i, NeoColor(*p)) self._strip.show()
class wordclock_display: """ Class to display any content on the wordclock display Depends on the (individual) wordclock layout/wiring """ def __init__(self, config, wci): """ Initialization """ # Get the wordclocks wiring-layout self.wcl = wiring.wiring(config) self.wci = wci self.config = config self.base_path = config.get('wordclock', 'base_path') max_brightness = 255 try: self.setBrightness(config.getint('wordclock_display', 'brightness')) except: self.brightness = max_brightness print( 'WARNING: Default brightness value not set in config-file: ' 'To do so, add a "brightness" between 1..255 to the [wordclock_display]-section.' ) if config.getboolean('wordclock', 'developer_mode'): from GTKstrip import GTKstrip self.strip = GTKstrip(wci) self.default_font = 'wcfont.ttf' else: try: from neopixel import Adafruit_NeoPixel, ws self.strip = Adafruit_NeoPixel( self.wcl.LED_COUNT, self.wcl.LED_PIN, self.wcl.LED_FREQ_HZ, self.wcl.LED_DMA, self.wcl.LED_INVERT, max_brightness, 0, ws.WS2811_STRIP_GRB) except: print( 'Update deprecated external dependency rpi_ws281x. ' 'For details see also https://github.com/jgarff/rpi_ws281x/blob/master/python/README.md' ) if config.get('wordclock_display', 'default_font') == 'wcfont': self.default_font = self.base_path + '/wcfont.ttf' else: self.default_font = os.path.join( '/usr/share/fonts/truetype/freefont/', config.get('wordclock_display', 'default_font') + '.ttf') # Initialize the NeoPixel object self.strip.begin() self.default_fg_color = wcc.WWHITE self.default_bg_color = wcc.BLACK # Choose language try: language = ''.join(config.get('wordclock_display', 'language')) except: # For backward compatibility language = ''.join(config.get('plugin_time_default', 'language')) print(' Setting language to ' + language + '.') if language == 'dutch': self.taw = time_dutch.time_dutch() elif language == 'english': self.taw = time_english.time_english() elif language == 'english_c3jr': self.taw = time_english_c3jr.time_english() elif language == 'german': self.taw = time_german.time_german() elif language == 'german2': self.taw = time_german2.time_german2() elif language == 'swabian': self.taw = time_swabian.time_swabian() elif language == 'swabian2': self.taw = time_swabian2.time_swabian2() elif language == 'bavarian': self.taw = time_bavarian.time_bavarian() elif language == 'swiss_german': self.taw = time_swiss_german.time_swiss_german() elif language == 'swiss_german2': self.taw = time_swiss_german2.time_swiss_german2() else: print('Could not detect language: ' + language + '.') print('Choosing default: german') self.taw = time_german.time_german() def setPixelColor(self, pixel, color): """ Sets the color for a pixel, while considering the brightness, set within the config file """ self.strip.setPixelColor(pixel, color) def getBrightness(self): """ Sets the color for a pixel, while considering the brightness, set within the config file """ return self.brightness def setBrightness(self, brightness): """ Sets the color for a pixel, while considering the brightness, set within the config file """ brightness_before = self.getBrightness() brightness = max(min(255, brightness), 0) for i in range(self.wcl.LED_COUNT): color = self.getPixelColor(i) color = (color / brightness_before) ^ (1 / 2.2) * brightness self.setPixelColor(i, color) self.brightness = brightness self.show() def setColorBy1DCoordinates(self, *args, **kwargs): """ Sets a pixel at given 1D coordinates """ return self.wcl.setColorBy1DCoordinates(*args, **kwargs) def setColorBy2DCoordinates(self, *args, **kwargs): """ Sets a pixel at given 2D coordinates """ return self.wcl.setColorBy2DCoordinates(*args, **kwargs) def get_wca_height(self): """ Returns the height of the WCA """ return self.wcl.WCA_HEIGHT def get_wca_width(self): """ Returns the width of the WCA """ return self.wcl.WCA_WIDTH def get_led_count(self): """ Returns the overall number of LEDs """ return self.wcl.LED_COUNT def dispRes(self): """ Returns the resolution of the wordclock array as string E.g. to choose the correct resolution of animations and icons """ return str(self.wcl.WCA_WIDTH) + 'x' + str(self.wcl.WCA_HEIGHT) def setColorToAll(self, color, includeMinutes=True): """ Sets a given color to all leds If includeMinutes is set to True, color will also be applied to the minute-leds. """ if includeMinutes: for i in range(self.wcl.LED_COUNT): self.setPixelColor(i, color) else: for i in self.wcl.getWcaIndices(): self.setPixelColor(i, color) def setColorTemperatureToAll(self, temperature, includeMinutes=True): """ Sets a color to all leds based on the provided temperature in Kelvin If includeMinutes is set to True, color will also be applied to the minute-leds. """ self.setColorToAll(wcc.color_temperature_to_rgb(temperature), includeMinutes) def resetDisplay(self): """ Reset display """ self.setColorToAll(wcc.BLACK, True) def showIcon(self, plugin, iconName): """ Dispays an icon with a specified name. The icon needs to be provided within the graphics/icons folder. """ self.setImage(self.base_path + '/wordclock_plugins/' + plugin + '/icons/' + self.dispRes() + '/' + iconName + '.png') def setImage(self, absPathToImage): """ Set image (provided as absolute path) to current display """ img = Image.open(absPathToImage) width, height = img.size for x in range(0, width): for y in range(0, height): rgb_img = img.convert('RGB') r, g, b = rgb_img.getpixel((x, y)) self.wcl.setColorBy2DCoordinates(self.strip, x, y, wcc.Color(r, g, b)) self.show() def animate(self, plugin, animationName, fps=10, count=1, invert=False): """ Runs an animation plugin: Plugin-name num_of_frames: Number of frames to be displayed count: Number of runs fps: frames per second invert: Invert order of animation """ animation_dir = self.base_path + '/wordclock_plugins/' + plugin + '/animations/' + self.dispRes( ) + '/' + animationName + '/' num_of_frames = len( [file_count for file_count in os.listdir(animation_dir)]) if invert: animation_range = range(num_of_frames - 1, -1, -1) else: animation_range = range(0, num_of_frames) for _ in range(count): for i in animation_range: self.setImage(animation_dir + str(i).zfill(3) + '.png') if self.wci.waitForExit(1.0 / fps): return def showText(self, text, font=None, fg_color=None, bg_color=None, fps=10, count=1): """ Display text on display """ if font is None: font = self.default_font if fg_color is None: fg_color = self.default_fg_color if bg_color is None: bg_color = self.default_bg_color text = ' ' + text + ' ' fnt = fontdemo.Font(font, self.wcl.WCA_HEIGHT) text_width, text_height, text_max_descent = fnt.text_dimensions(text) text_as_pixel = fnt.render_text(text) # Display text count times for i in range(count): # Erase previous content self.setColorToAll(bg_color, includeMinutes=True) # Assure here correct rendering, if the text does not fill the whole display render_range = self.wcl.WCA_WIDTH if self.wcl.WCA_WIDTH < text_width else text_width for y in range(text_height): for x in range(render_range): self.wcl.setColorBy2DCoordinates( self.strip, x, y, fg_color if text_as_pixel.pixels[y * text_width + x] else bg_color) # Show first frame for 0.5 seconds self.show() if self.wci.waitForExit(0.5): return # Shift text from left to right to show all. for cur_offset in range(text_width - self.wcl.WCA_WIDTH + 1): for y in range(text_height): for x in range(self.wcl.WCA_WIDTH): self.wcl.setColorBy2DCoordinates( self.strip, x, y, fg_color if text_as_pixel.pixels[y * text_width + x + cur_offset] else bg_color) self.show() if self.wci.waitForExit(1.0 / fps): return def setMinutes(self, time, color): if time.minute % 5 != 0: for i in range(1, time.minute % 5 + 1): self.setPixelColor(self.wcl.mapMinutes(i), color) def show(self): """ This function provides the current color settings to the LEDs """ self.strip.show()
import time, spidev from neopixel import Adafruit_NeoPixel # 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 = 5 # DMA channel to use for generating signal (try 5) LED_BRIGHTNESS = 140 # Set to 0 for darkest and 255 for brightest LED_CHANNEL = 0 # PWM channel LED_INVERT = True # True if using an inverting interface ws2812 = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) ws2812.begin() length = LED_COUNT circleLength = 16 totemLength = 14 launchPoint = 11 # LED opposite totem inBuf = [0, 0] lastBuf = [0, 0] difBuf = [0, 0] totBuf = [(0, i, 0) for i in range(0, totemLength)] def main(): print("Neopixel Bounce - Cnt C to stop") initHardware() curCol = (0, 120, 0)
def reset(self): self.hits = [] self.misses = dict() def miss(self, button, timestamp): self.misses[button] = timestamp if __name__ == "__main__": from neopixel import Adafruit_NeoPixel, ws import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) from gpio_switch import GPIOSwitch switches = [ GPIOSwitch(5, GPIO), GPIOSwitch(6, GPIO), GPIOSwitch(13, GPIO), GPIOSwitch(19, GPIO), GPIOSwitch(26, GPIO) ] lights = Adafruit_NeoPixel(len(switches), 18, 800000, 5, False, 50, 0, ws.WS2811_STRIP_GRB) lights.begin() board = Board(lights, switches) buttons = Buttons(board) board.loop()
def initialize_strip(): strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP) strip.begin() return strip
class ColoramaDisplay(ApplicationSession): @inlineCallbacks def onJoin(self, details): self._serial = get_serial() self._prefix = u'io.crossbar.demo.iotstarterkit.{}.pixelstrip'.format(self._serial) self.log.info("Crossbar.io IoT Starterkit Serial No.: {serial}", serial=self._serial) self.log.info("ColoramaDisplay connected: {details}", details=details) # get custom configuration cfg = self.config.extra self._leds = Adafruit_NeoPixel( cfg['led_count'], cfg['led_pin'], cfg['led_freq_hz'], cfg['led_dma'], cfg['led_invert'], cfg['led_brightness']) self._leds.begin() for proc in [ (self.set_color, 'set_color'), (self.get_color, 'get_color'), (self.flash, 'flash'), (self.lightshow, 'lightshow'), (self.color_wipe, 'color_wipe'), (self.theater_chase, 'theater_chase'), (self.rainbow, 'rainbow'), (self.rainbow_cycle, 'rainbow_cycle'), (self.theater_chaserainbow, 'theater_chaserainbow'), ]: yield self.register(proc[0], u'{}.{}'.format(self._prefix, proc[1])) self.flash() self.log.info("ColoramaDisplay ready!") @inlineCallbacks def flash(self, delay=50, repeat=5): delay = float(delay) / 1000. for i in range(repeat): self.set_color(0xe1, 0xda, 0x05) yield sleep(2 * delay) self.set_color(0x52, 0x42, 0x00) yield sleep(delay) @inlineCallbacks def lightshow(self): # Color wipe animations. yield self.color_wipe(255, 0, 0) # Red wipe yield self.color_wipe(0, 255, 0) # Blue wipe yield self.color_wipe(0, 0, 255) # Green wipe # Theater chase animations. yield self.theater_chase(127, 127, 127) # White theater chase yield self.theater_chase(127, 0, 0) # Red theater chase yield self.theater_chase(0, 0, 127) # Blue theater chase # Rainbow animations. yield self.rainbow() yield self.rainbow_cycle() #yield self.theater_chase_rainbow() yield self.flash() # Define functions which animate LEDs in various ways. @inlineCallbacks def color_wipe(self, r, g, b, wait_ms=50): """Wipe color across display a pixel at a time.""" for i in range(self._leds.numPixels()): self.set_color(r, g, b, i) yield sleep(wait_ms / 1000.0) @inlineCallbacks def theater_chase(self, r, g, b, 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, self._leds.numPixels(), 3): self.set_color(r, g, b, i + q) yield sleep(wait_ms / 1000.0) for i in range(0, self._leds.numPixels(), 3): self.set_color(0, 0, 0, i + q) def wheel(self, pos): """Generate rainbow colors across 0-255 positions.""" if pos < 85: return (pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 return (255 - pos * 3, 0, pos * 3) else: pos -= 170 return (0, pos * 3, 255 - pos * 3) @inlineCallbacks def rainbow(self, wait_ms=20, iterations=1): """Draw rainbow that fades across all pixels at once.""" for j in range(256 * iterations): for i in range(self._leds.numPixels()): r, g, b = self.wheel((i + j) & 255) self.set_color(r, g, b, i) yield sleep(wait_ms / 1000.0) @inlineCallbacks def rainbow_cycle(self, wait_ms=20, iterations=5): """Draw rainbow that uniformly distributes itself across all pixels.""" for j in range(256 * iterations): for i in range(self._leds.numPixels()): r, g, b = self.wheel(((i * 256 / self._leds.numPixels()) + j) & 255) self.set_color(r, g, b, i) yield sleep(wait_ms / 1000.0) @inlineCallbacks def theater_chaserainbow(self, 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, self._leds.numPixels(), 3): r, g, b = self.wheel((i+j) % 255) self.set_color(r, g, b, i + q) yield sleep(wait_ms / 1000.0) for i in range(0, self._leds.numPixels(), 3): self.set_color(0, 0, 0, i) def set_color(self, red, green, blue, k=None): if k is None: for i in range(self._leds.numPixels()): # FIXME: not sure, but we need to swap this here. maybe it is the specific neopixels? self._leds.setPixelColorRGB(i, green, red, blue) color_change = { u'led': i, u'r': red, u'g': green, u'b': blue } self.publish(u'{}.on_color_set'.format(self._prefix), color_change) else: # FIXME: not sure, but we need to swap this here. maybe it is the specific neopixels? self._leds.setPixelColorRGB(k, green, red, blue) color_change = { u'led': k, u'r': red, u'g': green, u'b': blue } self.publish(u'{}.on_color_set'.format(self._prefix), color_change) self._leds.show() def get_color(self, k): c = self._leds.getPixelColor(k) color = { u'g': c >> 16, u'r': (c >> 8) & 0xff, u'b': c & 0xff, } return color def onLeave(self, details): self.log.info("Session closed: {details}", details=details) self.disconnect() def onDisconnect(self): self.log.info("Connection closed") for i in range(self._leds.numPixels()): self._leds.setPixelColorRGB(i, 0, 0, 0) self._leds.show() try: reactor.stop() except ReactorNotRunning: pass
class RPiMaze(MazeGame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Set up NeoPixel self.np = Adafruit_NeoPixel(NUM_PIXELS, GPIO_PIN, brightness=INTENSITY) self.np.begin() self.led_grid = led_grid.LEDGrid(self.np, grid.SerpentinePattern.TOP_RIGHT, width=MATRIX_WIDTH, height=MATRIX_HEIGHT) @staticmethod def hexcolor_to_rgb(colorstr): # https://stackoverflow.com/a/29643643 TODO: abstract this out some more color = tuple(int(colorstr.lstrip('#')[i:i+2], 16) for i in (0, 2, 4)) print("%s: %s" % (colorstr, str(color))) return color def draw_point_at(self, x, y, color): try: self.led_grid.set(x, y, color, allowOverwrite=True) except IndexError: pass def _draw_walls(self, wall_points_to_draw): for point in wall_points_to_draw: #print("Drawing LED point %s, %s as a wall" % (point[0], point[1])) self.draw_point_at(point[0], point[1], (255, 255, 255)) def draw_maze_leds(self): """ Draws the maze on an LED strip. """ for pixel in range(NUM_PIXELS): self.np.setPixelColorRGB(pixel, 0, 0, 0) for ypos, row in enumerate(self.maze.by_rows()): for xpos, point in enumerate(row): if point.is_finish: color = self.hexcolor_to_rgb(self.FINISH_COLOR) elif point.is_start: color = self.hexcolor_to_rgb(self.START_COLOR) else: # Empty tile color = (0, 0, 0) for sprite in self.sprites: if sprite.x == xpos and sprite.y == ypos: color = self.hexcolor_to_rgb(sprite.color) print("Setting color to %s for sprite %s at %s, %s" % (color, sprite, xpos, ypos)) if point.is_selected: color = self.hexcolor_to_rgb(self.SELECTED_COLOR) led_xpos = xpos * 2 led_ypos = ypos * 2 #print("Translating player position (%s, %s) into LED position (%s, %s)" % (xpos, ypos, led_xpos, led_ypos)) wall_points_to_draw = { (led_xpos-1, led_ypos-1), (led_xpos-1, led_ypos+1), (led_xpos+1, led_ypos-1), (led_xpos+1, led_ypos+1) } paths = point.paths if 'north' not in paths: wall_points_to_draw.add((led_xpos, led_ypos-1)) if 'south' not in paths: wall_points_to_draw.add((led_xpos, led_ypos+1)) if 'east' not in paths: wall_points_to_draw.add((led_xpos+1, led_ypos)) if 'west' not in paths: wall_points_to_draw.add((led_xpos-1, led_ypos)) self._draw_walls(wall_points_to_draw) self.draw_point_at(led_xpos, led_ypos, color) self.np.show() self.led_grid.show() def draw_maze(self, *args, **kwargs): super().draw_maze(*args, **kwargs) self.draw_maze_leds() return True
def run(steps=120): result = VariousTools.offline_check('generalleds', hardware=False) changelog = [0, 0, 0] if result: setting = {'threat': 0, 'cautioning': 0, 'optimum': 0} plant = Plant.get(localhost=True) all_status = SensorStatus.select().where(SensorStatus.plant == plant) for status in all_status: setting[status.level.label] += 1 if setting['threat'] > 0: changelog[0] = 255 elif setting['cautioning'] > 0: changelog[0] = 255 changelog[1] = 255 elif setting['optimum'] > 0: changelog[1] = 255 basedir = os.path.dirname(os.path.realpath(__file__)) neopixel = Adafruit_NeoPixel(1, 18) neopixel.begin() if os.path.isfile(basedir + '/ledstate.json'): with open(basedir + '/ledstate.json', 'r') as out: current = json.loads(out.read()) else: raw = neopixel.getPixelColor(0) current = [] for _ in range(3): calc = divmod(raw, 256) raw = calc[0] current.append(calc[1]) current = current[::-1] if changelog == current: return True bcurrent = [] bchange = [] for pointer in range(len(current)): bcurrent.append(True if current[pointer] >= changelog[pointer] else False) bchange.append(True if current[pointer] != changelog[pointer] else False) old = deepcopy(current) for i in range(0, steps + 1): color = [] for pointer in range(len(bchange)): if bchange[pointer]: if not bcurrent[pointer]: x = i offset = current[pointer] else: x = steps - i offset = changelog[pointer] color.append(offset + int(abs(current[pointer] - changelog[pointer]) / steps * x)) else: color.append(old[pointer]) print(color) neopixel.setPixelColorRGB(0, color[0], color[1], color[2]) neopixel.show() old = deepcopy(color) time.sleep(1 / 15) with open(basedir + '/ledstate.json', 'w') as out: out.write(json.dumps(color)) time.sleep(1) neopixel.setPixelColorRGB(0, changelog[0], changelog[1], changelog[2]) neopixel.show() return True
class PiWS281X(DriverBase): """ Driver for controlling WS281X LEDs via the rpi_ws281x C-extension. Only supported on the Raspberry Pi 2, 3, and Zero This driver needs to be run as sudo and requires the rpi_ws281x C extension. Install rpi_ws281x with the following shell commands: git clone https://github.com/jgarff/rpi_ws281x.git cd rpi_ws281x sudo apt-get install python-dev swig scons sudo scons cd python # If using default system python3 sudo python3 setup.py build install # If using virtualenv, enter env then run python setup.py build install Provides the same parameters of :py:class:`.driver_base.DriverBase` as well as those below: :param int gpio: GPIO pin to output to. Typically 18 or 13 :param int ledFreqHz: WS2812B base data frequency in Hz. Only change to 400000 if using very old WS218B LEDs :param int ledDma: DMA channel to use for generating signal (Between 1 and 14) :param bool ledInvert: True to invert the signal (when using NPN transistor level shift) """ # Including follow as comment as URLs in docstrings don't play well with sphinx # Discussion re: running as sudo # https://groups.google.com/d/msg/maniacal-labs-users/6hV-2_-Xmqc/wmWJK709AQAJ # https://github.com/jgarff/rpi_ws281x/blob/master/python/neopixel.py#L106 def __init__( self, num, gamma=gamma.NEOPIXEL, c_order="RGB", gpio=18, ledFreqHz=800000, ledDma=5, ledInvert=False, color_channels=3, brightness=255, **kwds): if not NeoColor: raise ValueError(WS_ERROR) super().__init__(num, c_order=c_order, gamma=gamma, **kwds) self.gamma = gamma if gpio not in PIN_CHANNEL.keys(): raise ValueError('{} is not a valid gpio option!') try: strip_type = STRIP_TYPES[color_channels] except: raise ValueError('In PiWS281X, color_channels must be either 3 or 4') self._strip = Adafruit_NeoPixel( num, gpio, ledFreqHz, ledDma, ledInvert, brightness, PIN_CHANNEL[gpio], strip_type) # Intialize the library (must be called once before other functions). try: self._strip.begin() except RuntimeError as e: if os.geteuid(): if os.path.basename(sys.argv[0]) in ('bp', 'bibliopixel'): command = ['bp'] + sys.argv[1:] else: command = ['python'] + sys.argv error = SUDO_ERROR.format(command=' '.join(command)) e.args = (error,) + e.args raise def set_brightness(self, brightness): self._strip.setBrightness(brightness) return True def _compute_packet(self): self._render() data = self._buf self._packet = [tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3)] def _send_packet(self): for i, p in enumerate(self._packet): self._strip.setPixelColor(i, NeoColor(*p)) self._strip.show()
class LedController: global debug def __init__(self, display_mode:str, number_of_led_strips:int, number_of_leds_per_strip:int): self.current_beat_index = 0 self.note_led_rows = [] self.number_of_led_strips = number_of_led_strips self.number_of_leds_per_strip = number_of_leds_per_strip # holds the rgb values of each led self.all_colors_as_str = [] self.all_led_rgb_value_lists = [] # colors as [R, G, B] self.color_dict = { 'off': [0, 0, 0], 'white': [255, 255, 255], 'red': [255, 0, 0], 'blue': [0, 0, 255], 'green': [0, 255, 0] } # choose whether or not to highlight the current beat and dim the rest = 'highlight' # or only show the colors of the current beat = 'only_current' self.display_mode = display_mode # self.display_mode = 'only_current' # self.display_mode = 'highlight' # the other leds will be divided by this factor self.display_mode_highlight_factor = 10 self.led_strip = None # led strip settings self.number_of_leds_total = self.number_of_led_strips * self.number_of_leds_per_strip self.led_pin = 21 # uses PCM self.frequency_hz = 800000 self.dma = 10 self.led_brightness = 100 self.led_inverted = False self.led_pin_channel = 0 if debug: print('Settings for LedController(): ') print('Mode: ', self.display_mode) print('Brightness: ', self.led_brightness) print('Number of led strips: ', self.number_of_led_strips) print('Number of leds per strip: ', self.number_of_leds_per_strip) print('Total number of leds: ', self.number_of_leds_total) def initialize_led_strip(self): self.led_strip = Adafruit_NeoPixel(num=self.number_of_leds_total, pin=self.led_pin, freq_hz=self.frequency_hz, dma=self.dma, invert=self.led_inverted, brightness=self.led_brightness, channel=self.led_pin_channel ) self.led_strip.begin() if debug: print('\nInitialized Led strip... Obj: ', self.led_strip) print() def remove_strip_obj(self): self.led_strip = None def set_current_beat(self, beat:int): self.current_beat_index = beat - 1 # will set leds to be the colors from the led obj, depending on the display mode def set_led_colors(self): # choose whether to only show the current beat leds, or to highlight it if debug: print('Setting led colors... using display mode: ', self.display_mode) if self.display_mode == 'only_current': if debug: print('Mode is ', self.display_mode) self.only_show_colors_from_current_beat() self.convert_color_str_to_rgb() elif self.display_mode == 'highlight': if debug: print('Mode is ', self.display_mode) self.highlight_current_beat_leds() def only_show_colors_from_current_beat(self): index = 0 for note_led_row in self.note_led_rows: if index == self.current_beat_index: for note_led_container in note_led_row.row: led = note_led_container.led if led.is_displayed(): self.all_colors_as_str.append(led.get_color()) else: self.all_colors_as_str.append('off') else: for note_led_container in note_led_row.row: self.all_colors_as_str.append('off') index += 1 # convert color str to lists of three rgb values def convert_color_str_to_rgb(self): for color_str in self.all_colors_as_str: rgb_list = self.color_dict[color_str] self.all_led_rgb_value_lists.append(rgb_list) # the leds of the current beat will be displayed at full brightness, the other beats at half def highlight_current_beat_leds(self): index = 0 for note_led_row in self.note_led_rows: if index == self.current_beat_index: for note_led_container in note_led_row.row: led = note_led_container.led if led.is_displayed(): color_str = led.get_color() self.all_colors_as_str.append(color_str) self.add_color_to_rgb_list(color=color_str) else: color_str = 'off' self.all_colors_as_str.append(color_str) self.add_color_to_rgb_list(color=color_str) else: for note_led_container in note_led_row.row: led = note_led_container.led if led.is_displayed(): color_str = led.get_color() self.all_colors_as_str.append(color_str) self.add_color_to_rgb_list(color=color_str, reduced_brightness=True) else: color_str = 'off' self.all_colors_as_str.append(color_str) self.add_color_to_rgb_list(color=color_str) index += 1 def add_color_to_rgb_list(self, color:str, reduced_brightness=False): rgb_list = self.color_dict[color] output_list = [] # if reduced brightness we divide by a factor if reduced_brightness: index = 0 for rgb_val in rgb_list: if not (rgb_val == 0): rgb_val = int(float(rgb_val) / float(self.display_mode_highlight_factor)) output_list.append(rgb_val) index += 1 else: output_list = rgb_list self.all_led_rgb_value_lists.append(output_list) # set the values for each led in the strip obj def update_led_strip_colors(self): led_index = 0 for rgb_list in self.all_led_rgb_value_lists: r = rgb_list[0] g = rgb_list[1] b = rgb_list[2] self.led_strip.setPixelColorRGB(n=led_index, red=r, green=g, blue=b) led_index += 1 # actually output the color values to the strip def display_updated_leds(self): if debug: print('Updating the output of the leds') self.led_strip.show() def clear_led_strip(self): for i in range(self.number_of_leds_total): self.led_strip.setPixelColorRGB(n=i, red=0, green=0, blue=0) time.sleep(0.01) self.led_strip.show() # main function to control the led hardware def update_led_strips(self, led_note_rows:list): if debug: print('Will now update the colors of the ledstrips') # reset the lists self.note_led_rows = led_note_rows self.all_colors_as_str = [] self.all_led_rgb_value_lists = [] self.set_led_colors() self.update_led_strip_colors() if debug: # print('note_led_rows: ', self.note_led_rows) # print('all_colors_as_str: ', self.all_colors_as_str) print('all_led_rgb_value_list: ', self.all_led_rgb_value_lists) self.display_updated_leds()
class Controller: LEDS = None NEOPIXEL_GPIO_PIN = None NEOPIXEL_FREQUENCY = None NEOPIXEL_DMA = None NEOPIXEL_INVERT = None NEOPIXEL_BRIGHTNESS = None NEOPIXEL_CHANNEL = None NEOPIXEL_STRIP = None neopixel = None thread = None effect = None def __init__(self, leds, neopixel_gpio_pin, neopixel_frequency, neopixel_dma, neopixel_invert, neopixel_brightness, neopixel_channel, neopixel_strip): print("[Neopixel][info] Initialising NeoPixel") self.LEDS = leds self.NEOPIXEL_GPIO_PIN = neopixel_gpio_pin self.NEOPIXEL_FREQUENCY = neopixel_frequency self.NEOPIXEL_DMA = neopixel_dma self.NEOPIXEL_INVERT = neopixel_invert self.NEOPIXEL_BRIGHTNESS = neopixel_brightness self.NEOPIXEL_CHANNEL = neopixel_channel self.NEOPIXEL_STRIP = neopixel_strip self.neopixel = Adafruit_Neopixel( self.LEDS, self.NEOPIXEL_GPIO_PIN, self.NEOPIXEL_FREQUENCY, self.NEOPIXEL_DMA, self.NEOPIXEL_INVERT, self.NEOPIXEL_BRIGHTNESS, self.NEOPIXEL_CHANNEL, self.NEOPIXEL_STRIP ) try: self.neopixel.begin() except AttributeError: print("[Neopixel][error] An error occurred initialising NeoPixel") def pixel_color(self, pixel, color): print("[Controller][info] Setting color: '%s' to NeoPixel pixel '%d'" % (color.get_hex(), pixel)) try: self.neopixel.setPixelColor(pixel, color.get_bit()) self.neopixel.show() except AttributeError: print("[Controller][error] An error occurred setting color to NeoPixel pixel") def color_wheel(self, pos): print("[Controller][info] Generation a color wheel") 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 brightness(self, brightness): print("[Controller][info] Setting brightness: '%d' to NeoPixel pixels" % (brightness)) try: self.neopixel.setBrightness(brightness) self.neopixel.show() except AttributeError: print("[Neopixel][error] An error occurred setting brightness on NeoPixel") def color(self, color): print("[Controller][info] Setting color: '%s' to NeoPixel pixels" % (color.get_hex())) try: for i in range(self.LEDS): self.pixel_color(i, color) self.neopixel.show() except AttributeError: print("[Controller][error] An error occurred setting color to NeoPixel pixels") def start_effect(self, effect, color): print("[Controller][info] Starting effect: '%s' to NeoPixel pixels" % (effect)) try: self.effect = eval(effect + '.' + effect.replace('_', ' ').title().replace(' ', ''))(self) self.thread = threading.Thread(target=self.effect.run, args=(color,)) self.thread.daemon = True self.thread.start() except AttributeError: print("[Controller][error] An error occurred starting effect to NeoPixel pixels") def stop_effect(self): print("[Controller][info] Stopping effect to NeoPixel pixels") try: if self.effect is not None: self.effect.stop() except AttributeError: print("[Controller][error] An error occurred stopping effect to NeoPixel pixels") def quit_effect(self): print("[Controller][info] Quitting effect to NeoPixel pixels") try: if self.effect is not None: self.thread.terminate() except AttributeError: print("[Controller][error] An error occurred quitting effect to NeoPixel pixels") def effects(self): print("[Controller][info] Getting a list of NeoPixel effects") try: effects = [file for file in os.listdir('./neopixelcontroller/lib/effects') if not file.startswith('.') and not file.startswith('__init__') and not file.endswith('.pyc') and not file.startswith('effect_test')] return [effect.replace('.py', '') for effect in effects] except AttributeError: print("[Controller][error] An error occurred get NeoPixel effects") def clear(self): print("[Controller][info] Clearing pixels on NeoPixel") try: self.stop_effect() self.quit_effect() self.color(Color(0, 0, 0)) self.brightness(0) except AttributeError: print("[Controller][error] An error occurred clearing all pixels on NeoPixel") def cleanup(self): print("[Controller][info] NeoPixel clean up") self.clear() def __exit__(self): print("[Controller][info] NeoPixel exit") self.cleanup()
def exc(): import os import json import math import time from copy import deepcopy from neopixel import Adafruit_NeoPixel basedir = os.path.dirname(os.path.realpath(__file__)) steps = 120 neopixel = Adafruit_NeoPixel(1, 18) neopixel.begin() setting = {'threat': 0, 'cautioning': 0, 'optimum': 1} changelog = [0, 0, 0] if setting['threat'] > 0: changelog[0] = 255 elif setting['cautioning'] > 0: changelog[0] = 255 changelog[1] = 255 elif setting['optimum'] > 0: changelog[1] = 255 if os.path.isfile(basedir + '/ledstate.json'): with open(basedir + '/ledstate.json', 'r') as out: current = json.loads(out.read()) else: raw = neopixel.getPixelColor(0) current = [] for _ in range(3): calc = divmod(raw, 256) raw = calc[0] current.append(calc[1]) current = current[::-1] print(current) bcurrent = [] bchange = [] for pointer in range(len(current)): bcurrent.append( True if current[pointer] > changelog[pointer] else False) bchange.append( True if current[pointer] != changelog[pointer] else False) old = deepcopy(current) for i in range(0, steps + 1): color = [] for pointer in range(len(bchange)): if bchange[pointer]: if not bcurrent[pointer]: x = i offset = current[pointer] else: x = steps - i offset = changelog[pointer] color.append(offset + int( abs(current[pointer] - changelog[pointer]) / steps * x)) # color.append(offset + int(math.cos((1 / steps) * math.pi * x) * (abs(current[pointer] - changelog[pointer]) / 2) + (abs(current[pointer] - changelog[pointer]) / 2))) else: color.append(old[pointer]) print(color) neopixel.setPixelColorRGB(0, color[0], color[1], color[2]) neopixel.show() old = deepcopy(color) # time.sleep(1 / 30) print(color) with open(basedir + '/ledstate.json', 'w') as out: out.write(json.dumps(old))
from neopixel import Color from populate_coldict import popcol LED_NUMBER = 30 STARTING_VAL = 13 BIN_SIZE = 0.06 STEP_MODIFIER = 0.002 SAMPLE_RATE = 44100 CHUNK_SIZE = 192 LOWER_FREQ = 0 HIGHER_FREQ = 16000 light_types = ["volume", "waterfall", "frequency"] strip = Adafruit_NeoPixel(LED_NUMBER, 18, 800000, 5, False, 100) strip.begin() silence = False highest = 0 modifier = 0 prev_highest = 0 prev_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] bin_dict = {} # Creates a threshold for every led, once threshold is surpassed the led is lit for i in range(0, LED_NUMBER): STARTING_VAL += BIN_SIZE bin_dict[i] = STARTING_VAL waterfall_dict = {} for i in range(0, LED_NUMBER):
return self.set_lights(False, True, False) if curtime > self.goaltime - 60: # green return self.set_lights(True, False, False) return self.set_lights(False, False, False) if __name__ == '__main__': try: # create seven segment device serial = spi(port=0, device=0, gpio=noop()) device = max7219(serial, cascaded=1) seg = sevensegment(device) lightstring = Adafruit_NeoPixel(7, 18, 800000, 5, False, 40, 0, ws.WS2811_STRIP_GRB) lightstring.begin() GPIO.setmode(GPIO.BCM) timer = SpeechTimer(seg, minutes=2, startstoppin=13, updownpins=(5, 6), lightpins=None, lightstring=lightstring) # lightpins=(17, 27, 22)) except KeyboardInterrupt: print("Interrupt") finally: print("Cleaning up") GPIO.cleanup()
start = 0 + row_number*ROW_WIDTH end = start + ROW_WIDTH for i in range(start, end): strip.setPixelColor(i, color) strip.show() def fill_up_to(strip, row, color): for i in range(row + 1): setRowColor(strip,i,color) def empty_array(strip): for i in range(256): strip.setPixelColorRGB(i,0,0,0) strip.show() # Main program logic follows: if __name__ == '__main__': # Create NeoPixel object with appropriate configuration. led_array = 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). led_array.begin() while True: color = Color(0, 0, 60) # setRowColor(led_array,1,color) # fill_up_to(led_array,0,color) # sleep(0.1) fill_up_to(led_array,7,color) sleep(5) empty_array(led_array) sleep(3)