Lesson 4: for loops
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
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.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Blink pin 13 exactly 5 times (300 ms on, 300 ms off), then stop with the LED off. Use a for loop.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
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.
点击“运行”查看此处输出。