def pixel_strip():
    """
    Initialized and started PixelStrip fixture
    """
    ps = PixelStrip(NUM_PIXELS, 0)
    ps.begin()
    return ps
Example #2
0
def setup_strip():
    global LED_BRIGHTNESS
    global which_effect
    which_effect = False
    # LED strip configuration:
    LED_COUNT = 300  # Number of LED pixels.
    LED_PIN = 18  # GPIO pin connected to the pixels (18 uses PWM!).
    # LED_PIN        = 10      # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
    LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
    LED_DMA = 10  # DMA channel to use for generating signal (try 10)
    LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
    LED_INVERT = (
        False  # True to invert the signal (when using NPN transistor level shift)
    )
    LED_CHANNEL = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53
    strip = PixelStrip(
        LED_COUNT,
        LED_PIN,
        LED_FREQ_HZ,
        LED_DMA,
        LED_INVERT,
        LED_BRIGHTNESS,
        LED_CHANNEL,
    )
    # Intialize the library (must be called once before other functions).
    logger.debug(f"Setting up strip")
    strip.begin()
    clear_strip(strip)
    return strip
Example #3
0
    def __init__(self, light_state:LightState):
        super().__init__()
        self.state = light_state
        self.periodic = None
        self.refresh_period_or_duty_cycle()

        self.strip = PixelStrip(self.state.get_num_pixels(), 18)
Example #4
0
    def __init__(self, pixel_count=1, gpio_pin=13, strip_type='WS2812', channel=None, brightness=255, freq_hz=800000, dma=10, invert=False):
        """Initialise WS281X device.

        :param pixel_count: Number of individual RGB LEDs
        :param gpio_pin: BCM GPIO pin for output signal
        :param strip_type: Strip type: one of WS2812 or SK6812
        :param channel: LED channel (0 or 1, or None for automatic)
        :param brightness: Global WS281X LED brightness scale
        :param freq_hz: WS281X output signal frequency (usually 800khz)
        :param dma: DMA channel
        :param invert: Invert signals for NPN-transistor based level shifters

        """
        from rpi_ws281x import PixelStrip, ws

        strip_types = {}
        for t in ws.__dict__:
            if '_STRIP' in t:
                k = t.replace('_STRIP', '')
                v = getattr(ws, t)
                strip_types[k] = v

        strip_type = strip_types[strip_type]

        if channel is None:
            if gpio_pin in [13]:
                channel = 1
            elif gpio_pin in [12, 18]:
                channel = 0

        self._strip = PixelStrip(pixel_count, gpio_pin, freq_hz, dma, invert, brightness, channel, strip_type)
        self._strip.begin()

        Plasma.__init__(self, pixel_count)
 def start_strip(self):
     """
     Start PixelStrip object
     :returns rpi_ws281x.PixelStrip
     """
     self._logger.info("Initialising LED strip")
     strip_settings = self.settings['strip']
     try:
         strip = PixelStrip(
             num=strip_settings['led_count'],
             pin=strip_settings['led_pin'],
             freq_hz=strip_settings['led_freq_hz'],
             dma=strip_settings['led_dma'],
             invert=strip_settings['led_invert'],
             brightness=strip_settings['led_brightness'],
             channel=strip_settings['led_channel'],
             strip_type=STRIP_TYPES[strip_settings['strip_type']])
         strip.begin()
         self._logger.info("Strip object successfully initialised")
         return strip
     except Exception as e:  # Probably wrong settings...
         self._logger.error(
             "Strip failed to initialize, no effects will be run.")
         self._logger.error("Please check your settings.")
         self._logger.error("Here's the exception: {}".format(e))
         return None
def turn_lights_off(strip: ws.PixelStrip, runtime: float = RUNTIME):
    print(f"Turning the lights off over {runtime}s")
    weather = get_weather()
    WEATHER_ANIMATIONS[weather](strip, runtime, reverse=True)
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, ws.Color(0, 0, 0))
    strip.show()
Example #7
0
def setup_led_strips():
    # Create PixelStrip object with appropriate configuration
    global strip
    strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                       LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
    # Initialize the library (must be called once before other functions)
    strip.begin()
