2

I am trying to run a very simple program to glow LEDs in a certain fashion, I connected 9 LEDs to the GPIOs or digital pins, 2 To 10, via 220 Ohm resistors; when I am running the program it is hanging the Arduino after some time interval and LEDs stops glowing, not sure if it is a hardware issue or some bug in the software/code.

Here is the code:

int outGPIOsarr[9] = {2,3,4,5,6,7,8,9,10};

void setup() {
  
  for(int i=0; i<10; i++)
pinMode(outGPIOsarr[i], OUTPUT);
}

void loop() {
  
for(int i=0; i<10; i++) 
 {
digitalWrite(outGPIOsarr[i],HIGH);
delay(10);
 }

for(int i=0; i<10; i++) 
 {
digitalWrite(outGPIOsarr[i],LOW);
delay(10);
 }

}
Ashish Jog
  • 31
  • 4
  • 1
    Anything getting hot? Try using higher resistor values (470 or even 1k), you're drawing more than the allowed amps from a 328P (200mA IIRC) – Mat Aug 15 '21 at 13:00
  • @Mat , nothing is getting hotter , I checked it, one thing I observed is when I change the first argument of digitalwrite from outGPIOsarr[i] to respective pin number and change for loop from to run from 2 to 10 the code is running fine without a problem ! But I am not able to find good reasoning behind it !? – Ashish Jog Aug 15 '21 at 13:21

1 Answers1

3

This is the UB!

The indexes in array in C++ counts from 0;

So, the last index in your array of 9 elements is 8.

All cycles must stop at 8. Yours are stops at 9.

Access beyond the existing element in the array is the Undefined Behavior - it hangs the MCU.

gbg
  • 528
  • 3
  • 11
  • 2
    Oh well that was an embarrassing bug, thanks for pointing out >_ – Ashish Jog Aug 15 '21 at 13:29
  • and OP can't delete a question if it has an upvoted answer – Juraj Aug 15 '21 at 16:02
  • But why this topic must be deleted? – gbg Aug 15 '21 at 16:20
  • because the question is not about the arduino, it is a general programming question, so it is off topic here ... any answers are also off topic here – jsotola Aug 15 '21 at 18:09
  • I disagree. The reason is - OP doesn't know, what causes hanging - wrong firmware or wrong hardware. So, to mark the question as off topic, you must literally answer the question. – gbg Aug 15 '21 at 18:31
  • https://arduino.meta.stackexchange.com/questions/2667/trivial-questions-must-be-off-topic – Juraj Aug 16 '21 at 05:24
  • OP would like to remove the question because it is an "an embarrassing bug" and if not closed, with this count of votes it would be a "Hot network question" representing Arduino SE on the right side of every SE page. – Juraj Aug 16 '21 at 05:27