Sub topic 11
PWM frequency and the timers behind it
This chapter assumes you can already use analogWrite() on an Uno and know what duty cycle means. It also assumes you have seen a volatile or register name in AVR code before. You do not need to have used registers. The goal is to explain why analogWrite() produces the frequency it does, how to change that frequency, and what you break when you do.
What frequency means for PWM
A PWM signal repeats a fixed period. In each period the pin is high for a fraction of the time (the duty cycle) and low for the rest. The frequency is the number of periods per second:
frequency = 1 / period
On an Uno, most PWM pins run at about 490 Hz, so one period lasts about 2.04 ms. The duty cycle sets how much of that 2.04 ms the pin is high. The frequency sets how often the high-and-low pattern repeats.
For a plain LED, 490 Hz is already fast enough. Your eye averages the flashes and sees steady light. Frequency still matters in other cases:
- Cameras and phone video can show bands or flicker when the LED's period is close to the shutter timing.
- Motors and inductors can make an audible whine when the frequency falls in the hearing range.
- Switching a MOSFET very fast wastes energy as heat during each transition.
- Smoothing the signal into a steady voltage with a resistor and capacitor works better at higher frequency.
Where the signal comes from: timers
analogWrite() does not toggle the pin in your code. The pin is driven by a hardware timer/counter inside the ATmega328P chip. The processor sets it up once, and after that the timer produces the waveform with no further CPU work. This is why PWM keeps running while delay() blocks your code.
Each timer has three parts that matter here:
- A counter register that increases by one on every timer tick.
- A prescaler that divides the 16 MHz system clock to set how fast ticks happen.
- Compare registers (named
OCRnAandOCRnB). When the counter equals a compare value, the hardware changes the output pin.
The analogWrite() value (0 to 255) is written straight into a compare register. Its value is therefore the point in the count at which the pin goes low.
The three timers on the Uno
| Timer | Width | PWM pins | Default frequency | Also used for |
|---|---|---|---|---|
| Timer0 | 8-bit | 5, 6 | about 976 Hz | `millis()`, `micros()`, `delay()` |
| Timer1 | 16-bit | 9, 10 | about 490 Hz | `Servo` library |
| Timer2 | 8-bit | 3, 11 | about 490 Hz | `tone()` |
Two pins on the same timer share a frequency. You cannot give pin 9 one frequency and pin 10 another, because both follow Timer1.
Other boards use different chips with different timers. The Mega and the Leonardo have different pin-to-timer maps and defaults. Check the datasheet or board documentation before you reuse these numbers.
How the default frequencies arise
The Arduino core configures each timer in one of two modes.
Fast PWM (Timer0). The counter counts from 0 up to 255, then wraps to 0. The pin goes high at the wrap and low when the counter equals the compare value. One period is 256 ticks.
Phase-correct PWM (Timer1 and Timer2). The counter counts up from 0 to 255, then back down to 0. The pin goes low on the way up at the compare match and high again on the way down. One period is 510 ticks, because the counter passes 1 through 254 twice, with 255 and 0 each visited once.
The core sets the prescaler to 64 for all three timers, so the timer ticks at 16 000 000 / 64 = 250 000 Hz.
- Fast PWM: 250 000 / 256 = 976.6 Hz
- Phase-correct PWM: 250 000 / 510 = 490.2 Hz
These are the numbers behind "490 Hz" and "980 Hz" in the Arduino reference.
The general formulas are:
- Fast PWM, TOP = 255: f = 16 000 000 / (prescaler × 256)
- Phase-correct PWM, TOP = 255: f = 16 000 000 / (prescaler × 510)
Timer1 is 16-bit but the Arduino core runs it in an 8-bit phase-correct mode. That keeps analogWrite() consistent across pins, but it wastes the 16-bit range.
Choosing a different frequency
You change frequency by changing the prescaler or the counting mode. Both are controlled through timer registers. The prescaler is set by the three clock-select bits (CS22, CS21, CS20 for Timer2) in register TCCR2B.
For Timer2 the useful settings are:
| `CS22:0` value | Prescaler | Phase-correct frequency |
|---|---|---|
| 1 | 1 | 31 372 Hz |
| 2 | 8 | 3 921 Hz |
| 3 | 32 | 980 Hz |
| 4 | 64 (default) | 490 Hz |
| 5 | 128 | 245 Hz |
| 6 | 256 | 122 Hz |
| 7 | 1024 | 31 Hz |
Timer1 uses a different table. Its prescalers are 1, 8, 64, 256 and 1024, selected by values 1 to 5 in TCCR1B.
Example: moving pin 3 to about 31 kHz
This sketch changes only the low three bits of TCCR2B and leaves the rest alone. It then uses analogWrite() as usual.
const uint8_t PWM_PIN = 3; // Timer2, output OC2B
void setup() {
pinMode(PWM_PIN, OUTPUT);
// Keep the upper bits of TCCR2B, set CS22:0 = 001 (prescaler 1)
TCCR2B = (TCCR2B & 0b11111000) | 0x01;
analogWrite(PWM_PIN, 64); // about 25 percent duty at about 31 kHz
}
void loop() {
}The duty cycle still follows analogWrite()'s 0 to 255 scale. Only the period changes. At 31 kHz the period is about 32 µs, which is above the range of human hearing. A small motor on a MOSFET driver will stop whining.
To check the result, measure the pin with an oscilloscope or a logic analyzer. A multimeter in frequency mode may also work for a rough check.
Taking control of the period: custom TOP
Prescalers give only a few fixed frequencies. For an exact value you can choose the number the counter counts to (called TOP). Timer2 supports a fast PWM mode where TOP is stored in OCR2A. The frequency becomes:
f = 16 000 000 / (prescaler × (TOP + 1))
The duty cycle resolution becomes TOP + 1 steps instead of 256.
const uint8_t PWM_PIN = 3; // OC2B
void setup() {
pinMode(PWM_PIN, OUTPUT);
// Fast PWM, TOP = OCR2A (WGM22:0 = 111), clear OC2B on compare match
TCCR2A = _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS22); // prescaler 64
OCR2A = 99; // TOP: 16 MHz / (64 * 100) = 2500 Hz
OCR2B = 49; // duty = (49 + 1) / (99 + 1) = 50 percent
}
void loop() {
}This sketch does not use analogWrite(). It writes the registers directly, so analogWrite(3, x) after this would reset the timer's mode and configuration. The output is a 2500 Hz square wave with 100 steps of duty resolution.
In this mode OCR2A holds the period, so pin 11 (the OC2A output) can no longer carry an independent PWM signal. Only pin 3 is usable for PWM.
The trade-off: frequency against resolution
For a fixed clock and prescaler, a timer counting to a bigger TOP gives more duty steps but a lower frequency. A timer counting to a smaller TOP gives a faster signal with coarser steps.
| Prescaler | TOP | Steps | Frequency |
|---|---|---|---|
| 1 | 255 | 256 | 62 500 Hz (fast PWM) |
| 1 | 99 | 100 | 160 000 Hz |
| 64 | 255 | 256 | 976 Hz |
| 64 | 99 | 100 | 2 500 Hz |
With a 16 MHz clock, the product of frequency and steps is limited to 16 000 000 divided by the prescaler. To get 8-bit resolution at 62.5 kHz you need prescaler 1, and phase-correct mode would halve that. With the 16-bit Timer1 you can reach 16-bit resolution at about 244 Hz, or 10-bit resolution at about 15.6 kHz.
Common problems
- Pin 5 and 6 behave differently. They run twice as fast as the other PWM pins, and in fast PWM mode the lowest duty values cannot reach true zero except through the special-case handling in
analogWrite(pin, 0). Expect a slightly higher minimum brightness on these pins than on the others. - Libraries collide.
Servotakes Timer1 on the Uno and disablesanalogWrite()on pins 9 and 10.tone()uses Timer2 and disrupts PWM on pins 3 and 11. If two parts of a sketch need the same timer, move one of them to a pin on a different timer. - Register edits get overwritten.
analogWrite()configures the timer on first use of a pin. Call it before your register edits, or avoid it on that pin altogether. - High frequency is not always better. Each switching edge in a MOSFET circuit loses a little energy, and a long wire to the load can radiate noise at high frequency. Pick the lowest frequency that avoids visible flicker and audible noise.
- Do not assume the number is exact. The real frequency depends on the clock, and a ceramic resonator drifts. For timing that matters, measure.
Summary of the working model
- A timer counts clock ticks and compares its counter to a stored value.
- The pin changes state at compare matches and at the top or bottom of the count.
- The prescaler and counting mode set the frequency. The compare value sets the duty cycle.
- The timers have other jobs, so a change for PWM can affect
millis(),tone()orServo.
Exercise
You set Timer2 to fast PWM with TOP = 199 and prescaler 8 on a 16 MHz Uno. What PWM frequency do you get, and how many duty steps are available?
Show answer
f = 16 000 000 / (8 × (199 + 1)) = 16 000 000 / 1600 = 10 000 Hz. There are TOP + 1 = 200 duty steps.
Exercise
A sketch uses analogWrite(9, 128) for an LED and also uses the Servo library on pin 6. The LED stops responding to analogWrite(). Explain the cause and give one fix.
Show answer
On the Uno, the Servo library takes over Timer1, which drives pins 9 and 10, so analogWrite() no longer works there. Fix: move the LED to a pin on a different timer, such as 3, 5, 6 or 11.
Exercise
Why is it risky to change Timer0's prescaler to raise the frequency on pins 5 and 6?
Show answer
Timer0 also provides the time base for millis(), micros() and delay(). Changing its prescaler scales every time measurement and delay in the sketch by the same factor, so timing code gives wrong results.