Lesson 4: for loops
Esta página necesita un navegador reciente (con soporte para SharedArrayBuffer). Por favor, actualiza Chrome, Edge, Firefox o Safari a la última versión.
English
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.
English
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.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Blink pin 13 exactly 5 times (300 ms on, 300 ms off), then stop with the LED off. Use a for loop.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
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.
Haz clic en Ejecutar para ver la salida aquí.