Lesson 4: for loops
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Do it several times
- A
forloop repeats lines a fixed number of times. for (int i = 0; i < 3; i++)countsi= 0, 1, 2. That is 3 times.
void setup() {
pinMode(13, OUTPUT);
for (int i = 0; i < 3; i++) { // 3 quick blinks
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(200);
}
}
void loop() {
}
- The blinks are in
setup(), so they happen once.loop()is empty, so then the board does nothing.
A row of LEDs
- The loop variable can be a pin number.
void setup() {
for (int pin = 2; pin <= 5; pin++) {
pinMode(pin, OUTPUT);
}
}
void loop() {
for (int pin = 2; pin <= 5; pin++) {
digitalWrite(pin, HIGH);
delay(150);
digitalWrite(pin, LOW);
}
}
- Press Run: a light runs along pins 2, 3, 4, 5.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Blink pin 13 exactly 5 times (300 ms on, 300 ms off), then stop with the LED off. Use a for loop.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Switch on pins 2, 3, 4, 5 and 6 one after the other, 200 ms apart, so the bar grows. Then switch them all off and start again. Use for loops.
Click Run to see the output here.