# Make some FastLED code non-blocking

**URL:** <https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335>\
**Category:** Programming\
**Created:** [February 14, 2023, 11:20pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335 "2023-02-14T23:20:48Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 14, 2023, 11:20pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/1 "2023-02-14T23:20:48Z")

</div>

What is the best way to make this FastLED animation code non-blocking?

```cpp
// Code from https://github.com/s-marley/FastLED-basics/tree/main/5.%20Multiple%20patterns/classesTimer
// using a wokwi-neopixel-canvas
// https://wokwi.com/projects/356665860602531841
// See https://www.youtube.com/watch?v=fRXJQVdwrog
//

#include <FastLED.h>

#define NUM_LEDS 18
#define LED_PIN 2

CRGB leds[NUM_LEDS];
uint8_t patternCounter = 0;
bool isRunning = false;

void checkTimer();

#include "Fire2012.h"
#include "Pacifica.h"
#include "Pride2015.h"

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);
  Serial.begin(57600);
}

void loop() {
  
  switch (patternCounter) {
    case 0:
      runFire2012();
      break;
    case 1:
      runPacifica();
      break;
    case 2:
      runPride2015();
      break;
  }
}

void checkTimer() {
  EVERY_N_SECONDS(50) {
    nextPattern();
  }
}

void nextPattern() {
  isRunning = false;
  patternCounter = (patternCounter + 1) % 3;
}

void runFire2012(){
  isRunning = true;
  Fire2012 fire2012 = Fire2012();
  while(isRunning) fire2012.runPattern();
}

void runPacifica(){
  isRunning = true;
  Pacifica pacifica = Pacifica();
  while(isRunning) pacifica.runPattern();
}

void runPride2015(){
  isRunning = true;
  Pride2015 pride2015 = Pride2015();
  while(isRunning) pride2015.runPattern();
}

```

Following the original example, I wanted the delete the objects when they weren't in use, but I also wanted them to persist through iterations of `loop()` so the animations would be non-blocking.

I tried the code below, but I'm not sure of the new-delete-NULL logic I use.

Any suggestions?

```cpp
// Attempt at non-blocking version of FastLED classesTimer.ino example
// https://wokwi.com/projects/356666059490147329
//
// Based on sim from https://wokwi.com/projects/356665860602531841
// with code from https://github.com/s-marley/FastLED-basics/tree/main/5.%20Multiple%20patterns/classesTimer
// using a wokwi-neopixel-canvas

// Try to make non-blocking
//
// On Nano:
// A0 potentiometer: led speed 1-600 sec
// A1 potentiometer: report speed 1-1000 ms
// 
// Note that the reading of the A0 report() happens frequently while the loop animations are going 

#include <FastLED.h>

#define NUM_LEDS 18
const int LED_PIN = 2;
const int LED_speed_pin = A0; 
const int report_speed_pin = A1; 

CRGB leds[NUM_LEDS];
uint8_t patternCounter = 0;
bool isRunning = false;
bool changePattern = false;

void checkTimer();
int reportInterval = 500; // ms
int ledInterval = 1; // sec

#include "Fire2012.h"
#include "Pacifica.h"
#include "Pride2015.h"

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);
  Serial.begin(115200);
  pinMode(LED_speed_pin,INPUT);  
  pinMode(report_speed_pin,INPUT);  
}

void loop() {
  
  handleIO();

  switch (patternCounter) {
    case 0:
      runFire2012();
      break;
    case 1:
      runPacifica();
      break;
    case 2:
      runPride2015();
      break;
  }
  report();
}

void report(){
  static uint32_t last=0;
  //const int interval=1;
  if(millis() - last > reportInterval){
    last+=reportInterval;
    Serial.print('.');
  }
}

void handleIO(void){
   const int interval = 250; //ms
   static uint32_t last = -interval;
  if(millis() - last >= interval){
    ledInterval = map(analogRead(LED_speed_pin),0,1024,1,600); // seconds
    reportInterval = map(analogRead(report_speed_pin),0,1024,1,1000); // ms
  }
}

void checkTimer() {
  static uint32_t last = 0;
  if(millis() - last >= ledInterval*1000UL){
    last = millis();
    nextPattern();
  }
}

void nextPattern() {
  isRunning = false;
  changePattern = true;
  //patternCounter = (patternCounter + 1) % 3;
}

void runFire2012(){
  static Fire2012 *fire2012;
  if(! fire2012) {
    isRunning = true;
    fire2012 = new Fire2012;
    Serial.print("Fire2012");
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(fire2012){ // de-allocate
      delete fire2012;
      fire2012=NULL;
      Serial.print("deleted\n");
    }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
// Fire2012 fire2012 = Fire2012();
  if(isRunning) fire2012->runPattern();
}

void runPacifica(){
  static Pacifica *pacifica;
// if( !isRunning || ! pacifica) {
  if( ! pacifica) {
    isRunning = true;
    pacifica = new Pacifica;
    Serial.print("Pacifica");
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(pacifica){
      delete pacifica;
      pacifica = NULL;
      Serial.print("deleted\n");
    }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pacifica->runPattern();
}

void runPride2015(){
  static Pride2015 *pride2015;
  if( ! pride2015) {
    isRunning = true;
    pride2015 = new Pride2015;
    Serial.print("Pride2015");
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(pride2015){
      delete pride2015;
      pride2015 = NULL;
       Serial.print("deleted\n");
   }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pride2015->runPattern();
}

```

There is a simulation of my attempt at

> **[FastLED\_classesTimer\_nonblocking - Wokwi Arduino and ESP32 Simulator](https://wokwi.com/projects/356666059490147329)**
>
> Run IoT and embedded projects in your browser: ESP32, Arduino, Pi Pico, and more. No installation required!

Oops, it's Valentine's day. I should come up with a good dinner plan.

---

<div class="post-metadata">

**Author:** ![qubits-us](https://avatars.discourse-cdn.com/v4/letter/q/5daacb/32.png) [@qubits-us](https://forum.arduino.cc/u/qubits-us)\
**Post date:** [February 15, 2023, 2:12am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/2 "2023-02-15T02:12:43Z")

</div>

Interesting question, still discovering myself..  
Have already discovered strings are bad due to memory fragmentation..  
Would there also be potential frag here??

```cpp
int lastFreeRam = 0;

void display_freeram() {
  int ramleft = freeRam();
  if (ramleft!= lastFreeRam)
  {
   lastFreeRam = ramleft; 
  Serial.print(F("- SRAM left: "));
  Serial.println(ramleft);
  }
}

int freeRam() {
  extern int __heap_start,*__ brkval;
  int v;
  return (int)&v - (__brkval == 0  
    ? (int)&__heap_start : (int)__brkval);  
}

```

added this into the mix and a display\_freeram into your report func..  
can see the free ram change per test..  
looks like pacifica uses the most..

looks like it works good too me..

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 15, 2023, 3:56am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/3 "2023-02-15T03:56:55Z")

</div>

> [@qubits-us](#):
>
> `void`

It does seem like a possibility to be a problem, but the allocation/deallocation of the animation objects should happen at the same rate as with the blocking code. I think the trickier part is that other code that can run in the non-blocking mode, like the report or IO checking routines. The un-blocked code has more new/more opportunity to munge around with the memory as compared to the previous code.

---

<div class="post-metadata">

**Author:** ![alto777](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/alto777/32/317385_2.png) [@alto777](https://forum.arduino.cc/u/alto777)\
**Post date:** [February 15, 2023, 4:03am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/4 "2023-02-15T04:03:07Z")

</div>

> [@DaveX](#):
>
> Any suggestions?

I have taken a Valentine's Day low level flight about your sketch. Thank you for putting it in the wokwi simulator. That will increase eyes on it I am sure.

I don't use the language features you exploit, but as far as I understand what they do, it all looks fine.

I don't see memory as a problem, given that only one of the processes is running at a time, and anything running is destroyed before a new other thing is stood up. The care taken seems comprehensive.

I have seen the various versions of "EVERY\_N\_MILLISECONDS", I think I found it once, I assume it does the same thing that I normally see just in regular code. That is that it works and does not block. I would probably not use those macros, but that's just a personal thing - I generally enjoy figuring out and writing things like that and leaving them as non-mysterious for myself and readers.

The create/destroy/nullify logic and the patternCounter logic is strewn about (technical term!) but looks sound.

I resist an urge to make one controller out of the very similar functions _runFire2012_(),  
_runPacifica_() and _runPride2015_(), my idea of fun.

_So I got nothing_. Does the code crank away for longer than the minutes is has been happily doing here whilst I compose this?

I know it is not a valid test and it would be good to see if there is another "official" or better way to do this, but it does seem to run and report and act like... it works.

a7

---

<div class="post-metadata">

**Author:** ![qubits-us](https://avatars.discourse-cdn.com/v4/letter/q/5daacb/32.png) [@qubits-us](https://forum.arduino.cc/u/qubits-us)\
**Post date:** [February 15, 2023, 4:04am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/5 "2023-02-15T04:04:52Z")

</div>

didn't see the cpp files in the sim..  
but if there like the demo's in git..  
then they would have to be changed to be stepped from the loop..  
unless they already have it somewhere, lot a work..

just looking more.. i see it already is, lol..  
so, idk.. looks good..  
im crashing, happy val day everyone!!  
~q

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 15, 2023, 4:50am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/6 "2023-02-15T04:50:36Z")

</div>

I tried not to muck with the original code too much. I was interested in how to do use the static pointer with new and destroy repeatedly. I did learn that I had to NULL the pointer explicitly if I was going to use it for a test. I wonder if I should assign it to NULL with a `static Obj *x = NULL;`

The original code used an EVERY\_N\_SECONDS macro in the checkTimer routine, but using it I couldn't vary the interval with the potentiometer, so I replaced it with a millis()-last conditional.

I ran it for a while, using @qubits-us's memory test and a short interval for lots of switching and noticed no problems. But absence of evidence...etc..

I did have problems with memory when I wasn't careful about NULLing the pointer and then using it for the existence test.

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 15, 2023, 5:38am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/7 "2023-02-15T05:38:07Z")

</div>

Later during the video, Scott Marley apologized for leaving the functions in the .h files rather than .cpp files:

[![](https://europe1.discourse-cdn.com/arduino/original/4X/9/c/5/9c53edd6b5ddd1d562274fd1c4917ea8322a8df8.jpeg "FastLED Basics Episode 5 - Multiple patterns using a timer or button") ](https://www.youtube.com/watch?v=fRXJQVdwrog)

The repository at [FastLED-basics/5. Multiple patterns/classesTimer at main · s-marley/FastLED-basics · GitHub](https://github.com/s-marley/FastLED-basics/tree/main/5.%20Multiple%20patterns/classesTimer) has the code, and i thought it was good that the classes' functions weren't blocking. It was his code created the objects within the .ino file's functions, and relied on normal end-of-scope to automatically destroy them.

I guess my question was about how to switch from automatic object destruction in this sort of routine:

```cpp
void runPride2015(){
  isRunning = true;
  Pride2015 pride2015 = Pride2015();
  while(isRunning) pride2015.runPattern();
}

```

to a non-blocking function like my:

```cpp
void runPride2015(){
  static Pride2015 *pride2015;
  if( ! pride2015) {
    isRunning = true;
    pride2015 = new Pride2015;
    Serial.print("Pride2015");
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(pride2015){
      delete pride2015;
      pride2015 = NULL;
       Serial.print("deleted\n");
   }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pride2015->runPattern();
}

```

... while avoiding making it global, and keeping the initialization. I wonder if it would be better to pass a value in to signal a reset or destruction.

My current [code on the simulator](https://wokwi.com/projects/356666059490147329) has your memory code in it:

```cpp
// Attempt at non-blocking version of FastLED classesTimer.ino example
// https://wokwi.com/projects/356666059490147329
// Discussion at 
// https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335
//
// Based on sim from https://wokwi.com/projects/356665860602531841
// with code from https://github.com/s-marley/FastLED-basics/tree/main/5.%20Multiple%20patterns/classesTimer
// using a wokwi-neopixel-canvas
//
// Contribution of SRAM monitor from qbits-us per 
// https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/2
//
// Try to make non-blocking
//
// On Nano:
// A0 potentiometer: led speed 1-600 sec
// A1 potentiometer: report speed 1-1000 ms
// 
// Note that the reading of the A0 report() happens frequently while the loop animations are going 

#include <FastLED.h>

#define NUM_LEDS 18
const int LED_PIN = 2;
const int LED_speed_pin = A0; 
const int report_speed_pin = A1; 
const int verbose = 4;

CRGB leds[NUM_LEDS];
uint8_t patternCounter = 0;
bool isRunning = false;
bool changePattern = false;

void checkTimer();
int reportInterval = 500; // ms
int ledInterval = 1; // sec

#include "Fire2012.h"
#include "Pacifica.h"
#include "Pride2015.h"

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(100);
  Serial.begin(115200);
  pinMode(LED_speed_pin,INPUT);  
  pinMode(report_speed_pin,INPUT);  
}

void loop() {
  
  handleIO();

  switch (patternCounter) {
    case 0:
      runFire2012();
      break;
    case 1:
      runPacifica();
      break;
    case 2:
      runPride2015();
      break;
  }
  report();
  if(verbose >=0) LoopCounter();
}

/////////// diagnostic code for excercising doing several things at once 
// An output line like this consists of several reports
// Pride2015.- SRAM left: 1514 400Hzdeleted
// ^ object intantiated
// ^ report triggered
// ^ Free SRAM report
// ^ loop() frequency
// ^ object deleted
void report(){
  static uint32_t last=0;
  //const int interval=1;
  if(millis() - last > reportInterval){
    last+=reportInterval;
    if(verbose >= 3)Serial.print('.');
    if(verbose >= 2)display_freeram();
  }
}

int lastFreeRam = 0;

void display_freeram() {
  int ramleft = freeRam();
  if (ramleft!= lastFreeRam)
  {
   lastFreeRam = ramleft; 
  Serial.print(F("- SRAM left: "));
  Serial.print(ramleft);
  Serial.print(' ');
  }
}

int freeRam() {
  extern int __heap_start,*__ brkval;
  int v;
  return (int)&v - (__brkval == 0  
    ? (int)&__heap_start : (int)__brkval);  
}

void LoopCounter() // tells the average response speed of void loop()
// code modified from https://forum.arduino.cc/t/while-loop-as-a-condition-for-limit-switches/963899/11
{ // inside a function, static variables keep their value from run to run
  const unsigned long microsInOneSecond=1000000UL;
  static unsigned long count, countStartMicros; // only this function sees these

  count++; // adds 1 to count after any use in an expression, here it just adds 1.
  if ( micros() - countStartMicros >= microsInOneSecond ) // 1 second
  {
    countStartMicros += microsInOneSecond; // for a regular second
    Serial.print( count ); // 32-bit binary into decimal text = many micros
    Serial.print("Hz");
    count = 0; // don't forget to reset the counter 
  }
}
//////////// end diagnostic code 

void handleIO(void){
   const int interval = 250; //ms
   static uint32_t last = -interval;
  if(millis() - last >= interval){
    ledInterval = map(analogRead(LED_speed_pin),0,1024,1,600); // seconds
    reportInterval = map(analogRead(report_speed_pin),0,1024,1,1000); // ms
  }
}

void checkTimer() {
  static uint32_t last = 0;
  if(millis() - last >= ledInterval*1000UL){
    last = millis();
    nextPattern();
  }
}

void nextPattern() {
  isRunning = false;
  changePattern = true;
  //patternCounter = (patternCounter + 1) % 3;
}

// These runXXXX commands were modified from the original to
// be non-blocking by keeping a static pointer to an object
// that persists between calls, and is destryed when finished.

void runFire2012(){
  static Fire2012 *fire2012;
  if(! fire2012) {
    isRunning = true;
    fire2012 = new Fire2012;
    if(verbose>1)Serial.print(F("Fire2012"));
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(fire2012){ // de-allocate
      delete fire2012;
      fire2012=NULL;
      if(verbose>1)Serial.print(F("deleted\n"));
    }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
// Fire2012 fire2012 = Fire2012();
  if(isRunning) fire2012->runPattern();
}

void runPacifica(){
  static Pacifica *pacifica;
// if( !isRunning || ! pacifica) {
  if( ! pacifica) {
    isRunning = true;
    pacifica = new Pacifica;
    if(verbose>1)Serial.print(F("Pacifica"));
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(pacifica){
      delete pacifica;
      pacifica = NULL;
      if(verbose>1)Serial.print(F("deleted\n"));
    }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pacifica->runPattern();
}

void runPride2015(){
  static Pride2015 *pride2015;
  if( ! pride2015) {
    isRunning = true;
    pride2015 = new Pride2015;
    if(verbose>1)Serial.print(F("Pride2015"));
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(pride2015){
      delete pride2015;
      pride2015 = NULL;
      if(verbose>1)Serial.print(F("deleted\n"));
   }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pride2015->runPattern();
}

```

---

<div class="post-metadata">

**Author:** ![alto777](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/alto777/32/317385_2.png) [@alto777](https://forum.arduino.cc/u/alto777)\
**Post date:** [February 15, 2023, 1:14pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/8 "2023-02-15T13:14:37Z")

</div>

> [@DaveX](#):
>
> I wonder if I should assign it to NULL with a `static Obj *x = NULL;`

That might work but would be overkill.

This matches my preconceived prejudice:

> To deallocate an object allocated by `new`, you should use `delete`.

> To prevent a pointer from being ["dangling"](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer), set the pointer to `nullptr`

_nullptr_ is a C++ keyword, looks like for just what you want.

_delete_ can be safely used on a pointer that is the nullptr. I suppose\ it amounts to doing nothing as one might hope.

Now you say "But absence of evidence...etc..".

But where do you stop? We write code, it does what we think and want, we look a little closer and put some code in to check and confirm and test the flow, leave behind error mechanisms and so forth.

One guy here recently wanted to read back the bits he has sent out to a bank of shift registers to make sure they all got there. Where would that kind of fear lead?

Yes, even with that there will still be errors, my favorites are obscure 1 in a million things that could "never happen". Like when someone decides something can run at 115200 band rate when the programmer form the last century thought 9600 was super fast, or when the bored homeowner figures out opening the microwave door at just the right time makes the beeper go a bit crazy.

> I replaced [EVERY\_N\_] with a millis()-last conditional.

A good move. I'll take a peek when I am next in the lab.

a7

---

<div class="post-metadata">

**Author:** ![alto777](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/alto777/32/317385_2.png) [@alto777](https://forum.arduino.cc/u/alto777)\
**Post date:** [February 15, 2023, 4:11pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/9 "2023-02-15T16:11:43Z")

</div>

What are limbs for except to go out on them?

Here I have made a beginner's attempt at unifying the three effects. The idea is that _runThis_() is called with a pointer to the currently desired effect. If the effect changes, the old effect is deleted, and a new effect is stood up. Calling _runThis_() with _nullptr_ turns off the effect if one is running.

I've implied in the code the existence of a _runMethod_ for any effect object, and a _objectTag_() method which just returns some text we use to name the object for verbose reporting.

In case it isn't obvious, I can't test this, I have glossed over details I don't have any kind of grip on, and I am entirely faking this only in the hope that what I propose is possible, easy and legitiamte and that someone might be able to fix it or say why it can't be done or should not be.

Oh, and I have never been good at naming things, so I'd be happy with better names all around.

  

```cpp
void runThis(objectPtr pleaseRun)
{
  static objectPtr *currentObject = nullptr;

// normal. just run the current object
  if (currentObject == pleaseRun) {
    if (currentObject != nullptr)
      currentObject->runMethod();

    return;
  }

// different object specified! shut down the old one
  if (currentObject) {
  
    if (verbose > 1) {
      Serial.print("deleting ");
      Serial.println(currentObject.objectTag());
    }

    delete currentObject;

    currentObject = nullptr;
  }

// new object for reals! stand it up
  if (pleaseRun) {
    currentObject = new pleaseRun;

    if (verbose > 1) {
      Serial.print(" now to run ");
      Serial.println(currentObject.objectTag());
    }
  }
  
// we get called frequently, no need to start right away...
// if (currentObject != nullptr) currentObject->runMethod();
}

```

a7

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 15, 2023, 5:50pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/10 "2023-02-15T17:50:34Z")

</div>

Going further out on the limb into things I don't know about, wouldn't `objectPointer` need to be defined and wouldn't its definition need to accommodate the different objects, like Fire2012, Pacifica, and Pride2015? Does that mean one would have to re-write them to inherit something-or-other?

> [@alto777](#):
>
> Oh, and I have never been good at naming things, so I'd be happy with better names all around.

Well, how are you at cache invalidation?

---

<div class="post-metadata">

**Author:** ![alto777](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/alto777/32/317385_2.png) [@alto777](https://forum.arduino.cc/u/alto777)\
**Post date:** [February 15, 2023, 6:03pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/11 "2023-02-15T18:03:00Z")

</div>

> [@DaveX](#):
>
> Does that mean one would have to re-write them to inherit something-or-other?

Yes. I have no clue how to write it, but it seems that an uber-object would be the home for all runnable objects, which would need to provide standard methods.

It's the kind of thing I always assume would be easy, so if my ramblings are even close I'd like to see it fixed and demonstrated, close enough perhaps to use it as an excuse to dive a little more off the limb into the dark waters swirling just below.

Mostly I don't like the near-triplicate functions, as three can become N and N functions to maintain is fraught, too much possibility of getting a fix applied to all of of them correctly and so forth.

BTW, did you ever say why? Why do you need to create and destroy anything? In smart LED stuff the real hog is the pixel buffer, which has to exist for the entire time.

I have assumed you had a good reason or that this was just an artif7constraint to create the challenge that you attack here.

a7

---

<div class="post-metadata">

**Author:** ![qubits-us](https://avatars.discourse-cdn.com/v4/letter/q/5daacb/32.png) [@qubits-us](https://forum.arduino.cc/u/qubits-us)\
**Post date:** [February 15, 2023, 6:20pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/12 "2023-02-15T18:20:39Z")

</div>

need to cast the object to a base object that defines the runMethod..  
if all objects are derived from that base object, then should work..

looking through the source..  
this is where having all the dope in the h file kind of kills you..

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 15, 2023, 7:04pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/13 "2023-02-15T19:04:11Z")

</div>

Th constraint came from the original author, who suggests putting the automatic create-destroy things into the user-customized functions that call the different objects in the .h-files But then the suggested user-functions are blocking.

If the backend functions were more configureable, like a hypothetical updated `Fire2032::Fire2023(CRGB::color color)` object with author-suggested user functions like:

```cpp
void run_coolFire(){
  isRunning = true;
  Fire2023 fire2023 = Fire2023(CRGB::Blue);
  while(isRunning) fire2023.runPattern();
}

void run_warmFire(){
  isRunning = true;
  Fire2023 fire2023 = Fire2023(CRGB::Red);
  while(isRunning) fire2023.runPattern();
}

```

If memory isn't a concern maybe it would require only `static` and `if`:

```cpp
void run_warmFire(){
  isRunning = true;
  static Fire2023 fire2023 = Fire2023(CRGB::Red);
  if(isRunning) fire2023.runPattern();
}

```

...tinker...tinker...

Yes -- static initialization is enough. Relative to the above, I still needed some added logic to handle the non-blocking transition change.

```cpp
void runPacificaStatic(){
  static bool wasRunning = false;
  static Pacifica pacifica;
  if(wasRunning == false){
    isRunning = true;
    wasRunning = isRunning;
    if(verbose>1)Serial.print(F("Pacifica"));
  }
  if(changePattern){
    isRunning = false;
    wasRunning = false;
      if(verbose>1)Serial.print(F("Over\n"));
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pacifica.runPattern();
}

```

That wokwi sim is running with that runPacificaStatic() now:

> **[FastLED\_classesTimer\_nonblocking - Wokwi Arduino and ESP32 Simulator](https://wokwi.com/projects/356666059490147329)**
>
> Run IoT and embedded projects in your browser: ESP32, Arduino, Pi Pico, and more. No installation required!

 ![image](https://europe1.discourse-cdn.com/arduino/original/4X/0/f/5/0f58c9276fcdf0818195da514af728798efb3ab4.png)

```cpp
// Attempt at non-blocking version of FastLED classesTimer.ino example
// https://wokwi.com/projects/356666059490147329
// Discussion at 
// https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335
//
// Based on sim from https://wokwi.com/projects/356665860602531841
// with code from https://github.com/s-marley/FastLED-basics/tree/main/5.%20Multiple%20patterns/classesTimer
// using a wokwi-neopixel-canvas
//
// Contribution of SRAM monitor from qbits-us per 
// https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/2
//
// Try to make non-blocking
//
// On Nano:
// A0 potentiometer: led speed 1-600 sec
// A1 potentiometer: report speed 1-1000 ms
// 
// Note that the reading of the A0 report() happens frequently while the loop animations are going 

#include <FastLED.h>

#define NUM_LEDS 18
const int LED_PIN = 2;
const int LED_speed_pin = A0; 
const int report_speed_pin = A1; 
const int verbose = 4;

CRGB leds[NUM_LEDS];
uint8_t patternCounter = 0;
bool isRunning = false;
bool changePattern = false;

void checkTimer();
int reportInterval = 500; // ms
int ledInterval = 1; // sec

#include "Fire2012.h"
#include "Pacifica.h"
#include "Pride2015.h"

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(100);
  Serial.begin(115200);
  pinMode(LED_speed_pin,INPUT);  
  pinMode(report_speed_pin,INPUT);  
}

void loop() {
  
  handleIO();

  switch (patternCounter) {
    case 0:
      runFire2012();
      break;
    case 1:
      if(1) runPacificaStatic(); else // XXX comment to use runPacifica
       runPacifica();
      break;
    case 2:
      runPride2015();
      break;
  }
  report();
  if(verbose >=0) LoopCounter();
}

/////////// diagnostic code for excercising doing several things at once 
// An output line like this consists of several reports
// Pride2015.- SRAM left: 1514 400Hzdeleted
// ^ object intantiated
// ^ report triggered
// ^ Free SRAM report
// ^ loop() frequency
// ^ object deleted
void report(){
  static uint32_t last=0;
  //const int interval=1;
  if(millis() - last > reportInterval){
    last+=reportInterval;
    if(verbose >= 3)Serial.print('.');
    if(verbose >= 2)display_freeram();
  }
}

int lastFreeRam = 0;

void display_freeram() {
  int ramleft = freeRam();
  if (ramleft!= lastFreeRam)
  {
   lastFreeRam = ramleft; 
  Serial.print(F("- SRAM left: "));
  Serial.print(ramleft);
  Serial.print(' ');
  }
}

int freeRam() {
  extern int __heap_start,*__ brkval;
  int v;
  return (int)&v - (__brkval == 0  
    ? (int)&__heap_start : (int)__brkval);  
}

void LoopCounter() // tells the average response speed of void loop()
// code modified from https://forum.arduino.cc/t/while-loop-as-a-condition-for-limit-switches/963899/11
{ // inside a function, static variables keep their value from run to run
  const unsigned long microsInOneSecond=1000000UL;
  static unsigned long count, countStartMicros; // only this function sees these

  count++; // adds 1 to count after any use in an expression, here it just adds 1.
  if ( micros() - countStartMicros >= microsInOneSecond ) // 1 second
  {
    countStartMicros += microsInOneSecond; // for a regular second
    Serial.print( count ); // 32-bit binary into decimal text = many micros
    Serial.print("Hz");
    count = 0; // don't forget to reset the counter 
  }
}
//////////// end diagnostic code 

void handleIO(void){
   const int interval = 250; //ms
   static uint32_t last = -interval;
  if(millis() - last >= interval){
    ledInterval = map(analogRead(LED_speed_pin),0,1024,1,600); // seconds
    reportInterval = map(analogRead(report_speed_pin),0,1024,1,1000); // ms
  }
}

void checkTimer() {
  static uint32_t last = 0;
  if(millis() - last >= ledInterval*1000UL){
    last = millis();
    nextPattern();
  }
}

void nextPattern() {
  isRunning = false;
  changePattern = true;
  //patternCounter = (patternCounter + 1) % 3;
}

// These runXXXX commands were modified from the original to
// be non-blocking by keeping a static pointer to an object
// that persists between calls, and is destryed when finished.

void runFire2012(){
  static Fire2012 *fire2012;
  if(! fire2012) {
    isRunning = true;
    fire2012 = new Fire2012;
    if(verbose>1)Serial.print(F("Fire2012"));
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(fire2012){ // de-allocate
      delete fire2012;
      fire2012=NULL;
      if(verbose>1)Serial.print(F("deleted\n"));
    }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
// Fire2012 fire2012 = Fire2012();
  if(isRunning) fire2012->runPattern();
}

void runPacificaStatic(){
  static bool wasRunning = false;
  static Pacifica pacifica;
  if(wasRunning == false){
    isRunning = true;
    wasRunning = isRunning;
    if(verbose>1)Serial.print(F("Pacifica"));
  }
  if(changePattern){
    isRunning = false;
    wasRunning = false;
      if(verbose>1)Serial.print(F("Over\n"));
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pacifica.runPattern();
}

void runPacifica(){
  static Pacifica *pacifica;
// if( !isRunning || ! pacifica) {
  if( ! pacifica) {
    isRunning = true;
    pacifica = new Pacifica;
    if(verbose>1)Serial.print(F("Pacifica"));
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(pacifica){
      delete pacifica;
      pacifica = NULL;
      if(verbose>1)Serial.print(F("deleted\n"));
    }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pacifica->runPattern();
}

void runPride2015(){
  static Pride2015 *pride2015;
  if( ! pride2015) {
    isRunning = true;
    pride2015 = new Pride2015;
    if(verbose>1)Serial.print(F("Pride2015"));
  }
  if(changePattern){ // shut things down and transition
    isRunning = false;
    if(pride2015){
      delete pride2015;
      pride2015 = NULL;
      if(verbose>1)Serial.print(F("deleted\n"));
   }
    patternCounter = (patternCounter+1)%3;
    changePattern=false; // oneshot
  }
  if(isRunning) pride2015->runPattern();
}

```

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 15, 2023, 7:14pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/14 "2023-02-15T19:14:16Z")

</div>

Yeah. There's a lot of FastLED animation code that needs rewrites, and most implementations have a bunch of hacked-together functions copy-pasted from elsewhere.

Here, half of it looked non-blocking (the stuff in the .h files) but the other part seemed to add the blocking-ness unnecessarily.

---

<div class="post-metadata">

**Author:** ![anon56112670](https://avatars.discourse-cdn.com/v4/letter/a/c5a1d2/32.png) [@anon56112670](https://forum.arduino.cc/u/anon56112670)\
**Post date:** [February 15, 2023, 7:27pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/15 "2023-02-15T19:27:45Z")

</div>

> [@qubits-us](#):
>
> Have already discovered strings are bad due to memory fragmentation

strings are not the same as Strings.

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [February 15, 2023, 9:57pm UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/16 "2023-02-15T21:57:58Z")

</div>

> [@DaveX](#):
>
> What is the best way to make this FastLED animation code non-blocking?

let do void loop() **ALL** the looping.

Which means delete **ALL** while-loops and let do void loop() **ALL** the looping

Why would you want to create / destroy objects on runtime multiple times?  
This is just adding complexity and possible bugs by allocating and freeing RAM

It should be enough to create the objects **once** and then simply to do function-calls of the animation if this particular animation shall run.  
And to simply **NOT** call the animation if this animation shall **not** run

best regards Stefan

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 16, 2023, 1:28am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/17 "2023-02-16T01:28:28Z")

</div>

Surely not **ALL** of the looping. To eliminate the for loops to set each of the NUM\_LEDS to a specific color seems awkward -- you'd need to persist the for's loop state across loop() iterations, using a global or a static at some level.

Deleting the while loops in these functions make sense, but then you need to persist state for the objects across loop() iterations with maybe a global or static at some level.

The original author suggested that memory can be a problem for some animations, and liked the automatic creation and deletion in his blocking functions. At first I tried to follow that, but with @qubit-us's memory test, these particular functions do not need much state info, so statically allocating them with a global or a static with less scope seems fine. There are some FastLED functions that could need a lot more memory. For example, using the FastLED::blend() to crossfade between two patterns could use 3x the size of a uint32\_t leds[NUM\_LEDS] -- less than 170 LEDS on a 2kb Nano. If you needed to persist arrays across loop(), statically defining its storage might limit the ability to do other animations or limit the number of LEDs when it wasn't being used.

Maintaining state with a `static` declaration within the function seems the simplest/cleanest way to persist state across loops. But if you do run low on memory and need to release the storage when the function isn't active for a long time, is the {static Obj \*obj; obj = new Obj; delete obj; obj=nullptr;} pattern reasonable?

---

<div class="post-metadata">

**Author:** ![alto777](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/alto777/32/317385_2.png) [@alto777](https://forum.arduino.cc/u/alto777)\
**Post date:** [February 16, 2023, 2:49am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/18 "2023-02-16T02:49:54Z")

</div>

> [@DaveX](#):
>
> Surely not **ALL** of the looping.

No, only the loops that take more than zero, to a first approach, time. The time you can afford to block is something you get to decide.

Typically some loops have a delay call and a strip show to make an effect play out over time. Time that effects the response of the rest of the program cannot be wasted hanging out - if you don't care if a button takes 3 seconds to be seen, then don't "fix" the loop that causes that.

So all such looping, up to and includes stripping down a for loop into equivalent stages/states like setup, body, iterate and so forth.

Add variables as necessary to support that. A major state, _body_, might technically be dozens if you consider the true state of the machine is a step within a state.

I'm trying to see the use case for your mechanism. If there are N real pixels, how much more or less memory can one effect use than another, and wouldn't there need to be room for all the code? Of all the effects? There is no facility for overlays on an UNO.

I've been sidetracked by trying to use this to learn how or whether some things are done in C++ and haven't really worried about it making too much sense. I'd like to see this work and be verifiable as working well.

a7

---

<div class="post-metadata">

**Author:** ![DaveX](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/davex/32/751443_2.png) [@DaveX](https://forum.arduino.cc/u/DaveX)\
**Post date:** [February 16, 2023, 5:06am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/19 "2023-02-16T05:06:38Z")

</div>

> [@alto777](#):
>
> I'm trying to see the use case for your mechanism. If there are N real pixels, how much more or less memory can one effect use than another, and wouldn't there need to be room for all the code? Of all the effects? There is no facility for overlays on an UNO.

The clearest hypothetical use-case I could imagine would be if one took a pattern that uses blend to fade between two other patterns, like "[crossfadeTimer.ino](https://github.com/s-marley/FastLED-basics/blob/main/5.%20Multiple%20patterns/crossfadeTimer/crossfadeTimer.ino)" and try to package into some c++ class thing. While operating it would need to maintain state for two extra arrays for strips of pixels (which are global in that example) to fade between. If you tried to write it as some kind of c++ class that didn't use global namespace, it would need its own static arrays. If you had two or more such animations, they'd take `sizeof(CRGB leds[NUM_LEDS]) *(1+2*N)` pixel memory for N animations. You could re-write them to share some global arrays and use only 3x pixel storage, or you could write the animation to release the private pixel storage when disabled and be more independent and encapsulated (and potentially memory leaky)

Of course that is hypothetical, but since the author of the source code, Scott Marley, was advocating writing classes so that "The patterns are in ram for only as long as they are active. Once a pattern stops running, that memory is freed up for other patterns to use...", it conflicts with the persistent static or global variables seemingly required for non-blocking code. The classes Marley writes are non blocking, but to get the memory-freeing benefit, he wraps them in an automatic constructor/destructor function that blocks.

I wondered how you could have your cake and eat it too.

Marley on the advantages of writing FastLED patterns as c++ classes:

[![](https://europe1.discourse-cdn.com/arduino/original/4X/9/c/5/9c53edd6b5ddd1d562274fd1c4917ea8322a8df8.jpeg "FastLED Basics Episode 5 - Multiple patterns using a timer or button") ](https://www.youtube.com/watch?v=fRXJQVdwrog&t=549s)

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [February 16, 2023, 5:27am UTC](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335/20 "2023-02-16T05:27:19Z")

</div>

If RAM-usage becomes a problem and just a few IO-pins are needed I would change from a Arduino Nano to a Seeeduino XIAO

one third of the price of an original Ardiuno Nano and 16 times more RAM

Nano $22 / XIAO $7  
Nano 2kB SRAM / XIAO 32 kB SRAM  
Nano 32kB flash / XIAO 256 kB flash  
Clock Nano 16 MHz / XIAO 48 MHz

best regards Stefan

[Next page](https://forum.arduino.cc/t/make-some-fastled-code-non-blocking/1090335.md?page=2)
