Lesson 4: for loops
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
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.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Blink pin 13 exactly 5 times (300 ms on, 300 ms off), then stop with the LED off. Use a for loop.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
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.
Nhấn Chạy để xem kết quả ở đây.