Teach Remote lab lessons

Teach lesson

Basic Arduino 2/4: create a light sequence

Students program four external LEDs with arrays and loops, test a 1-2-3-4 sequence, and turn it into a back-and-forth pattern.

  • Arduino Board (code)
  • 35 min
  • Lower secondary / first physical-programming lessons
  • English
  • Embedded systems
Arduino Board (code)
Arduino Board (code)

Learning Outcomes

  • Use several digital pins as outputs.

  • Understand a simple for loop.

  • Modify a light pattern.

Student activity preview

Activity Content

Preview only. In a class session, students can fill in responses and submit their work to the teacher.

1

One board, several LEDs

9 min

The board has four external LEDs connected to pins 8, 7, 6, and 5. The goal is to turn one LED on and off at a time to make a visible sequence: LED 1, LED 2, LED 3, and LED 4. You could write four almost identical blocks of code, one for each LED, but an array and a for loop avoid so much repetition. Think of the array as a list of pins, and the for loop as a way to go through that list and apply the same action to each LED.

Look at this part of the activity's base program:

const int totalLeds = 4;

void loop() {
  for (int i = 0; i < totalLeds; i++) {
    // Turn one LED from the list on and off.
  }
}

According to that snippet, how many times does the for loop inside loop() repeat?

2

Program the sequence

18 min

First test the base program: it should turn on LED 1, LED 2, LED 3, and LED 4, one after another. Then modify it so the sequence comes back the other way: LED 1, 2, 3, 4, 3, 2. One simple way is to add a second for loop after the first one, starting from the next-to-last LED so LED 4 is not repeated twice in a row. Save the file before attaching the snapshot.

const int leds[] = {8, 7, 6, 5};
const int totalLeds = 4;

void setup() {
  for (int i = 0; i < totalLeds; i++) {
    pinMode(leds[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < totalLeds; i++) {
    digitalWrite(leds[i], HIGH);
    delay(300);
    digitalWrite(leds[i], LOW);
  }
}
  1. Open the lab.

  2. Upload the base program and observe the LED order.

  3. Add the return path: after LED 4, the pattern should turn on LED 3 and LED 2 before starting again.

  4. Save before capturing the code.

Submit your code

Capture the code for your back-and-forth sequence: LED 1, 2, 3, 4, 3, 2. Before attaching it, save main.ino in the lab environment. The snapshot must show the program you actually want your teacher to review.

3

Read the program

8 min

Which line would you change so that each LED stays on for longer? Name the line and the new value you would try.