To use PWM, connect your LED (through its resistor) to one of the six pins marked ~ on the HERO Board, 3, 5, 6, 9, 10 or 11, and call analogWrite(pin, value) with a value from 0 (always off) to 255 (always on). The pin then switches between 5V and 0V hundreds of times a second, and the share of each cycle it spends on, the duty cycle, sets how bright the LED looks or how hard a motor pushes.
The HERO Board is Uno-compatible (it runs the ATmega328P), so the pins, numbers and timers below match any Uno-type board. New to boards like this? Start with what a microcontroller is.
What PWM Actually Does
A digital pin only has two states: 5V or 0V. PWM (Pulse Width Modulation) fakes the in-between by switching faster than your eye can follow. The LED is really flashing, but at 490 or 980 flashes a second it looks steady, and the more of each cycle it spends on, the brighter it looks.
0%: |___________________________| = 0V average
25%: |██████_____________________| = 1.25V average
50%: |█████████████______________| = 2.5V average
75%: |██████████████████_________| = 3.75V average
100%: |████████████████████████████| = 5V
The average voltage is 5V × value ÷ 255. analogWrite(9, 64) averages about 1.25V and analogWrite(9, 128) about 2.5V. The pin never actually sits at 2.5V: a multimeter shows the average of a square wave. That's why analogWrite() is a slightly misleading name. The output is digital; only the average is "analog".
analogWrite() in Detail
analogWrite(pin, value); // value: 0 to 255
- pin: a PWM pin, 3, 5, 6, 9, 10 or 11.
- value: the duty cycle. 0 is a plain LOW, 255 a plain HIGH, and every value between is PWM.
- The chip's hardware timers keep the pin pulsing on their own, so your sketch moves on at once. The pin holds that duty cycle until the next
analogWrite()on it, or adigitalWrite(), which switches PWM off on that pin. analogWrite()sets the pin to OUTPUT itself. ApinMode(pin, OUTPUT)insetup()is still good practice: it documents your wiring.
The PWM Pins, Their Timers and Their Speeds
Three hardware timers inside the ATmega328P generate the pulses, two pins each. That is why two pins run twice as fast, and why some functions take PWM pins away from you.
| Pins | Timer | PWM frequency | Also used by | |------|-------|---------------|--------------| | 5, 6 | Timer0 | about 980 Hz | millis(), delay(), micros() | | 9, 10 | Timer1 | about 490 Hz | the Servo library | | 3, 11 | Timer2 | about 490 Hz | tone() |
We measured these by running a compiled sketch in our simulator: 977 Hz on pin 5, 490 Hz on pins 9 and 11. Both speeds are far too fast to see, so for LEDs it makes no difference which PWM pin you pick. It matters when a buzzer or a servo shares the board, as you'll see under Common Mistakes.
Example 1: A Breathing LED
Wire pin 9 to a 220 Ω resistor, the resistor to the LED's long leg (anode), and the LED's short leg to GND. Then count the duty cycle up and back down:
// Breathing LED: fade the LED on pin 9 up and down, forever.
const int LED_PIN = 9; // must be a PWM pin (~)
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
for (int level = 0; level <= 255; level++) { // breathe in
analogWrite(LED_PIN, level);
delay(8);
}
for (int level = 255; level >= 0; level--) { // breathe out
analogWrite(LED_PIN, level);
delay(8);
}
delay(200);
}
Each of the 256 steps lasts 8 ms, so one breath in and out takes about four seconds. Make the delay(8) shorter for faster breathing.
Example 2: Mix Any Color on the RGB LED
An RGB LED is three LEDs in one package. Give each color its own PWM pin and its own 220 Ω resistor, and you can mix any color by setting three duty cycles. In the 30 Days Lost in Space Day 8 lesson red goes to pin 11, green to 10, blue to 9, and the longest leg (the shared cathode) to GND. Here is that lesson's sketch, shortened:
// RGB color mixing, shortened from the 30 Days Day 8 lesson.
// Each leg of the RGB LED goes through a 220 ohm resistor to a PWM pin.
const byte RED_PIN = 11;
const byte GREEN_PIN = 10;
const byte BLUE_PIN = 9;
void setup() {
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}
void displayColor(byte red, byte green, byte blue) {
analogWrite(RED_PIN, red);
analogWrite(GREEN_PIN, green);
analogWrite(BLUE_PIN, blue);
}
void loop() {
displayColor(64, 0, 0); // red at 1/4
delay(500);
displayColor(255, 0, 0); // red at full
delay(500);
displayColor(192, 192, 0); // red + green = yellow
delay(500);
displayColor(0, 192, 192); // green + blue = cyan
delay(500);
displayColor(192, 0, 192); // red + blue = magenta
delay(500);
displayColor(192, 192, 192); // all three = white
delay(500);
}
Red and green make yellow, green and blue make cyan, all three make white. The RGB LED guide explains why each leg needs its own resistor. For a smooth fade between colors, see the Color fade sketch under Code Examples at the bottom of this page.
Example 3: A Night Light That Dims Itself
PWM gets interesting when a sensor drives it. Wire the photoresistor as a divider (5V to the photoresistor, its other leg to A0 and to a 10 kΩ resistor, the resistor's far end to GND) and keep the LED on pin 9:
// Automatic night light: the darker the room, the brighter the LED on pin 9.
const int SENSOR_PIN = A0; // the photoresistor and the 10k resistor meet here
const int LED_PIN = 9; // a PWM pin (~)
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int light = analogRead(SENSOR_PIN); // 0 (dark) to 1023 (bright)
int brightness = map(light, 0, 1023, 255, 0); // flipped: dark room, bright LED
analogWrite(LED_PIN, brightness);
Serial.println(brightness);
delay(50);
}
analogRead() gives 0 to 1023, analogWrite() wants 0 to 255, and map() converts between them. Listing the output range as 255 to 0 flips it, so darkness gives a bright LED. The map() guide explains the conversion, and the photoresistor guide explains the divider.
Make Fades Look Even
Your eye is much more sensitive to changes in dim light than in bright light. Going from 10 to 40 looks like a big jump; going from 200 to 255 barely shows. Squaring the level spreads the visible steps evenly:
int perceived(int level) { // level: 0 to 255
return (long)level * level / 255; // also 0 to 255, with more steps at the dim end
}
Use analogWrite(LED_PIN, perceived(level)) in Example 1 and the breath looks smooth all the way down. The (long) matters: 255 × 255 is 65,025, too big for an int on this board (its limit is 32,767).
Common Mistakes
- Using a pin without ~.
analogWrite()on pin 2, 4, 7, 8, 12 or 13 can't make PWM. Values below 128 give a plain LOW and 128 or more a plain HIGH, so the LED snaps on and off instead of dimming. - Passing a value above 255. Only the lowest 8 bits reach the timer, so the number wraps around. In our test,
analogWrite(9, 256)left pin 9 completely off andanalogWrite(9, 300)gave the same dim glow as 44. Scale a 0 to 1023 reading withmap()or divide it by 4, and clamp anything else withconstrain(value, 0, 255). - Sharing a timer with tone() or Servo. While
tone()plays, pins 3 and 11 stop pulsing. Worse,analogWrite()on pin 11 during a tone overwrites the timer setting the tone runs on: in our test a 1,000 Hz tone jumped to about 2,475 Hz. The Servo library takes over Timer1, so pins 9 and 10 lose PWM as soon as a servo is attached. When a buzzer is in the circuit, dim your LEDs on 5, 6, 9 or 10. - Mixing digitalWrite() and analogWrite() on one pin.
digitalWrite()turns PWM off for that pin. That's right when you mean it, and baffling when two parts of a sketch fight over the same pin. - Driving a motor straight from the pin. 40 mA is the absolute maximum a pin can supply, and 20 mA is a comfortable working limit. A motor needs a transistor or driver board between the pin and the motor, with the PWM signal on the transistor's input.
Frequently Asked Questions
What is PWM in Arduino code?
It's how analogWrite() produces "in-between" output from a pin that can only be on or off. The pin switches on and off at a fixed rate, and the value you pass (0 to 255) sets how much of each cycle it stays on. LEDs look dimmer and motors run slower because they respond to the average.
Which pins support PWM on the HERO Board?
Pins 3, 5, 6, 9, 10 and 11, the ones with a ~ next to the number. The analog pins A0 to A5 are inputs for analogRead() and can't produce PWM. The HERO Board guide has the full pin map.
Why is analogWrite() 0 to 255 when analogRead() is 0 to 1023?
The timers that make PWM count in 8 bits (256 steps), while the analog-to-digital converter that reads A0 to A5 measures in 10 bits (1,024 steps). Convert a reading with map(reading, 0, 1023, 0, 255) or reading / 4.
Can I change the PWM frequency?
Yes, by changing a timer's prescaler, and pins 9 and 10 (Timer1) are the safe pair to change:
TCCR1B = (TCCR1B & 0b11111000) | 0b001; // in setup(): pins 9 and 10 at about 31.4 kHz
After that line we measured 31,372 Hz on pin 9, above the range you can hear, which is the usual reason to do it with motors. Leave Timer0 (pins 5 and 6) alone: millis() and delay() count with it, so changing it changes how long a "second" lasts. And don't change Timer1 in a sketch that uses the Servo library.
Is PWM a real analog voltage?
No. It's a square wave whose average is the value you set. LEDs, motors and heaters respond to the average, which is why PWM works for them. If you need a steady voltage, smooth the output with a resistor and a capacitor (a low-pass filter).
Do I need pinMode() before analogWrite()?
No, analogWrite() makes the pin an output itself. Writing pinMode(pin, OUTPUT) anyway costs nothing and makes the sketch easier to read.