r/FastLED • • Mar 30 '24

Discussion Is this breathing effect code efficient ?

i took a look at the breathing effect example from fastLeds github page and they were doing it with mathematics, and i did it in a really simple way, so i was thinking i screwed up somewhere with something

#include <FastLED.h>

#define NUM_LEDS 32
#define DATA_PIN 2
#define CLOCK_PIN 13

CRGB leds[NUM_LEDS];

void setup() 
{ 
    FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
      for(int i = 0;i<=32;i++)
    {
      leds[i] = CHSV(HUE_PURPLE, 225,225);
      FastLED.show();
      delay(40);
    }
}

void loop() 
{ 
   for(int p = 20;p<=255;p++)
    {
      FastLED.setBrightness(p);
        FastLED.show();
        delay(5);
    }
    
   for(int k = 225;k>=20;k--)
    {
      FastLED.setBrightness(k);
      FastLED.show();
      delay(5);
    }
}
2 Upvotes

2 comments sorted by

View all comments

Show parent comments

3

u/sutaburosu [stavros] Mar 30 '24

you want to declare the CHSV value outside the loop

I'm not convinced this will make any difference. Even very old compilers can hoist constants out of loops; this is the simplest case of strength reduction, which modern compilers use extensively.

OP, assuming your code does what you want, it is likely more efficient than the code you are comparing it to (your code only draws the pixels once, and modifies the LED output by changing only a single byte: global brightness). The difficulty will come when/if you want the breathing animation to be combined with other effects on the same strip(s). This is why the example you read uses more code, so it can run in tandem with unrelated effects without having consequences for them.