RGB led

Is there a sample code for the RGB led fading colours?

Thank you

Yulia

I’ve done lots of non-blocking fade stuff for a couple projects… here’s some shell code. The RGBFader class is the important one… it’s what manages the “animation” / fading without blocking.

You’ll need to flush out the rest of the RGBLed class - basically, finish off the constructor with whatever you need + make the setColor function actually do something:

`const NUMPIXELS = 9;
const FADETIME = 5.0;

class RGBLed {
_red = null;
_green = null;
_blue = null;

function constructor() {
    // add constructor logic here.. init pins, etc
    
    
    // set the color
    this._red = 0;
    this._green = 0;
    this._blue = 0;
    setColor(r,g,b);
}

function setColor(r,g,b) {
    if (r > 255) r = 255;
    if (r < 0) r = 0;
    if (g > 255) g = 255;
    if (g < 0) g = 0;
    if (b > 255) b = 255;
    if (b < 0) b = 0;

    // do hardware stuff here.. write pins, etc
}

}

class RGBFader {
green = 0;
red = 0;
blue = 0;

lock = null;
_rgb = null;

constructor(rgb) {
    this._rgb = rgb;
}

function set(r,g,b) {
    red = r;
    green = g;
    blue = b;
    
    _rgb.setColor(r,g,b);
}

function fadeTo(color, t, callback = null, fps = 30) {
    // check if we're already in a fade
    if (lock) return false;
    
    // set lock
    lock = true;
    
    // do some math to get parameters for fade()
    fps *= 1.0; // (convert fps to float)
    
    local wakeupTime = 1 / fps;
    local totalFrames = fps * t;
    
    local dR = (color[0] - red) / totalFrames;
    local dG = (color[1] - green) / totalFrames;
    local dB = (color[2] - blue) / totalFrames;

    fade(color, [dR, dG, dB], wakeupTime, totalFrames, 0, callback);
    return true;
}

function fade(targetColor, dColor, wakeupTime, totalFrames, currentFrame, callback) {
    if (!lock) return;
    
    this.set(red+dColor[0], green+dColor[1], blue+dColor[2]);
    currentFrame++;
    
    if (currentFrame >= totalFrames) {
        set(targetColor[0], targetColor[1], targetColor[2]);
        lock = false;
        if (callback) callback();
        return;
    }
    imp.wakeup(wakeupTime, function() { fade(targetColor, dColor, wakeupTime, totalFrames, currentFrame, callback) }.bindenv(this));
}

}

function rnd(values, min = 0) {
local r = ((math.rand() / 2147483647.0) * values) + min;
return r;
}

rgb <- RGBLed();
fader <- NeoPixelFader(rgb);

function fade() {
fader.fadeTo([rnd(255), rnd(255), rnd(255)], FADETIME, fade);
} fade();`

thanks. not as straight forwards as I though it might be :slight_smile:

Non-blocking code tends to end up being recursive, which can be a bit convoluted.

If there’s anything specific you’re wondering about let me know and I can try to explain it in a bit more depth.