RGB LED Kit for Tiny FX Tutorial?

If you look at the existing examples you can generally find the base class that is being extended, such as Updateable or Cycling (which extends Updateable). These are all defined in tinyfx/lib/picofx/__init__.py.

I wanted to blink the RGB LED so I looked at the existing mono BlinkFX class, then extended Cycling to make my own version for the RGB LED:

from picofx import Cycling

import itertools
from color import Color

class RgbBlinkFX(Cycling):
    '''
    Blinks the RGB LED according to the speed, phase and duty cycle.

    The color argument is a single tuple of the form (i,R,G,B), or a
    list of such tuples. A None color argument defaults to red.

    :param:   speed   the speed of the blink, where 1.0 is 1 second, 0.5 is 2 seconds, etc.
    :param:   phase   the phase of the blink
    :param:   duty    the duty cycle of the blink
    :param:   color   an RGB tuple as the color or colors of the blink
    '''
    def __init__(self, speed=1, phase=0.0, duty=0.5, color=None):
        super().__init__(speed) 
        self.phase = phase
        self.duty  = duty
        self._colors = []
        self._counter = itertools.count()
        if color is None:
#           self._colors.append(Color.RED)
            self._colors.append((0, 255, 0, 0))
        elif isinstance(color, tuple):
            self._colors.append(color)
        elif type(color) is list:
            self._colors.extend(color)
        else:
            raise Exception('unrecognised argument type.')
        self._cycle = itertools.cycle(self._colors)
        self._color = self._colors[0]

    def __call__(self):
        percent = (self.__offset + self.phase) % 1.0
        if percent < self.duty:
            if len(self._colors) == 1:
                self._color = self._colors[0]
            elif next(self._counter) % 5 == 0:
                self._color = next(self._cycle)
            _red   = self._color[1]
            _green = self._color[2]
            _blue  = self._color[3]
            return _red, _green, _blue
        else:
            return 0, 0, 0

This uses a MicroPython version of itertools, which you can download from micropython-itertools.

I wrote a simple Color class, noting that the first value in the tuple is an index:

class Color(object):
    #                   i  R      G      B
    WHITE           = ( 1, 255.0, 255.0, 255.0)
    BLACK           = ( 2,   0.0,   0.0,   0.0)
    RED             = ( 3, 255.0,   0.0,   0.0)
    YELLOW          = ( 4, 255.0, 160.0,   0.0)
    GREEN           = ( 5, 0.0,   255.0,   0.0)
    BLUE            = ( 6, 0.0,    40.0, 255.0)
    CYAN            = ( 7, 0.0,   255.0, 255.0)
    MAGENTA         = ( 8, 255.0,   0.0, 255.0)

and of course you could add your own colors to that list.

1 Like