Fade with PWM
Smoothly fade an LED using analogWrite. Introduction to pulse-width modulation and duty cycles.
1What is PWM?
Digital pins can only output full ON (5V) or full OFF (0V). But what if you want something in between — like half brightness? Pulse-Width Modulation (PWM) simulates an analog voltage by rapidly switching a pin on and off.
The key concept is duty cycle: the percentage of time the pin spends HIGH in one cycle. A 50% duty cycle (on half the time) averages out to 2.5V. A 25% duty cycle averages to 1.25V. The switching happens so fast (~490Hz) that an LED appears to dim smoothly.
Note: On the Arduino Uno, only pins 3, 5, 6, 9, 10, and 11 support PWM. They're marked with a ~ symbol on the board.
2analogWrite()
analogWrite(pin, value) sets the duty cycle on a PWM pin. The value ranges from 0 (always off, 0V) to 255 (always on, 5V). 128 is approximately 50% duty cycle.
analogWrite(9, 0); // Off
analogWrite(9, 128); // ~50% brightness (~2.5V)
analogWrite(9, 255); // Full brightness (5V)Note: Despite the name, analogWrite() doesn't produce a true analog voltage — it's still a digital square wave. The averaging effect makes it behave like analog.
3Building the Circuit
- Connect pin 9 → 220Ω resistor → LED anode (long leg)
- LED cathode (short leg) → GND
- Pin 9 is a PWM pin (~) on the Uno
4The Fade Sketch
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
// Fade in: 0 to 255
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(ledPin, brightness);
delay(10); // 10ms per step = ~2.5 second fade
}
// Fade out: 255 to 0
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(ledPin, brightness);
delay(10);
}
}The for loop increments brightness from 0 to 255, writing each value to the LED. At 10ms per step with 256 steps, each fade takes about 2.5 seconds.
Skill Check
8 questions · Up to 180 XP
Q1.What does PWM stand for?
Q2.What range of values does analogWrite() accept?
Q3.Which pins on the Arduino Uno support PWM?
Q4.A 50% duty cycle on a 5V Arduino produces approximately what average voltage?
Q5.What does analogWrite(9, 0) do?
Q6.What approximate PWM frequency does the Arduino Uno use?
Q7.What does analogWrite(9, 255) produce?
Q8.Why does the fade appear smooth to the human eye?
Sign in to earn XP for your answers.