Int variable is different before or after, unrelated loop

Hi there, I am using FastLED library to make some LEDs rainbow fade however if I increase my variable Color before the 'for loop' it gives eratic values, however if I increase it after the 'for loop' it works normally, why is this?

If I increase it before the loop I get color values of:

Erratic LED Colors: 222, 166, 17, 211, 137, 1, 254

Placed after the Loop I get:

An expected fade transition: 4, 5, 6, 7, 8, 9.... etc 

My Code:

#include <FastLED.h>

#define NUM_LEDS 3
#define DATA_PIN 3
uint8_t color = 0;
CRGB leds[NUM_LEDS];
 
void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);  
  Serial.begin(9600);
}


void loop() {

  color++; // PLACED HERE gives erratic values...

  for(int i = 0; i <= NUM_LEDS; i++){
    leds[i] = CHSV(color ,255,255);
  }

// color++;  // PLACED HERE works fine!

  Serial.println(color);
  delay(200);
  FastLED.show();
}

I am using Arduino IDE 2.1.1 and FastLED 3.6.0

Thank you

This loop writes outside of the array leds[] and trashes memory you don't own.

Replace "<=" with "<".

1 Like

Oh right, thank you! Of course because the array is only 0,1,2 sorry for the basic question!

When you say 'trashes memory you dont own' do you mean overwrites memory that is being used by something else?

Would that be why it works one way an not the other? Because it may be changing values in memory that are assigned to the number of 'color'?

Thank you for the quick response!

yes that's what was meant.

May be these bytes in memory were not used, in which case there could be not bad side effect* but if those bytes were the location of another variable, then you've overwritten this memory and changed something ...


* but the C++ standard says the writing beyond the end of your array is Undefined Behaviour, so all bets are off at that point, the fact that it works might change if you add one line of code

1 Like

Awsome, thank you that is very interesting. I would have thought the IDE would have picked up on this kind of mistake. But it is really helpful to know now for future errors as I have had unexpected behavior from projects before. :slight_smile:

Thank you very much!

It does, if you have the preferences set to show all compiler warnings (although the warning can be a bit cryptic):

/home/user/.arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino/main.cpp: In function 'main':
/home/user/Arduino/libraries/FastLED/src/hsv2rgb.cpp:467:11: warning: iteration 3 invokes undefined behavior [-Waggressive-loop-optimizations]
     rgb.r = r;
           ^
/tmp/arduino_modified_sketch_325038/BlinkWithoutDelay.ino:18:20: note: within this loop
   for(int i = 0; i <= NUM_LEDS; i++){
                    ^

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.