Example #1
0
class Leds:
    def __init__(self, count, pin=21, br=100):
        """
        LEDs
        """
        self.LED_COUNT = count
        LED_PIN = pin  # GPIO пин, к которому вы подсоединяете светодиодную ленту
        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 = br  # 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

        self.strip = Adafruit_NeoPixel(self.LED_COUNT, LED_PIN, LED_FREQ_HZ,
                                       LED_DMA, LED_INVERT)
        self.strip.begin()

    def setPixelsColor(self, color):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    def setPixelColor(self, color):
        self.strip.setPixelColor(i, color)
        self.strip.show()

    def colorWipe(self, color, wait_ms=50):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
Example #2
0
class Strip:
    def __init__(self):
        self.strip = Adafruit_NeoPixel(
            LED_COUNT,
            LED_PIN,
            LED_FREQ_HZ,
            LED_DMA,
            LED_INVERT,
            LED_BRIGHTNESS,
            LED_CHANNEL,
        )
        self.strip.begin()

    def clear(self):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, Color.rgb(0, 0, 0).toLED())
        self.show()

    def show(self):
        self.strip.show()

    def set_color(self, obj):
        if type(obj) == Key:
            self.strip.setPixelColor(obj.led_index, obj.led.color.toLED())
        elif type(obj) == Keyboard:
            for key in obj.keys:
                if key.led.color:
                    self.strip.setPixelColor(key.led_index,
                                             key.led.color.toLED())
Example #3
0
class StripManager:

    @staticmethod
    def default():
        led_count = 159  # Number of LED pixels.
        led_pin = 18  # 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
        return StripManager(led_count, led_pin, led_freq_hz, led_dma, led_invert, led_brightness, led_channel)

    def __init__(self, led_count, led_pin, led_freq_hz, led_dma, led_invert, led_brightness, led_channel):
        self.strip = Adafruit_NeoPixel(led_count, led_pin, led_freq_hz, led_dma, led_invert, led_brightness,
                                       led_channel)
        self.strip.begin()

    def solid_color(self, r, g, b):
        self.strip.setBrightness(255)
        for i in range(0, self.strip.numPixels()):
            self.strip.setPixelColor(i, Color(r, g, b))
            self.strip.show()

    def alert(self, r, g, b, wait_ms=50, iterations=10):
        for j in range(iterations):
            for q in range(3):
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, Color(r, g, b))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    def clear(self):
        self.solid_color(0, 0, 0)

    def orange(self):
        self.solid_color(255, 64, 0)
    def __init__(self, strip: Adafruit_NeoPixel, num_segments: int,
                 leds_per_segment: int):
        required_leds = num_segments * leds_per_segment

        if strip.numPixels() < num_segments * leds_per_segment:
            raise ValueError(
                f"LED strip has {strip.numPixels()} pixels but requires {required_leds}"
            )

        self.strip = strip
        self.num_segments = num_segments
        self.leds_per_segment = leds_per_segment

        self._black_color = Color(0, 0, 0)
Example #5
0
class LED():
    def __init__(self):
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ,
                                       LED_DMA, LED_INVERT, LED_BRIGHTNESS,
                                       LED_CHANNEL)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def colorWipe(self, rgb, wait_ms=50):
        """Wipe color across display a pixel at a time.
        :param rgb: color
        :type rgb: tuple(int, int, int) 
        """
        color = Color(*rgb)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 10000.0)
Example #6
0
class LedControl:
    def __init__(self):
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(
            LED_COUNT,
            LED_PIN,
            LED_FREQ_HZ,
            LED_DMA,
            LED_INVERT,
            LED_BRIGHTNESS,
            LED_CHANNEL,
        )
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def color_wipe(self, color):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    def transition_to_white(self, steps=18000, timestep=100):
        """
        Transition all leds to white
        :param steps: number of steps in transition
        :param timestep: time that one step takes in ms
        """
        final_color = np.array([255, 255, 255])
        start_color = np.array([0, 0, 0])
        color_delta = final_color - start_color
        for i in range(steps):
            # create linear i in range 0 to 100
            lin_range = i / (steps - 1) * 100
            # create exponential range from 1 to exp(100)
            log_range = np.exp(lin_range)
            # create exponential range from 0 to 1
            log_range = (log_range - 1) / (np.exp(100) - 1)
            color = start_color + color_delta * lin_range / 100  # log_range
            self.color_wipe(Color(int(color[0]), int(color[1]), int(color[2])))
            time.sleep(timestep / 1000)