Example #8
0
    def __init__(self, rows, columns, serial_type=1, led_pin=18):
        ##
        # serial_type 信号线连接方式, 1表示弓字形连线,2表示Z字形连线
        ##
        self.rows = rows
        self.columns = columns
        self.led_numbers = rows * columns
        self._mod = 1
        self.leds = []
        for i in range(self.led_numbers):
            self.leds.append(LED(i))

        self.led_index = [[0 for i in range(self.columns)]
                          for i in range(self.rows)]
        if (serial_type == 1):
            for i in range(0, rows, 2):
                for j in range(0, self.columns):
                    self.led_index[i][j] = i * self.columns + j

            for i in range(1, rows, 2):
                for j in range(0, self.columns):
                    self.led_index[i][j] = (i + 1) * self.columns - (j + 1)
        elif (serial_type == 2):
            for i in range(0, rows):
                for j in range(0, columns):
                    self.led_index[i][j] = i * self.columns + j

        self.strip = PixelStrip(self.led_numbers, led_pin)
        self.strip.begin()
        self.strip.setBrightness(255)
    class __LedCore:
        def __init__(self):
            # Create NeoPixel object with appropriate configuration.
            self.strip = PixelStrip(
                settings.LED_COUNT,
                settings.LED_PIN,
                settings.LED_FREQ_HZ,
                settings.LED_DMA,
                settings.LED_INVERT,
                settings.LED_BRIGHTNESS,
                settings.LED_CHANNEL,
            )
            # Intialize the library (must be called once before other functions).
            self.strip.begin()

            self.thread = None
            self.strip_actions = StripActions()

        def strip_action(self, name, **kwargs):
            if (issubclass(type(self.thread), StoppableThread)
                    and self.thread.is_alive() and not self.thread.stopped()):
                self.thread.stop()
                self.thread.join()
            self.thread = getattr(self.strip_actions, name)(self.strip,
                                                            **kwargs)
            return self.thread
 def start_strip(self):
     """
     Start PixelStrip object
     :returns strip: (rpi_ws281x.PixelStrip) The initialised strip object
     """
     self._logger.info("Initialising LED strip")
     try:
         strip = PixelStrip(
             num=int(self.strip_settings["count"]),
             pin=int(self.strip_settings["pin"]),
             freq_hz=int(self.strip_settings["freq_hz"]),
             dma=int(self.strip_settings["dma"]),
             invert=bool(self.strip_settings["invert"]),
             brightness=int(self.strip_settings["brightness"]),
             channel=int(self.strip_settings["channel"]),
             strip_type=constants.STRIP_TYPES[self.strip_settings["type"]],
         )
         strip.begin()
         self._logger.info("Strip successfully initialised")
         return strip
     except Exception as e:  # Probably wrong settings...
         self._logger.error(repr(e))
         self._logger.error(
             "Strip failed to initialize, no effects will be run.")
         raise StripFailedError("Error intitializing strip")
Example #11
0
 def __init__(self):
     self.gammaTable = [
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4,
         5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
         12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19,
         20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30,
         31, 31, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 43,
         44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
         60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77,
         78, 79, 80, 81, 83, 84, 85, 86, 88, 89, 90, 91, 93, 94, 95, 96, 98,
         99, 100, 102, 103, 104, 106, 107, 109, 110, 111, 113, 114, 116,
         117, 119, 120, 121, 123, 124, 126, 128, 129, 131, 132, 134, 135,
         137, 138, 140, 142, 143, 145, 146, 148, 150, 151, 153, 155, 157,
         158, 160, 162, 163, 165, 167, 169, 170, 172, 174, 176, 178, 179,
         181, 183, 185, 187, 189, 191, 193, 194, 196, 198, 200, 202, 204,
         206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 227, 229, 231,
         233, 235, 237, 239, 241, 244, 246, 248, 250, 252, 255
     ]
     self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                             LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
     self.strip.begin()
     self.cols = []
     self.hues = np.arange(360, step=10)
     for i in range(36):
         self.cols.append(hsv2rgb(self.hues[i] / 360, 1, 1))
Example #12
0
    def dosetup(self):
        """ Init. of a default rgb strip

        Note:
            The config file need to be loaded before calling this method

        """
        fix = 0
        if self.BROKEN_PCB:
            fix = 1
        LED_COUNT = (
            (self.FRET_CNT + self.CONFIG["TOP_INSTALLED"]) * self.STRING_CNT +
            fix)
        LED_PIN = 18
        LED_FREQ = 800000
        LED_DMA = 10
        LED_BRIGHTNESS = self.CONFIG["BRIGHTNESS"]
        self.LED_STRIP = PixelStrip(\
                                    LED_COUNT,\
                                    LED_PIN,\
                                    LED_FREQ,\
                                    LED_DMA,\
                                    False,\
                                    LED_BRIGHTNESS)
        self.LED_STRIP.begin()
Example #13
0
def clear_strip(strip: PixelStrip):
    """Turn all lights off instantly.

    :return:
    """
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color(0, 0, 0))
    strip.show()
 def __init__(self, LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
              LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP):
     self._strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                              LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,
                              LED_STRIP)
     self._strip.begin()
     self._step = 0.5
     self._start = 0
