Fade an LED with PWM (Arduino)
Smoothly fade an LED brighter and dimmer using analogWrite on a PWM pin. Learn pulse-width modulation and for-loops.
Beginner15 min
What you need
Wiring
Hover a pin or a wire to trace the connection.
Code
fade.ino
// Fade an LED up and down using PWM (analogWrite).
// Use a PWM-capable pin — on the Uno these are marked with ~ (3,5,6,9,10,11).
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int b = 0; b <= 255; b++) { analogWrite(ledPin, b); delay(8); } // fade up
for (int b = 255; b >= 0; b--) { analogWrite(ledPin, b); delay(8); } // fade down
}
Steps
- Wire the LED from D9 through a 220Ω resistor; cathode to GND.
- D9 must be a PWM pin (marked ~ on the board).
- Upload the sketch. The LED breathes smoothly up and down.
- Try changing the delay to speed up or slow down the fade.