Example #7
0
class RGB(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.thread_name = "RGB_LIGHT"
        self.strip = Adafruit_NeoPixel(configs.LED_COUNT, configs.LED_PIN,
                                       configs.LED_FREQ_HZ, configs.LED_DMA,
                                       configs.LED_INVERT,
                                       configs.LED_BRIGHTNESS)
        self.strip.begin()
        init_color = Color(0, 0, 0)
        self.led_colors = [init_color for i in range(configs.LED_COUNT)]
        # 预警返回值,如果为1,则需要颜色预警
        self.remind_type = 0
        my_print(self, 'init done!')

    def run(self) -> None:
        while True:
            if self.remind_type:
                # 先清除颜色
                self.colorWipe(Color(0, 0, 0), 0)
                self.breath_chase()
                self.remind_type = 0
            self.rainbowCycle()

    #功能一-逐个变色-
    # colorWipe(self.strip, Color(255, 0, 0))  # Red wipe
    # 所有灯逐个变成红色
    def colorWipe(self, color, wait_ms=50):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    # 呼吸闪烁
    def breath_chase(self, wait_ms=3):
        for i in range(0, 255, 3):
            now_color = Color(i, 0, 0)
            # 所有灯珠设置一遍
            self.colorWipe(now_color, 0)
            # 延时
            time.sleep(wait_ms / 1000.0)
        for i in range(255, 0, -3):
            now_color = Color(i, 0, 0)
            self.colorWipe(now_color, 0)
            time.sleep(wait_ms / 1000.0)

    # 渐变至某个颜色
    def gradient_change(self, color):
        pass

    # 白色交替闪烁
    def theaterChase(self, color, wait_ms=50, iterations=10):
        """Movie theater light style chaser animation."""
        for j in range(iterations):
            for q in range(3):
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, color)
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    # 支撑函数
    def wheel(self, pos):
        """Generate rainbow colors across 0-255 positions."""
        if pos < 85:
            return Color(pos * 3, 255 - pos * 3, 0)
        elif pos < 170:
            pos -= 85
            return Color(255 - pos * 3, 0, pos * 3)
        else:
            pos -= 170
            return Color(0, pos * 3, 255 - pos * 3)

    #功能三-彩虹色整体统一柔和渐变-每个灯颜色同一时间相同
    def rainbow(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.strip.numPixels()):
                self.strip.setPixelColor(i, self.wheel((i + j) & 255))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    #功能四-彩虹色每一个灯各自柔和渐变-每个灯颜色同一时间不同
    def rainbowCycle(self, wait_ms=20, iterations=5):
        """Draw rainbow that uniformly distributes itself across all pixels."""
        for j in range(256 * iterations):
            # 如果颜色渐变的时候预警了,推出循环
            if self.remind_type == 1:
                break
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(
                    i,
                    self.wheel((int(i * 256 / self.strip.numPixels()) + j)
                               & 255))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    #功能五-彩虹色统一闪烁流动变色-每个灯颜色同一时间相同
    def theaterChaseRainbow(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.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, self.wheel((i + j) % 255))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    def test(self):
        print('Color wipe animations.')
        self.colorWipe(Color(155, 0, 0))  # Red wipe
        self.colorWipe(Color(0, 255, 0))  # Blue wipe
        self.colorWipe(Color(0, 0, 255))  # Green wipe
        print('Theater chase animations.')
        self.theaterChase(Color(127, 127, 127))  # White theater chase
        self.theaterChase(Color(127, 0, 0))  # Red theater chase
        self.theaterChase(Color(0, 0, 127))  # Blue theater chase
        print('Rainbow animations.')
        self.rainbow()
        self.rainbowCycle()
        self.theaterChaseRainbow()
Example #8
0

strip1 = Adafruit_NeoPixel(LED_1_COUNT, LED_1_PIN, 800000, 5, False,
                           LED_1_BRIGHTNESS, 0, ws.WS2811_STRIP_GRB)
strip1.begin()

strip2 = Adafruit_NeoPixel(LED_2_COUNT, LED_2_PIN, 800000, 6, False,
                           LED_2_BRIGHTNESS, 0, ws.WS2811_STRIP_GRB)
strip2.begin()

# strip3 = Adafruit_NeoPixel(LED_3_COUNT, LED_3_PIN, 800000, 7, False, LED_2_BRIGHTNESS, 0, ws.WS2811_STRIP_GRB)
# strip3.begin()

if __name__ == '__main__':
    while True:
        for i in range(strip1.numPixels()):
            strip1.setPixelColor(i, COLOR.RED)
        strip1.show()

        for i in range(strip2.numPixels()):
            strip2.setPixelColor(i, COLOR.GREEN)
        strip2.show()

        # for i in range(strip3.numPixels()):
        # 	strip3.setPixelColor(i, COLOR.BLUE)
        # strip3.show()

        time.sleep(1)

        for i in range(strip1.numPixels()):
            strip1.setPixelColor(i, COLOR.GREEN)
Example #9
0
class PiCamera(Camera):
    """
    Adapted from PyImageSearch
    https://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/
    """

    def __init__(self, window_name="PiCamera", algorithm=None):
        # Ensure object is created in RPi
        if not self.can_run():
            raise RuntimeError("PiCamera only allowed to be run via RPi. "
                               "Please use camera.Webcam for testing purposes.")

        from picamera.array import PiRGBArray
        from picamera import PiCamera

        # define camera
        self.camera = PiCamera()
        self.camera.resolution = (CAMERA_WIDTH, CAMERA_HEIGHT)
        self.camera.framerate = 30
        # grab reference to the raw camera capture
        self.rawCapture = PiRGBArray(self.camera)

        # setup lights
        from rpi_ws281x import Adafruit_NeoPixel, Color
        self.strip = Adafruit_NeoPixel(8, 18, 800000, 10, False, 255, 0)
        self.strip.begin()

        # Allow camera to warm up
        time.sleep(0.1)
        super().__init__(window_name, algorithm)

    def set_light_color(self, color):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    @staticmethod
    def can_run() -> bool:
        import os
        return os.uname()[4][:3] == "arm"

    def draw(self):
        self.camera.capture(self.rawCapture, format="bgr")
        image = self.rawCapture.array

    def process_video(self):
        # begin frame loop
        for frame in self.camera.capture_continuous(
                self.rawCapture,
                format="bgr",
                use_video_port=True
        ):
            # grab the raw numpy array representing the image
            image = frame.array

            image = self.algorithm.run(image).labelled_frame

            # show the frame
            cv2.imshow("Frame", image)
            key = cv2.waitKey(1) & 0xFF

            # clear the stream in preparation for the next frame
            self.rawCapture.truncate(0)

            # allow exit when 'q' is pressed
            if key == ord("q"):
                break

    def process_image(self):
        # capture image and get np array
        self.set_light_color(Color(255, 255, 255))
        self.camera.capture(self.rawCapture, format="bgr")
        image = self.rawCapture.array

        # process image
        image = self.algorithm(image).run().labelled_frame

        # display the image on screen
        cv2.imshow("Image", image)
        # also output with text and audio
        self.output_sound(image)

        # allow exit when any key is pressed
        print("Press any key to exit.")
        cv2.waitKey(0)

    def destroy(self):
        super().destroy()
        # clear lights
        self.set_light_color(Color(0, 0, 0))
