With an 8MHz osc, Timer1 will increment by 1 every 500nS with a prescaler
of 1:1.
It's a 16-bit timer so it can count from 0 to $FFFF or 0 to 65,535. Once it
reaches 65,535 and rolls-over back to 0, it will generate the interrupt if the
interrupt is enabled.
That means you have 65,536 Timer1 ticks before roll-over. 65,536 * 500nS
= 32.768mS before each Timer1 interrupt.
1 second/32.768mS = 30.517. Once Timer1 has over-flowed 30 times, you
know a 30 * 32.768mS (0.98304 seconds) period has expired.
If 0.98304 seconds is close enough to your "approximate" period of 1 second,
then you could do something simple like this;
Setup Timer1 with a 1:1 prescaler, clear Timer1, start the timer. Then count
each over-flow by monitoring the Timer1 interrupt flag bit. PIR1.0.
Just monitor PIR1.0. Once this flag bit is set, clear it, then increment your
variable;
Code:
IF PIR1.0 THEN
PIR1.0 = 0
MyVar = MyVar+1
ENDIF
If MyVar = 30 & no serial data has been received from your external device,
then reset the external device.
If the external device responds before MyVar = 30, then reset MyVar to 0 to
restart your countdown.
You can do this without interrupts by just watching the Timer1 interrupt flag
bit. This flag bit is automatically set each time Timer1 rolls-over, whether you
have the Timer1 interrupt enabled or not.
If you need more time, then just use the prescaler.
Example: Setup Timer1 prescaler to 1:8. This gives you 8 * 65,536 * 500nS
(8 * 32.768mS) for 0.262144 seconds before the flag bit is set. You would
then only need to increment your variable to 4 (4 * 0.262144 = 1.048576
seconds) for your approximate 1 second period.
You only need a 1 byte variable for the over-flow counter, your program
never gets interrupted while it's doing other things, and you'll be darn close
to your 1 second period before resetting the external device.
If you need better precision, you can let the timer free run and roll-over x
number of times until the roll-over count is just short of your required time
period.
After x number of roll-overs, stop the timer, and load it with a value that will
cause the last roll-over at the remaining time required for your 1 second
period.
Bookmarks