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.

In shortTimer0, 1 and 2 generate time bases, PWM and periodic interrupts.

Theory in plain words

CTC interrupt every 1 msF_CPU 16 MHzprescaler 64: 250 kHzOCR0A = 249interrupt every 1 ms
CTC interrupt every 1 ms

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

Find prescaler and OCR for a target frequencyTry it Yourself

Try 1000 Hz at 16 MHz with the 8 bit timer: prescaler 64 and OCR 249 gives exactly 1 ms.

1 ms tick and millis() style counter
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 modeFrequencyUse
Fast PWM 8 bitF_CPU / (prescaler x 256)LED dimming, motors
Phase correctF_CPU / (prescaler x 510)servo and motor drivers, less noise
Timer1 16 bit with ICR1anyservo 50 Hz, audio

Quick quiz

1. CTC mode means...

2. For 1 kHz at 16 MHz with an 8 bit timer, prescaler 64 gives OCR...