Example #10
0
class PiStripLed(piIotNode.PiIotNode):
    """ encapsulates the RGB led strip using ws281x """
    def __init__(self,
                 name,
                 parent,
                 ledCount,
                 ledPin,
                 freq=800000,
                 dmaChannel=10,
                 invert=False,
                 brightness=255,
                 ledChannel=0,
                 debug=False):
        """ construct a strip led """
        super(PiStripLed, self).__init__(name, parent)
        self.debug = debug
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(ledCount, ledPin, freq, dmaChannel,
                                       invert, brightness, ledChannel)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def setPixel(self, i, red, green, blue):
        """ set color for a single pixel with red, green, blue values"""
        self.setPixelColor(i, Color(red, green, blue))

    def setPixelRGB(self, i, rgb):
        """ set color for a single pixel with RGB object """
        red, green, blue = rgb.toRGBList()
        self.setPixelColor(i, Color(int(red), int(green), int(blue)))

    def setPixelRGBStr(self, i, rgbStr):
        """ set color for a single pixel with RGB string """
        red, green, blue = rgbStr.split(',')
        self.setPixelColor(i, Color(int(red), int(green), int(blue)))

    def setPixelColor(self, i, color):
        """ set color for a single pixel with rpi_ws281x Color object """
        self.strip.setPixelColor(i, color)
        self.strip.show()

    def setAllPixels(self, red, green, blue, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        self.setAllPixelsColor(Color(red, green, blue), delay_ms)

    def setAllPixelsRGB(self, rgb, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        red, green, blue = rgb.toRGBList()
        self.setAllPixelsColor(Color(red, green, blue), delay_ms)

    def setAllPixelsRGBStr(self, rgbStr, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        red, green, blue = rgbStr.split(',')
        self.setAllPixelsColor(Color(int(red), int(green), int(blue)),
                               delay_ms)

    def setAllPixelsColor(self, color, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(delay_ms / 1000.0)

    @staticmethod
    def wheel(pos):
        """ generate rainbow colors across 0-255 positions """
        if pos < 85:
            return Color(pos * 3, 255 - pos * 3, 0)
        elif pos < 170:
            pos -= 85
            return Color(255 - pos * 3, 0, pos * 3)
        else:
            pos -= 170
            return Color(0, pos * 3, 255 - pos * 3)

    def rainbowCycle(self, delay_ms=20, iterations=5):
        """ Draw rainbow that uniformly distributes itself across all pixels """
        self._debugInfo('start rainbowCycle')
        for j in range(256 * iterations):
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(
                    i,
                    PiStripLed.wheel((int(i * 256 / self.strip.numPixels()) +
                                      j) & 255))
            self.strip.show()
            time.sleep(delay_ms / 1000.0)
        self._debugInfo('end rainbowCycle')

    def theaterChaseRainbow(self, delay_ms=50):
        """Rainbow movie theater light style chaser animation."""
        self._debugInfo('start theaterChaseRainbow')
        for j in range(256):
            for q in range(3):
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q,
                                             PiStripLed.wheel((i + j) % 255))
                self.strip.show()
                time.sleep(delay_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)
        self._debugInfo('end theaterChaseRainbow')

    def _debugInfo(self, msg):
        """ print debug info when debug is enabled """
        if self.debug:
            print(msg)
Example #11
0
#以下LED配置无需修改
LED_FREQ_HZ = 800000  # LED信号频率(以赫兹为单位)(通常为800khz)
LED_DMA = 10  # 用于生成信号的DMA通道(尝试5)
LED_INVERT = False  # 反转信号(使用NPN晶体管电平移位时)

# 创建NeoPixel对象
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                          LED_BRIGHTNESS)
# 初始化库
strip.begin()

#设置整体亮度 关闭LED为0 最亮为255 范围0-255
#该函数与下面的设置颜色都不会直接对LED进行修改,可以理解为将修改数据保存到缓存区。
#strip.setBrightness(200)

#numPixels()函数介绍:取NeoPixel对象创建时设置的LED数量
for i in range(0, strip.numPixels()):  #设置个循环(循环次数为LED数量)

    # setPixelColor()函数介绍:设置LED色值(RGB).
    #参数1:LED 的ID (从0开始, 比如第5个LED)
    #参数2:RGB色值  Color()RGB转Color值,参数依次为R,G,B
    #例子:设置第5个LED颜色为红色
    #       strip.setPixelColor(4, Color(255,0,0))
    #该函数不会直接对LED进行修改,可以理解为将修改数据保存到缓存区。
    strip.setPixelColor(i, Color(0, 0, 255))

    #提交缓存区的修改数据到WS2812B,以显示效果
    strip.show()

    time.sleep(0.1)  #延迟0.1秒
Example #12
0
class LedManager:
    def __init__(self, brightness=None):
        if brightness == None:
            brightness = cs.LED_STRIP_BRIGHTNESS
        if brightness < 0:
            brightness = 0
        elif brightness > 255:
            brightness = 255
        self.strip = Adafruit_NeoPixel(cs.LED_COUNT, cs.LED_PIN,
                                       cs.LED_FREQ_HZ, cs.LED_DMA,
                                       cs.LED_INVERT, brightness,
                                       cs.LED_CHANNEL)
        self.strip.begin()
        self.OFF_COLOR = Color(0, 0, 0)
        self.R = Color(255, 0, 0)
        self.G = Color(0, 255, 0)
        self.B = Color(0, 0, 255)
        self.W = Color(255, 255, 255)
        self.DEFAULT_COLOR = Color(cs.LED_STRIP_DEFAULT_COLOR[0],
                                   cs.LED_STRIP_DEFAULT_COLOR[1],
                                   cs.LED_STRIP_DEFAULT_COLOR[2])

    def getColorFromTuple(self, rgb):
        return Color(rgb[0], rgb[1], rgb[2])

    def test(self):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.R)
        self.strip.show()
        time.sleep(1)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.G)
        self.strip.show()
        time.sleep(1)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.B)
        self.strip.show()
        time.sleep(1)
        self.clear()

    def testWheel(self, pos):
        # from https://github.com/jgarff/rpi_ws281x/blob/master/python/examples/strandtest.py
        """Generate rainbow colors across 0-255 positions."""
        if pos < 85:
            return Color(pos * 3, 255 - pos * 3, 0)
        elif pos < 170:
            pos -= 85
            return Color(255 - pos * 3, 0, pos * 3)
        else:
            pos -= 170
            return Color(0, pos * 3, 255 - pos * 3)

    def testTheaterChaseRainbow(self, wait_ms=50):
        # from https://github.com/jgarff/rpi_ws281x/blob/master/python/examples/strandtest.py
        """Rainbow movie theater light style chaser animation."""
        for j in range(256):
            for q in range(3):
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q,
                                             self.testWheel((i + j) % 255))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    def testRightLeftBack(self):
        for i in cs.LEDS_RIGHT:
            self.strip.setPixelColor(i, self.R)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_BACK:
            self.strip.setPixelColor(i, self.G)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_LEFT:
            self.strip.setPixelColor(i, self.B)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_BEFORE:
            self.strip.setPixelColor(i, self.W)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_AFTER:
            self.strip.setPixelColor(i, self.W)
        self.strip.show()
        time.sleep(1)

    def clear(self):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.OFF_COLOR)
        self.strip.show()

    def loadUserMode(self):
        col = self.getColorFromTuple(cs.USER_LOAD_COLOR)
        self.clear()
        time.sleep(0.3)
        for i in range(self.strip.numPixels(), 0, -1):
            self.strip.setPixelColor(i, col)
            time.sleep(0.1)
            self.strip.show()
        self.blink(blinkTime=0.6, col=col)

    def unloadUserMode(self):
        col = self.getColorFromTuple(cs.USER_LOAD_COLOR)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.OFF_COLOR)
            time.sleep(0.1)
            self.strip.show()

    def showResult(self, result):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(
                i, self.R if
                (i < result * self.strip.numPixels() / 6.) else self.OFF_COLOR)
        self.strip.show()

    def setLeds(self, leds, r, g, b):
        for i in leds:
            self.strip.setPixelColor(i, Color(r, g, b))
        self.strip.show()

    def setAllLeds(self, color=None, r=None, g=None, b=None):
        if color is None:
            color = self.DEFAULT_COLOR
        if r is not None and g is not None and b is not None:
            color = Color(clamp255(r), clamp255(g), clamp255(b))
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    def blink(self, blinkTime=0.01, col=None, repeat=3, keepLight=True):
        if col is None:
            col = self.W
        for i in range(repeat):
            self.setAllLeds(col)
            time.sleep(blinkTime)
            self.clear()
            time.sleep(blinkTime)
        if keepLight:
            self.setAllLeds(col)