Example #15
0
    def __init__(self, pixels):
        # the imports must be hidden since they won't work on pc
        from rpi_ws281x import PixelStrip

        # init the pixel strip
        self.np = PixelStrip(pixels, 18, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.np.begin()
        self.pixel_count = pixels
Example #16
0
    def __init__(self, pin: int, nb_led: int = 5):
        self.pixels = PixelStrip(nb_led, pin)
        self.pixels.begin()
        self._state: bool = False
        self.delay: float = 0.01
        self._mode: int = MODE_RGB

        self.off()
Example #17
0
 def __init__(self, width, height, serpentine=False, name=None):
     self.serpentine = serpentine
     super().__init__(np.zeros((height, width, 3), dtype=np.uint8),
                      8,
                      name=name)
     self.pixelstrip = PixelStrip(self.height * self.width, LED_PIN,
                                  LED_FREQ_HZ, LED_DMA, LED_INVERT,
                                  LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA)
Example #18
0
 def __init__(self):
     if LedManager.__instance is None:
         LedManager.__instance = self
         self.strip = PixelStrip(self.__LED_COUNT, self.__LED_PIN, self.__LED_FREQ_HZ, self.__LED_DMA,
                                 self.__LED_INVERT, self.__LED_BRIGHTNESS, self.__LED_CHANNEL, self.__LED_STRIP)
         self.strip.begin()
     else:
         raise Exception("This class is a Singleton")
Example #19
0
 def __init__(self, width, height, led_pin=18, map=None, name=None):
     self.map = map
     if self.map is None:
         n_leds = self.height * self.width
     else:
         n_leds = len(self.map)
     super().__init__(np.zeros((height, width, 3), dtype=np.uint8), 8, name=name)
     self.pixelstrip = PixelStrip(n_leds, led_pin, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA)
Example #20
0
    def __init__(self, pixels):
        # the imports must be hidden since they won't work on pc
        from rpi_ws281x import PixelStrip

        # init the pixel strip
        self.np = PixelStrip(pixels, PIN)
        self.np.begin()
        self.pixel_count = pixels
        self.is_stopped = False
Example #21
0
 def __init__(self):
     # strip = None
     # self.DotCount = LED_COUNT
     # Create NeoPixel object with appropriate configuration.
     self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                             LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
     # Intialize the library (must be called once before other functions).
     self.strip.begin()
     self.DotCount = self.strip.numPixels()
Example #22
0
 def __init__(self):
     # Create NeoPixel object with appropriate configuration.
     self.strip = PixelStrip(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ,
                             self.LED_DMA, self.LED_INVERT,
                             self.LED_BRIGHTNESS, self.LED_CHANNEL,
                             self.LED_STRIP)
     # Intialize the library (must be called once before other functions).
     self.strip.begin()
     self.colorFill(Color(0, 0, 0, 0))
Example #23
0
def getPixels(strip: PixelStrip):
    num_pixels = strip.numPixels()
    all_pixels = []
    for i in range(num_pixels):
        c = strip.getPixelColorRGB(i)
        # all_pixels.append((c.r, c.g, c.b))
        all_pixels.append(c)

    return all_pixels
Example #24
0
    def __init__(self, led_count, led_pin, led_freq_hz, led_dma, led_invert,
                 led_brightness, led_channel):
        self.strip = PixelStrip(led_count, led_pin, led_freq_hz, led_dma,
                                led_invert, led_brightness, led_channel)
        self.strip.begin()

        self.led_count = led_count
        self.pixels = [Pixel(self.strip, x) for x in range(led_count)]

        signal.signal(signal.SIGINT, self.signal_handler)
Example #25
0
def init():
    global strip
    LED_COUNT = cfg["WS8211"].getint("count", 6)
    LED_PIN = cfg["WS8211"].getint("pin", 12)
    LED_FREQ_HZ = cfg["WS8211"].getint("frequence", 800000)
    LED_DMA = cfg["WS8211"].getint("dma", 10)
    LED_INVERT = cfg["WS8211"].getboolean("invert", False)
    LED_BRIGHTNESS = cfg["WS8211"].getint("brightness", 50)
    LED_CHANNEL = cfg["WS8211"].getint("channel", 0)
    strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                       LED_BRIGHTNESS, LED_CHANNEL)
    strip.begin()
Example #26
0
    def __init__(self):
        # Create NeoPixel object with appropriate configuration.
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

        for i, led_counter in enumerate(NUMBER_OF_LEDS):
            # get last led
            start = 0 if i == 0 else (self[-1][-1] + 1)
            # define step 
            step = Step(self.strip, start, start + led_counter)
            self.append(step)
