“8 LED Fun” for Arduinos explained

arduinobasicled

I'm relatively new to programming, Arduinos, and online forums in general. I would really appreciate an explanation for one of the basic tutorials for Arduinos:

I connected 8 LEDs to 8 pins (2 through 9) and programmed a short script to light the LEDs up successively, based on a schematic (found here): http://www.instructables.com/files/deriv/F45/G030/FVT7A09T/F45G030FVT7A09T.LARGE.jpg

A sample code suggests:

int ledPins[] = {2,3,4,5,6,7,8,9);

void setup(){
  for(int i = 0; i<8; i++){
    pinMode(ledPins[i], OUTPUT);
  }
}    
void loop(){
  oneAfterAnotherNoLoop();
}    
void oneAfterAnotherNoLoop(){
  digitalWrite(ledPins[0], HIGH);
  delay(10);
  digitalWrite(ledPins[0], LOW);
  delay(10);
  ...
}

However, I'm confused about the function of the setup() method! I'm told that the setup() method only runs once, so shouldn't the lights stop blinking after one iteration? Or is it a way to initialize ALL 8 pins continuously (and not successively)? Additionally, why is the setup() and oneAfterAnotherNoLoop() methods needed? I wrote everything into the loop() method:

void loop(){
  for(int i = 0; i<10; i++){
    pinMode(ledPins[i], OUTPUT); 
    digitalWrite(ledPins[i], HIGH);
    delay(250);
    digitalWrite(ledPins[i], LOW);
    delay(250);
  }
}

And this ran pretty well, except after maybe 20 iterations, it just got stuck on the first LED light 🙁

Any feedback would be greatly appreciated! Thanks!

Best Answer

The setup() method run only once because it is used in order to set the direction of the pins (Input or Output).

The oneAfterAnotherNoLoop() method produce only a blink of the LEDs. It turns on the LEDs, wait a little bit, turns off the LEDs and wait another little bit.

The loop() method is an infinite loop that calls the oneAfterAnotherNoLoop() method in order to produce an infinite cycle of blinking.

In your code you initialize the pins every time and this isn't needed. Try this:

void loop() {
  for (int i = 0; i < 8; i++) {       // Initialize pins
    pinMode(ledPins[i], OUTPUT);      // Set pin i as an OUTPUT
  }
  while (1) {                         // Infinite loop
    for (int i = 0; i < 8; i++) {
      digitalWrite(ledPins[i], HIGH); // Drive LED i HIGH
      delay(250);                     // Wait
      digitalWrite(ledPins[i], LOW);  // Drive LED i LOW
      delay(250);                     // Wait
    }
  }
}