Home / Learn Chip Programming / AVR Timers: CTC, PWM and millis
AVR Timers: CTC, PWM and millis
Timer0, 1 and 2 generate time bases, PWM and periodic interrupts.
Theory in plain words
What it is
A timer counts clock ticks (optionally divided by a prescaler). CTC mode resets at a compare value to make exact periods. PWM modes drive pins with a duty cycle.
Why we use it
Precise timing without busy-wait, LED dimming, servo control and tone generation all use timers.
How it works
Choose prescaler and compare value: f_out = F_CPU / (2 x prescaler x (OCR + 1)) for toggle, or interrupt rate = F_CPU / (prescaler x (OCR + 1)).
Where it is used
- millis() (Timer0)
- Servo.h (Timer1)
- tone() (Timer2)
Timer calculator
Try 1000 Hz at 16 MHz with the 8 bit timer: prescaler 64 and OCR 249 gives exactly 1 ms.
volatile uint32_t ms;
ISR(TIMER0_COMPA_vect) { ms++; }
uint32_t millis_safe(void) { uint8_t s = SREG; cli(); uint32_t m = ms; SREG = s; return m; } // atomic read| PWM mode | Frequency | Use |
|---|---|---|
| Fast PWM 8 bit | F_CPU / (prescaler x 256) | LED dimming, motors |
| Phase correct | F_CPU / (prescaler x 510) | servo and motor drivers, less noise |
| Timer1 16 bit with ICR1 | any | servo 50 Hz, audio |
Quick quiz
1. CTC mode means...
The timer restarts at the compare value.
2. For 1 kHz at 16 MHz with an 8 bit timer, prescaler 64 gives OCR...
16 000 000 / 64 / 1000 - 1 = 249.