Comparing Loops vs No Loops in Arduino Code | Task 2

In this task, we compare writing Arduino code with and without using for loops. Watch the videos and see how your code can be shorter and more powerful.

Example 1: Without using loops




        
// Lesson 6 part 1
// variables

int twoPin =2;
int threePin=3;
int fourPin=4;
int fivePin=5;
int sixPin=6;

int dt=500;


void setup() {
  // put your setup code here, to run once:
pinMode(twoPin,OUTPUT);
pinMode(threePin,OUTPUT);
pinMode(fourPin,OUTPUT);
pinMode(fivePin,OUTPUT);
pinMode(sixPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(twoPin,HIGH);
delay(dt);
digitalWrite(threePin,HIGH);
delay(dt);
digitalWrite(fourPin,HIGH);
delay(dt);
digitalWrite(fivePin,HIGH);
delay(dt);
digitalWrite(sixPin,HIGH);
delay(dt);

digitalWrite(twoPin,LOW);
delay(dt);
digitalWrite(threePin,LOW);
delay(dt);
digitalWrite(fourPin,LOW);
delay(dt);
digitalWrite(fivePin,LOW);
delay(dt);
digitalWrite(sixPin,LOW);
delay(dt);

}
      

Example 2: Using a for loop


Now open the Arduino IDE. Create a new sketch and follow the second example (with the for loop). Upload it to your board and observe how each LED turns on and off in sequence.

If your LEDs are not lighting up, first check your wiring. Then add debugging messages like the video shows.



//Lesson 6 part 2
// variables

int basePin = 2;
int numPins = 5;
int j;
int dt = 500;

void setup() {
  for (j = basePin; j < basePin + numPins; j = j + 1) {
    pinMode(j, OUTPUT);
  }
}

void loop() {
  for (j = basePin; j < basePin + numPins; j = j + 1) {
    digitalWrite(j, HIGH);
    delay(dt);
  }

  for (j = basePin; j < basePin + numPins; j = j + 1) {
    digitalWrite(j, LOW);
    delay(dt);
  }
}
        

Which approach do you prefer? The long version or the short loop version?