def dither_fade(
    strip: ws.PixelStrip,
    new_color: Union[ws.Color, np.array],
    leds_to_switch: Optional[Iterable[int]] = None,
    dither_time: float = 1,
):
    """
    Dither in to a new set of colours by switching small batches of pixels.

    Parameters
    ---------
    strip
        the LED strip to animate
    new_color
        Either a single ws.Color or an array of them. Providing one colour acts as an array of that one colour.
    leds_to_switch
        Only dither these LEDs to leave specific elements static.
    dither_time
        the time over which to dither. Do not make this too short
    """

    try:
        iter(new_color)
    except TypeError:
        # this is not iterable, therefore it is one colour.
        # Make an array of that colour.
        new_color = np.array([new_color for _ in range(strip.numPixels())])

    start_time = time.time()
    if leds_to_switch is None:
        leds_to_switch = [i for i in range(strip.numPixels())]
    random.shuffle(leds_to_switch)

    num_leds = len(leds_to_switch)
    # As a rough rule of thumb, it takes 0.005 seconds to switch an LED and render an
    # update. Calculate the group size dynamically to fit into our time budget.

    min_update_time = 0.005
    switches_in_time = int(round(dither_time / min_update_time))
    batch_size = int(round((strip.numPixels() / switches_in_time) + 0.5))
    if batch_size != 1:
        num_batches = int(round((strip.numPixels() / batch_size)))
        batch_size = int(round((strip.numPixels() / num_batches)))

    while leds_to_switch:
        these_leds = [leds_to_switch.pop() for _ in range(batch_size) if leds_to_switch]
        for this_led in these_leds:
            strip.setPixelColor(this_led, new_color[this_led])
        time.sleep(dither_time / (batch_size * num_leds))
        strip.show()

    # Sometimes we go too fast with the switching, as
    # the batching approximation is horrible. If we
    # do, just chill here before moving on
    end_time = time.time()
    time_diff = end_time - start_time
    if time_diff < dither_time:
        time.sleep(dither_time - time_diff)
def alternate_colors(strip: ws.PixelStrip, colors: Optional[Iterable[ws.Color]] = None):
    """
    Show a set of colours along the strip.

    :param strip: the strip to show the colors on
    :param colors: a list of colors to show
    """
    if colors is None:
        colors = [ws.Color(255, 0, 0), ws.Color(0, 255, 0), ws.Color(0, 0, 255)]
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, colors[i % len(colors)])
    strip.show()
def color_wipe(strip: ws.PixelStrip, color: ws.Color, wait_ms: float = 50.0):
    """
    Wipe color across display a pixel at a time.

    :param strip: the strip to animate
    :param color: the color to set each pixel to
    :param wait_ms: the time between animating each pixel, in milliseconds
    """
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color)
        strip.show()
        time.sleep(wait_ms / 1000.0)
Example #30
0
 def Start(self):
     """ Initialize the LED strip at the hardware level so that we can start control the individual LEDs. """
     self._strip=PixelStrip(self._ledCount, \
                 self._stripGpioPin, \
                 self._ledFrequency, \
                 self._ledDmaChannel, \
                 self._ledInvert, \
                 self._ledBrightness, \
                 self._ledChannel, \
                 self._stripType)
     # Initialize the library (must be called once before other functions):
     self._strip.begin()
Example #31
0
        time.sleep(wait_ms/1000.0)

def rainbowCycle(strip, wait_ms=20, iterations=2):
    """Draw rainbow that uniformly distributes itself across all pixels."""
    for j in range(256*iterations):
        for i in range(strip.numPixels()):
            strip.setPixelColor(i, wheel(((i * 256 / strip.numPixels()) + j) & 255))
        strip.show()
        time.sleep(wait_ms/1000.0)

# Main loop:
if __name__ == '__main__':
    # Create NeoPixel object with appropriate configuration.
    #strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
    if __version__ == "legacy":
        strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
    else:
        strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA)# Intialize the library (must be called once before other functions).

    strip.begin()

    ## Color wipe animations.
    colorWipe(strip, Color(127, 0, 0), WAIT_MS)  # Red wipe
    colorWipe(strip, Color(0, 127, 0), WAIT_MS)  # Green wipe
    colorWipe(strip, Color(0, 0, 127), WAIT_MS)  # Blue wipe
    colorWipe(strip, Color(0, 0, 0), WAIT_MS)  # Off wipe

    ## Rainbow animations.
    #rainbow(strip)
    #rainbowCycle(strip)
    #colorWipe(strip, Color(0, 0, 0))  # Off wipe