Overview
A for loop has three parts: a start, a condition checked before each pass, and
a step applied after each pass. for (int i = 0; i < 5; i++) runs with i = 0, 1, 2, 3, 4.
You will need
- Arduino Uno R3
- LED and 330 Ω resistor
- Breadboard
Wiring
| Uno pin | Connects to | Notes |
|---|---|---|
| 9 | 330 Ω → LED anode | PWM pin |
| GND | LED cathode |
The sketch
const int LED_PIN = 9; // PWM pin
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// Fade in: 0, 5, 10 ... 255
for (int level = 0; level <= 255; level += 5) {
analogWrite(LED_PIN, level);
delay(20);
}
// Fade out
for (int level = 255; level >= 0; level -= 5) {
analogWrite(LED_PIN, level);
delay(20);
}
delay(400);
// Three quick blinks
for (int blink = 0; blink < 3; blink++) {
digitalWrite(LED_PIN, HIGH);
delay(100);
digitalWrite(LED_PIN, LOW);
delay(150);
}
delay(600);
}How the code works
Watch the loop bounds: <= 255 includes 255; < 255 would stop at 250.
Counting down needs >= 0 and -=. Use int, not byte, for
the counter: a byte can never exceed 255, so level <= 255 would always be true and the
loop would never end.
What you should observe
- The LED breathes in and out over about two seconds, then blinks three times.