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 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()
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 setup_strand(self, gpio_pin, pixel_count, led_frequency, dma, initial_brightness, invert, channel): from neopixel import Adafruit_NeoPixel self.strand = Adafruit_NeoPixel(pixel_count, gpio_pin, led_frequency, dma, invert, initial_brightness, channel) self.strand.begin()
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 __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()
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 __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()
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)
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 __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()
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()
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")
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()
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 _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
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 __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 onJoin(self, details): self._serial = get_serial() self._prefix = 'io.crossbar.demo.iotstarterkit.{}.colorstrip'.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], '{}.{}'.format(self._prefix, proc[1])) yield self.color_wipe(255, 255, 255) self.log.info("ColoramaDisplay ready!") while True: yield self.flash(delay=20, repeat=5) yield self.set_color(40, 40, 40) yield sleep(5) cols = [] for i in range(3): cols.append(random.randint(0, 255)) yield self.color_wipe(*cols, wait_ms=20, repeat=5)
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 __init__(self): self.LED_COUNT = 64 # 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 __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')
def __init__(self): threading.Thread.__init__(self) self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) self.strip.begin() self.exit = False self.command = None self.reply = None self.lock = threading.Condition() self.isConnected = False self.isConnectedTick = 0 self.commandId = 0 logging.info("GpioThread initialized")
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)
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
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)
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 onJoin(self, details): self._serial = get_serial() self._prefix = u'io.crossbar.demo.iotstarterkit.{}.colorstrip'.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])) yield self.color_wipe(255, 255, 255) self.log.info("ColoramaDisplay ready!") # flash + set pixels to white to indicate component running yield self.flash(delay=20, repeat=5) yield self.set_color(40, 40, 40)
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")
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)
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 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 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)
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 __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 __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 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!")
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()
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()
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
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()
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)