TEACHER GOAL

This lesson is a revisit to Lesson 4, where students first learned to work with digital pins in OUTPUT mode. The big difference is this time students learn to handle groups of pins by using the for loop of the C language. The syntax of the for loop is the same across C, C++, C#, and Java, so this is a highly transferable skill.

COMMON STUDENT MISTAKES

  • Students do not understand the syntax of the for loop, and thus make mistakes, particularly with the testing condition. The following is an example of this type of student error:

1  // the following won't run because pinNumber is
2  // never greater than 7
3  for(int pinNumber = 2; pinNumber >= 7; pinNumber++){
4    pinMode(pinNumber, OUTPUT);
5  }

Here is a corrected version of this loop:

1  // this loop will set the pins 2 throuh 7
2  // to OUTPUT
3  for(int pinNumber = 2; pinNumber <= 7; pinNumber++){
4    pinMode(pinNumber, OUTPUT);
5  }

  • Students have difficulty with the two-at-a-time programming because they don't understand processing before and after the for loop, and the mathematics allowed within the for loop. The following code segment shows how these are used to light two LEDs at a time, beginning with just one and ending with just one:

1  digitalWrite(2, HIGH);  // turn on first LED
2  delay(100);  // let viewer see it
3  digitalWrite(3, HIGH);  // turn on second LED
4  delay(100);
5  for(int pinNumber = 4; pinNumber <= 7; pinNumber++){
6    digitalWrite(pinNumber, HIGH); // turn on next LED
7    digitalWrite(pinNumber - 2, LOW); // turn trailing LED off
8    delay(100);
9  }
10 digitalWrite(6, LOW);  // turn off next to last LED
11 delay(100);
12 digitalWrite(7, LOW);  // now all are off
13 delay(100); // wait so viewers can see all off

Notice the subtraction in line 7 to set the trailing LED off.

  • Students are prone to making the same wiring mistakes as in Lesson 4.
  • Students sometimes attempt to use pins 0 and 1. While this is technically possible it should be discouraged as these pins are also involved in the Serial print methods for sending text to and getting text from the Arduino.

EXERCISES VIDEO

Here is the one-at-a-time sequence but with a pair of for loops, one to go up, followed by one to go down:

 

Odd / Even Alternating LEDs

Two at a time, beginning with all off, then one