Saturday 29 November 2008

Timers on the PIC mcu's

Here is how to work with timers:

1) The timer/counter counts once per microcontroller instruction
2) When the counter reaches it's max value, it overflows (starts at 0) and triggers an interrupt, which we can react to in our program.
3) One microcontroller instruction is 4 clock cycles long, which means that a clock frequency of 8MHz gives 2000000 counter ticks per second.
4) an 8 bit counter can tick 256 times before triggering an interrupt, a 16 bit counter ticks 65536 times. The maximum interval for a 16 bit counter is thus 65536 * (1s/2000000) = 0.032768 seconds.
5) To increase the interval, a prescaler can be added. A prescaler divides the instruction frequency. prescalers on the P18F458 comes in exponential values from 1 to 256.
6) A prescaler of 256 gives an instruction frequency of 2000000/256 = 7812.5
7) The maximum interval for such a timer is thus 65536 * (1s/7812.5) = 8.388608
8) To set the timer to overflow at a given time, we have to set the start value for the timer to a precalculated number. Ex: We want an interrupt interval of 10ms. For this, we can select a prescaler value of 4, which gives us 500 000 timer ticks per second. Without setting the timer start value, the timer will overflow after 13.1072 ms. As we know that one tick equals 1/500000s, we need to divide 0.031072 s by 1s/500000 to get the number of unnecessary ticks = 15536 (well, this was of course quite obvious, but for the sake of the example). We thus need to start the timer at 15536 to make it tick 50000 before overflowing and generating an interrupt.

Easy, right? :-D

No comments: