Timer interrupts

Hi,

I'm just trying to understand the way that the Arduino (and ATmega) handles timer interrupts, with a view to using one in a project in the near future. I have been looking at the Timer1 library, cross-referencing to the ATMega168/328P data-sheet, in order to get an understanding of a working example.

However, I've come across something where I can't get the same results as are given on the Timer1 page on the playground Arduino Playground - HomePage. When I calculate the maximum period for any value of the prescaler, I always get half the value given on this wiki page.

The formula the author has stated for obtaining the maximum period is

Max Period = (Prescale)(1/Frequency)(2^17)

  • why is this 2^17? From my understanding Timer1 is a 16-bit timer and therefore there would be a maximum value for the register of 2^16 - 1, thus causing overflow (and so, the timer interrupt to trigger) at 2^16.

Am I missing something here?

Yes, you are missing an understanding of the phase-correct PWM modes, where the counter counts down to BOTTOM, then counts up to TOP, then counts down to BOTTOM etc etc. Thus the period is 2 x (2^16 - 1), which is approx 2^17.

So, if I understand what you are saying, for the 'normal', 'CTC' and 'Fast PWM' modes, my calculation is correct - there is a maximum period of 2^16 clock ticks, since in these modes the timer only counts up. It is only for the 'phase correct' and 'phase and frequency correct' PWM modes that the period is doubled.

Is this right?

Yes, precisely.