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);
 }

}
2
  • 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
    Commented Aug 15, 2021 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
    Commented Aug 15, 2021 at 13:21

1 Answer 1

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.

7
  • 2
    Oh well that was an embarrassing bug, thanks for pointing out >_<
    – Ashish Jog
    Commented Aug 15, 2021 at 13:29
  • and OP can't delete a question if it has an upvoted answer
    – Juraj
    Commented Aug 15, 2021 at 16:02
  • But why this topic must be deleted?
    – gbg
    Commented Aug 15, 2021 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
    Commented Aug 15, 2021 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
    Commented Aug 15, 2021 at 18:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.