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 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
  • 518
  • 3
  • 11