You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
any way to redefine strips/controller at runtime? #826
I am looking for a way to remotely set up strips, based on information the arduino receives over serial usb.
What I'd need is something like "LEDS.removeLeds(CLEDController Reference)" so I could run addLeds again later on if needed, but there seems to be nothing as simple like that.
Not directly in the library, no - because of how much gets done at compile time for optimization reasons, combined with trying to make sure no dynamic memory allocation/deallocation is included by the library by default I haven’t put a lot of time/work into more generic controller arrangements like what you describe.
You could create/use your own controllers directly at runtime and bypass the FastLED object if you wanted. There are some elements that would still need to be determined at compile time, like PIN numbers and controller types.
By "compile time", you mean actual compile by Arduino Studio / other tools ord do je refer to the setup() routine?
If it's only setup routine, I might just have found my workaround:
I cound read my setup from serial within setup() first and initialize FastLED with my params.
Whenever needed for a setup change, I could try to force a software reboot of the Arduino.
Would be sufficient for me, as setup changes should not be a regular thing and if they happen, any reboot downtime is acceptabel.
To elaborate a bit, I am writing a highly customizeable LED-renderer-sw that will run on raspberry and have one ore multiple Arduinos connected via USB as shields for LED control, each Arduino possibly of a different type and with an individual setup of strips.
Once this setup is done, I'd like to pack all of those components + power supply into a box and seal that with silicone for protection against moisture and dust for outdoor usage. Opening that case for uploading new sketches any time a different setup is needed, will break the sealing and would also be annoying if you have to service more than one Arduino. For the Raspberry, this wont be an issue, as I can use wireless here.
So what I am looking for is a one-fits-all solution, or if not possible a one-fits-most general purpose with as few constraints as possible.
Constraints I could live with, is having a predefined set of pins and commit to using a predefined type of led-strips (most likely ws2813). Whats important to me is controlling 1-8 strips, having in total as much leds. as can be held in the arduinos.
If it's only setup routine, I might just have found my workaround:
I cound read my setup from serial within setup() first and initialize FastLED with my params.
Whenever needed for a setup change, I could try to force a software reboot of the Arduino.
Would be sufficient for me, as setup changes should not be a regular thing and if they happen, any reboot downtime is acceptabel.
Yes - something like that - I know some folks who have done something similar (selecting a specific controller on startup) -- for a while I had a test harness where I would use a set of jumpers to tell what type of led was hooked up so I could quickly try different types of leds without refreshing.
For what you're describing/trying to do - have you looked at fadecandy - https://www.adafruit.com/product/1689 - it is pretty much perfectly designed for what you're trying to do. FastLED is pretty heavily focused towards on device/mcu rendering - using it to build what is effectively a dumb frame buffer sometimes runs into problems, especially with led chipsets like the Ws28xx which require disabling interrupts while writing out led data (which can either mess with the integrity of incoming data, or requires more work/thought on the communications protocol (e.g. the Arduino will have to tell the pi "hey, I'm ready to read a frame of data now, send it to me!" - read a frame of data, call FastLED.show(), then do that loop all over again))
That said - when I say compile time, I actually mean compile time in Arduino. So you'd want something like this:
void setup() {
// read the "controller type" using either a stored EEPROM value or pin settings or read from serial
switch(controllerType) {
case 1: { FastLED.addLeds<WS2812,13,RGB>(leds, NUM_LEDS); break; }
case 2: { FastLED.addLeds(APA106,12,RGB>(leds, NUM_LEDS); break; }
// etc... etc...
}
}
FadeCanddy looks nice but istn for me because I need striplengths of way more than 64 leds only.
So I took that workaround solution and ran with it.
Here's the proof of concept sketch for others to reuse:
#include <FastLED.h>
byte num_strips;
byte strip_chips[8];
byte strip_pins[8];
int strip_lengths[8];
long num_leds;
CRGB leds[300];
union intBytes {
int ivalue;
byte ibytes[2];
} intByte;
void setup() {
delay(2000);
//init status LED to off
//status LED will be enabled if protocol out of sync due to data loss
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
//open USB-Serial Connection and wait to connect.
Serial.begin(1000000);
while (!Serial);
readSetup();
//initFastLEDOutputs
int startindex = 0;
for (byte strip = 0; strip < num_strips; strip++) {
//switch to support different LED-chipsets
switch (strip_chips[ strip ]) {
case 1: {
switch (strip_pins[strip]) {
case 3: {
FastLED.addLeds<WS2811, 3, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 4: {
FastLED.addLeds<WS2811, 4, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 5: {
FastLED.addLeds<WS2811, 5, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 6: {
FastLED.addLeds<WS2811, 6, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
}
break;
}
case 2: {
switch (strip_pins[strip]) {
case 3: {
FastLED.addLeds<WS2812, 3, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 4: {
FastLED.addLeds<WS2812, 4, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 5: {
FastLED.addLeds<WS2812, 5, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 6: {
FastLED.addLeds<WS2812, 6, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
}
break;
}
case 3: {
switch (strip_pins[strip]) {
case 3: {
FastLED.addLeds<WS2813, 3, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 4: {
FastLED.addLeds<WS2813, 4, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 5: {
FastLED.addLeds<WS2813, 5, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
case 6: {
FastLED.addLeds<WS2813, 6, GRB>(leds, startindex, strip_lengths[strip]);
break;
}
}
break;
}
}
startindex += strip_lengths[strip];
}
}
void loop() {
readLEDColors();
LEDS.show();
validateSetup();
}
//declare reset function at address 0
void(* resetFunc) (void) = 0;
void readLEDColors() {
for (int i = 0; i < num_leds; i++) {
while (Serial.available() < 3);
Serial.readBytes((byte*)(&leds[i]), 3);
}
}
void readSetup() {
readUntilSetupHeaderReceived(true);
while (Serial.available() == 0);
num_strips = Serial.read();
num_leds = 0;
char str[17];
for (byte strip = 0; strip < num_strips; strip++) {
while (Serial.available() == 0);
strip_pins[strip] = Serial.read();
while (Serial.available() == 0);
strip_chips[strip] = Serial.read();
while (Serial.available() < 2);
strip_lengths[strip] = serialReadInt();
num_leds += strip_lengths[strip];
}
}
void validateSetup() {
readUntilSetupHeaderReceived(false);
while (Serial.available() == 0);
byte data = Serial.read();
if (num_strips != data) {
setupChanged();
}
for (byte strip = 0; strip < num_strips; strip++) {
while (Serial.available() == 0);
if (strip_pins[strip] != Serial.read()) {
setupChanged();
}
while (Serial.available() == 0);
if (strip_chips[strip] != Serial.read()) {
setupChanged();
}
while (Serial.available() < 2);
if (strip_lengths[strip] != serialReadInt()) {
setupChanged();
}
}
}
void readUntilSetupHeaderReceived(boolean startup) {
//setup header is 0xffffffff
byte receivedHeaderBytes = 0;
//rotating single byte read
while (true) {
while (Serial.available() == 0);
if (Serial.read() == 255) {
//count successive reads of 0xff
receivedHeaderBytes++;
} else {
receivedHeaderBytes = 0;
if (!startup) {
//simple visual debug method:
// signal that we received something unexpected instead of the header right away
// -> this is ok during startup, but should not happen later
// -> if so, itss most likely due to data loss
// -> the source is feeding data at highger rates than max fps for this setup
digitalWrite(LED_BUILTIN, HIGH);
}
}
if (receivedHeaderBytes == 4) {
//Setup Header read successfully
return;
}
}
}
void setupChanged() {
//reset Board and start over by loading Setup again
resetFunc();
}
word serialReadInt() {
Serial.readBytes(intByte.ibytes, 2);
return intByte.ivalue;
}
This is how it works:
To circumvent the problem of the arduino having to signal "ready to read", I designed a simple unidirectional protocol.
The code will read any input in a loop until a 4-byte header is received.
Then setup will be read and inialized.
Within the main loop, the led data will be read from serial and pushed out to the strips.
After each data frame, another setup (incl header) is read.
If the header is not the next thing we find in the data stream, both systems are likely out of sync -> this will be singnaled by the onboard led turned on.
However, the code will then just skip to the next frame, so in case of the host pushing data at a too high rate, the frame rate will just be reduced by at least half.
Turning the fps on the host down will subsequently return the systems to a synced state, all that while still running.
Also we can compare our current setup to the one just read at this point.
If anything changed, a software reset is performed and after a short reboot of few seconds, it will run with the new setup.
Thats basically it, works just fine for my purpose.
An imperfection might be, that 4 white leads in a row might be mistaken for a header.
This could be solved by transmitting led data in chunks of 4 bytes (rgb + a leading or trailing zero-byte).
However there were still a couple of issues that I ran into.
It seems, the more instance of addLeds you have in your code, the more likely to encounter this at random. I used Arduino 1.8.9. Downgrading to 1.8.5 solved that problem.
Second thing that threw me off, was that FastLed eats away bits of ram with every instance of addLeds in the code, wheter it is called or not. About 50 bytes each is probably a good guess. Having an Arduino Uno, this blew ram usage out of proportion really quick, even my prove-of-concept with a very reduced set of chipsets and pins had to be downsized to fit 300 leds max.
Fully fledged support for a full set of pins and a wide range of chipsets isn't possible with just 2KB and
moving on to teensy or due therefore is mandatory.
And given the low difference in pricetag combined with the option for parallel output, probably a nobrainer anyways. LEarned my lesson here: dont code on cheap stuff.
An interesting workaround, resetting the board. I ran into a similar situation, wanting to change the setup during runtime.
It is unfortunate that addLeds is templated as it is (especially the data pin). Seems a bit unnecessary. The data storage for the LED colors is passed in anyway, and like you noticed, each different addLeds call takes up memory (whether called in the 'switch' or not-- controller is a static defined within the templated function, so its memory is reserved basically at compile time).
If I use this technique, I might use a nonvolatile setting instead of the serial input (I'm looking at a stand-alone controller situation). Still wish there were a better solution though.
Исходя из того, что я увидел в обсуждениях по данному вопросу, могу сказать точно - использовать данную библиотеку можно только для тестов, отладки и тому подобное. Для серьезных работ придется разобраться в коде библиотеки , забрать необходимое и написать свои функции. У меня был подобный опыт - я заказывал пустые микросхемы автоконтроллеров, что ставятся в начале светодиодных лент и прошивал их собственным кодом, затем менял их на на светодиодной ленте . Видимо здесь придется так же...
Activity
focalintent commentedon Jun 25, 2019
Not directly in the library, no - because of how much gets done at compile time for optimization reasons, combined with trying to make sure no dynamic memory allocation/deallocation is included by the library by default I haven’t put a lot of time/work into more generic controller arrangements like what you describe.
You could create/use your own controllers directly at runtime and bypass the FastLED object if you wanted. There are some elements that would still need to be determined at compile time, like PIN numbers and controller types.
psymagic commentedon Jun 25, 2019
Thanks for your quick reply.
By "compile time", you mean actual compile by Arduino Studio / other tools ord do je refer to the setup() routine?
If it's only setup routine, I might just have found my workaround:
I cound read my setup from serial within setup() first and initialize FastLED with my params.
Whenever needed for a setup change, I could try to force a software reboot of the Arduino.
Would be sufficient for me, as setup changes should not be a regular thing and if they happen, any reboot downtime is acceptabel.
To elaborate a bit, I am writing a highly customizeable LED-renderer-sw that will run on raspberry and have one ore multiple Arduinos connected via USB as shields for LED control, each Arduino possibly of a different type and with an individual setup of strips.
Once this setup is done, I'd like to pack all of those components + power supply into a box and seal that with silicone for protection against moisture and dust for outdoor usage. Opening that case for uploading new sketches any time a different setup is needed, will break the sealing and would also be annoying if you have to service more than one Arduino. For the Raspberry, this wont be an issue, as I can use wireless here.
So what I am looking for is a one-fits-all solution, or if not possible a one-fits-most general purpose with as few constraints as possible.
Constraints I could live with, is having a predefined set of pins and commit to using a predefined type of led-strips (most likely ws2813). Whats important to me is controlling 1-8 strips, having in total as much leds. as can be held in the arduinos.
focalintent commentedon Jun 26, 2019
Yes - something like that - I know some folks who have done something similar (selecting a specific controller on startup) -- for a while I had a test harness where I would use a set of jumpers to tell what type of led was hooked up so I could quickly try different types of leds without refreshing.
For what you're describing/trying to do - have you looked at fadecandy - https://www.adafruit.com/product/1689 - it is pretty much perfectly designed for what you're trying to do. FastLED is pretty heavily focused towards on device/mcu rendering - using it to build what is effectively a dumb frame buffer sometimes runs into problems, especially with led chipsets like the Ws28xx which require disabling interrupts while writing out led data (which can either mess with the integrity of incoming data, or requires more work/thought on the communications protocol (e.g. the Arduino will have to tell the pi "hey, I'm ready to read a frame of data now, send it to me!" - read a frame of data, call FastLED.show(), then do that loop all over again))
focalintent commentedon Jun 26, 2019
That said - when I say compile time, I actually mean compile time in Arduino. So you'd want something like this:
psymagic commentedon Jul 18, 2019
FadeCanddy looks nice but istn for me because I need striplengths of way more than 64 leds only.
So I took that workaround solution and ran with it.
Here's the proof of concept sketch for others to reuse:
This is how it works:
To circumvent the problem of the arduino having to signal "ready to read", I designed a simple unidirectional protocol.
The code will read any input in a loop until a 4-byte header is received.
Then setup will be read and inialized.
Within the main loop, the led data will be read from serial and pushed out to the strips.
After each data frame, another setup (incl header) is read.
If the header is not the next thing we find in the data stream, both systems are likely out of sync -> this will be singnaled by the onboard led turned on.
However, the code will then just skip to the next frame, so in case of the host pushing data at a too high rate, the frame rate will just be reduced by at least half.
Turning the fps on the host down will subsequently return the systems to a synced state, all that while still running.
Also we can compare our current setup to the one just read at this point.
If anything changed, a software reset is performed and after a short reboot of few seconds, it will run with the new setup.
Thats basically it, works just fine for my purpose.
An imperfection might be, that 4 white leads in a row might be mistaken for a header.
This could be solved by transmitting led data in chunks of 4 bytes (rgb + a leading or trailing zero-byte).
However there were still a couple of issues that I ran into.
First was this infamous bug:
#646
It seems, the more instance of addLeds you have in your code, the more likely to encounter this at random. I used Arduino 1.8.9. Downgrading to 1.8.5 solved that problem.
Second thing that threw me off, was that FastLed eats away bits of ram with every instance of addLeds in the code, wheter it is called or not. About 50 bytes each is probably a good guess. Having an Arduino Uno, this blew ram usage out of proportion really quick, even my prove-of-concept with a very reduced set of chipsets and pins had to be downsized to fit 300 leds max.
Fully fledged support for a full set of pins and a wide range of chipsets isn't possible with just 2KB and
moving on to teensy or due therefore is mandatory.
And given the low difference in pricetag combined with the option for parallel output, probably a nobrainer anyways. LEarned my lesson here: dont code on cheap stuff.
stevesch commentedon Oct 28, 2020
An interesting workaround, resetting the board. I ran into a similar situation, wanting to change the setup during runtime.
It is unfortunate that addLeds is templated as it is (especially the data pin). Seems a bit unnecessary. The data storage for the LED colors is passed in anyway, and like you noticed, each different addLeds call takes up memory (whether called in the 'switch' or not-- controller is a static defined within the templated function, so its memory is reserved basically at compile time).
If I use this technique, I might use a nonvolatile setting instead of the serial input (I'm looking at a stand-alone controller situation). Still wish there were a better solution though.
Kwotermain commentedon Jan 30, 2026
Исходя из того, что я увидел в обсуждениях по данному вопросу, могу сказать точно - использовать данную библиотеку можно только для тестов, отладки и тому подобное. Для серьезных работ придется разобраться в коде библиотеки , забрать необходимое и написать свои функции. У меня был подобный опыт - я заказывал пустые микросхемы автоконтроллеров, что ставятся в начале светодиодных лент и прошивал их собственным кодом, затем менял их на на светодиодной ленте . Видимо здесь придется так же...