Example #13
0
LED_PIN = 18  # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10  # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
# True to invert the signal (when using NPN transistor level shift)
LED_INVERT = False

# Main program logic follows:
if __name__ == '__main__':
    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                              LED_INVERT, LED_BRIGHTNESS)
    # Intialize the library (must be called once before other functions).
    strip.begin()

    for i in range(0, strip.numPixels(), 1):
        strip.setPixelColor(i, Color(0, 0, 0))
    while True:
        now = datetime.datetime.now()

        # Low light during 19-8 o'clock
        if (8 < now.hour < 19):
            strip.setBrightness(200)
        else:
            strip.setBrightness(25)

        hour = now.hour % 12
        minute = now.minute / 5
        second = now.second / 5
        secondmodulo = now.second % 5
        timeslot_in_microseconds = secondmodulo * 1000000 + now.microsecond
Example #14
0
class LedController(Actuator):
    """Implementation for the Neopixel Programmable RGB LEDS. Extends 
    :class:`Actuator`.
    
    It use's rpi_ws281x library.

    Args:
        led_count (int): Number of leds.
        led_pin (int): GPIO pin connected to the pixels.
        led_freq_hz (int): LED signal frequency in hertz (usually 800khz)
        led_brightness (int): Set to 0 for darkest and 255 for brightest
        led_dma (int): DMA channel to use for generating signal.
            Defaults to :data:`10`.
        led_invert (boolean): True to invert the signal 
            (when using NPN transistor level shift). Defaults to :data:`False`.
        led_channel (int): Set to '1' for GPIOs 13, 19, 41, 45 or 53. Defaults
            to :data:`0`.
        led_strip: Strip type and colour ordering. Defaults to 
            :data:`ws.WS2811_STRIP_RGB`.
    """
    def __init__(self,
                 led_count,
                 led_pin,
                 led_freq_hz,
                 led_brightness,
                 led_dma=10,
                 led_invert=False,
                 led_channel=0,
                 led_strip=ws.WS2811_STRIP_RGB,
                 name=""):
        """Constructor"""

        self._led_count = led_count
        self._led_pin = led_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._led_strip = led_strip

        # Set the id of the actuator
        super(LedController, self).__init__(name)

        self.start()

    @property
    def led_count(self):
        """Number of leds."""
        return self._led_count

    @led_count.setter
    def led_count(self, x):
        self._led_count = x

    @property
    def led_pin(self):
        """GPIO pin connected to the pixels."""
        return self._led_pin

    @led_pin.setter
    def led_pin(self, x):
        self._led_pin = x

    @property
    def led_freq_hz(self):
        """LED signal frequency in hertz."""
        return self._led_freq_hz

    @led_freq_hz.setter
    def led_freq_hz(self, x):
        self._led_freq_hz = x

    @property
    def led_brightness(self):
        """Set to 0 for darkest and 255 for brightest."""
        return self._led_brightness

    @led_brightness.setter
    def led_brightness(self, x):
        self._led_brightness = x

    @property
    def led_dma(self):
        """DMA channel to use for generating signal."""
        return self._led_dma

    @led_dma.setter
    def led_dma(self, x):
        self._led_dma = x

    @property
    def led_invert(self):
        """True to invert the signal."""
        return self._led_invert

    @led_invert.setter
    def led_invert(self, x):
        self._led_invert = x

    @property
    def led_channel(self):
        """Set to '1' for GPIOs 13, 19, 41, 45 or 53."""
        return self._led_channel

    @led_channel.setter
    def led_channel(self, x):
        self._led_channel = x

    @property
    def led_strip(self):
        """Strip type and color ordering."""
        return self._led_strip

    @led_strip.setter
    def led_strip(self, x):
        self._led_strip = x

    def start(self):
        """Initialize hardware and os resources."""
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(self.led_count, self.led_pin,
                                       int(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.strip.show()

    def stop(self):
        """Free hardware and os resources."""
        # Turn-off led strip
        self.close()

    def write(self, data, wait_ms=50, wipe=False):
        """Write to the leds.
        
        Args:
            data: A list of lists of which each list corresponds to each led 
                and the values are [red, green, blue, brightness].
            wait_ms (int): Optional argument that has to be set when wipe is 
                :data:`True`. Defaults to :data:`50`.
            wipe: Flag for writting to all leds at once.
        """

        if wipe:
            self._color_wipe(data[0][:3],
                             wait_ms=wait_ms,
                             brightness=data[0][3])
        else:
            for (i, led) in enumerate(data):
                self.strip.setPixelColor(i, Color(led[1], led[0], led[2]))
                self.strip.setBrightness(led[3])
                self.strip.show()
                time.sleep(0.1)

    def close(self):
        """Free hardware and os resources."""

        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, Color(0, 0, 0))
            self.strip.show()

        self.strip._cleanup()
        del self.strip

    def _color_wipe(self, rgb_color=[0, 0, 255], wait_ms=50, brightness=60):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(
                i, Color(rgb_color[1], rgb_color[0], rgb_color[2]))
            self.strip.setBrightness(brightness)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
Example #15
0
import time
import random
from rpi_ws281x import Adafruit_NeoPixel, Color

LED_COUNT = 30
LED_PIN = 18
LED_BRIGHTNESS = 10
LED_FREQ_HZ = 800000
LED_DMA = 10
LED_INVERT = False

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()):
    strip.setPixelColor(i, Color(0, 0, 255))
strip.show()