#include <FastLED.h>
#define NUM_LEDS 240
#define DATA_PIN 5
#define COLOR_ORDER GRB
#define CHIPSET WS2812B
CRGBArray<NUM_LEDS> leds;
byte datos[4];
// a struct to hold the pixel index, fade level and colour for each active pixel
struct Pixel {
uint8_t index = 255; // with only 240 LEDs, we use 255 as flag for this pixel being unused
uint8_t fade;
CRGB col;
};
// 160 active pixels ought to be enough for anyone ;)
#define CACHE_ENTRIES 160
Pixel cache[CACHE_ENTRIES];
void addToCache(int index, CRGB col) {
// find the first free slot in cache[], or an existing slot with the same index
int slot = 0;
while (slot < CACHE_ENTRIES) {
if (cache[slot].index == 255)
break;
if (cache[slot].index == index)
break;
slot++;
}
// bail out if there are no free slots
if (slot >= CACHE_ENTRIES)
return;
// copy the received data into the slot and set fade level to 0
cache[slot].index = index;
cache[slot].fade = 0;
cache[slot].col = col;
}
void setup() {
Serial.begin(9600);
FastLED.addLeds<CHIPSET, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
FastLED.clear(1);
}
void loop() {
if (Serial.available()>= 4) { // verify if the led index, r,g,b bytes are available
Serial.readBytes(datos, 4);
addToCache(datos[0], CRGB(datos[1],datos[2],datos[3]));
}
// for use in the sim, fake receiving random things over serial
if (random8() < 128)
addToCache(random8(NUM_LEDS), CRGB(random8(), random8(), random8()));
// display each active cache slot and advance its fade level
for (auto slot = 0; slot < CACHE_ENTRIES; slot++) {
if (cache[slot].index == 255)
continue; // this slot is currently unused
leds[cache[slot].index] = cache[slot].col;
leds[cache[slot].index].fadeToBlackBy(cache[slot].fade);
// if the fade level overflows from 255 -> 0, disable this slot by setting the index to 255
if (++cache[slot].fade == 0) {
cache[slot].index = 255;
}
}
FastLED.show();
}FPS: 0
Power: 0.00W
Power: 0.00W