CONFIDENTLY USING INTERRUPTS IN YOUR MICROCONTROLLER PROJECT
for the PIC16F84, we know that Timer0 — which is used to
generate interrupts — increments once every instruction cycle
(not using the prescaler). Also from the data sheet, we know
that there is one instruction cycle for every four clock cycles,
giving us an instruction cycle frequency of 2.5 MHz ( 10 MHz /
4 = 2.5 MHz). We now divide this by our desired interrupt frequency of 51,000 and we get 49.02 (2,500,000 / 51,000 =
49.02). Since we need an integer number of timer increments
per interrupt, we round this to 49. So, the timer will increment
49 times from one interrupt to the next.
Now, the next fact we need to
know is that Timer0 causes an interrupt
when it rolls over, when its value goes
from 255 to 0 (255 is the maximum
value for an eight-bit timer). From the
last step in our calculation, we know
that we want 49 increments between
interrupts to get our desired frequency.
So, if we subtract 49 from the timer’s
value during our interrupt, we know
that the next interrupt will occur 49
cycles later than this one. This is how
we set the interrupt frequency. If
we don’t change the timer’s value
during the interrupt, we will instead get
interrupts every 256 cycles when the
timer naturally rolls over.
Another thing to keep in mind is
that you might have to adjust the
value you subtract from the timer
because you lose a few cycles doing
the subtraction. This is because the
timer value will continue to increment
while you are doing the subtraction.
For instance, if reading the timer,
subtracting, and writing the timer
again takes three cycles, you will want
to actually subtract 46 from the timer
instead of 49. Otherwise, your interrupt frequency will be slightly off.
An alternate way to set the interrupt frequency is to load a constant
value into the timer at the beginning
of each interrupt. This method uses
fewer instructions to set the timer, but
is less accurate because it doesn’t
take into account the interrupt latency.
The interrupt latency is the few
instruction cycles it takes between the
timer rolling over and the first instruction of your interrupt service routine.
The interrupt latency varies for different
microcontrollers and can also vary
slightly from interrupt to interrupt,
depending on the microcontroller.
When the latency varies slightly, so
will your interrupt frequency.
If we were to use this method in our example, what value
would we need to load into the timer at the beginning of our
interrupt so that — 49 cycles later — the timer will roll over? We
subtract 49 from 256 (the timer rolls over one cycle after it
reaches 255) and get an answer of 207. So, if we load a value
of 207 into the timer at the beginning of our interrupt, the next
interrupt will happen when the timer rolls over 49 cycles later.
If you really need to make your interrupt routine short, this
can be a good alternate way to set the interrupt rate.
Circle #95 on the Reader Service Card.