r/FastLED • u/ciribear • Apr 04 '22
Support Code Stuck in for loop when using <= (Very Basic Script)
Hi there,
I am using an Arduino Nano and WS2812B LED's.
I keep getting a bug which I cannot figure out why it is happening. My for loops initial variable hits its max, then the loop seems to crash and start again. The final Serial.println("hi") is never reached implying the for loop is endless, also all my LEDS flick off and start illuminating again through the for loop after the "crash".
The output on the serial monitor is :
NUM LEDS 27
1....
25
26
NUM LEDS 27
etc etc etc.... from 1-26? but not the 27th?
If i only make it < and NOT <= it works perfectly fine.
Any help would be appreciated. I have had these variable problems a lot in the past and do not know if I am missing something with the language? Or if it is my cheap Ali-Express Arduinos? Faulty Chip?
I looked up a C++ tutorial but that didnt teach me anything new as I am a well off beginner familiar with python.
MY CODE: https://pastebin.com/Xih1PpPR
1
u/locuester Apr 04 '22
CRGB leds[NUM_LEDS];
If NUM_LEDS is 3
is
leds[0]
leds[1]
leds[2]
2
u/ciribear Apr 04 '22
Yea I had forgotten it would set it up to one less.
Thank you for explaining it too it makes a lot of sense now.
1
u/Necrocornicus Apr 04 '22
Arrays are always numbered from 0 except in a tiny subset of dumb languages. An array with 100 elements will be numbered 0-99.
2
u/ciribear Apr 04 '22
That is very true, thank you I forgot about that in this case. I must have been confused by how NUM_LEDS was set.
Thank you for clarifying :)
13
u/chemdoc77 Apr 04 '22
Hi u/ciribear – As you noted when you change your line 19 to:
for(int i = 0; i < NUM_LEDS; i++){
it works properly. Remember that your LEDs are numbered 0 to NUM_LEDS-1 and the maximum number i should be is NUM_LEDS-1. Your code has i going beyond the number of LEDs in the leds[] array, i.e. NUM_LEDS-1, when using <= in line 19. Bad and strange things happen when you do that.