0

I wrote this for my Arduino Mega 2560:

int LED[14] = { 28,29,30,31,32,33,34,35,36,37,38,39,40,41 } ;
...
... (some other code like setup(), etc. Note:pinmode output for this 14 leds wich pins is defined in
... array named LED[]
...
void intro(){
  for(int j=1; j<100; j++ ){
    for(int r=1; r<15; r++ ){ digitalWrite(LED[r],HIGH); delay(100);  }
    delay(100);
    for(int r=1; r<15; r++ ){digitalWrite(LED[r],LOW); delay(100);}
    delay(100);
  }
  Serial.print("Pattern started");
  delay(1000);
}

So when I run this script, I expect that each LED will light up in the sequence and remain lit until the second loop to turn it off, but I see that when lighting each LED, when lighting the 9th LED, the first 8 LEDs shut off inexplicably and LEDs 9 through 14 light one by one, remaining lit. That I expected but why do the first 8 LEDs shut off before the loop ends and the second loop starts?

  • maybe you are overloading the data pins – jsotola Mar 21 at 18:08
  • 5
    for (int r = 0; r < 14; r++). first index is zero and the size of the array is 14 – Juraj Mar 21 at 18:49
1

While it is true that your loop is incorrect, the coding error is unlikely to cause the behaviour that you have described.

Please ensure that a current limiting resistor is placed in series with each LED. Since you have 14 LEDs, you will need 14 current limiting resistors. 470 Ohm resistors (or similar) should be adequate for this purpose.

As per the other comments, C++ Arrays start at 0, not 1. The last element is the size of the array minus 1. In your case 14 - 1 = 13. Thus the loop can continue as long as the index is < 14 (or <= 13)

Thus your loops should read:

for(int r=0; r<14; r++ ) {
  digitalWrite(LED[r],HIGH);
  delay(100);
}
| improve this answer | |
0

your for statements with r=1 need to be changed to r=0;r<14 Arrays always start with the first item being 0, so yours is 0 to 13.

| improve this answer | |
  • and how does it cause the described behavior of the code? – Juraj Mar 25 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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