With Timer1 you'll normally want to stop it, add in your reload value to the existing count (+ whatever time is involved for instructions after stopping it), then restart it. This can throw you off if you're not right on.
This could be a lot easier with Timer2 since it gets automatically reset - so you don't need to mess with reloading the timer.
Here's an example that keeps spot-on with my PC time clock to the second;
Code:
DEFINE OSC 4 ' using a 4MHz crystal
' setup vars for clock
Time VAR BYTE ' accumulates TMR2 to PR2 match counts
Minutes VAR BYTE ' minutes
Hours VAR BYTE ' hours
Seconds VAR BYTE
Match VAR PIR1.1 ' TMR2 to PR2 match interrupt flag bit
CMCON = 7 ' disable comparators
INTCON = 0 ' not using interupts. Just monitoring int flag bits
Time = 0 ' clear TMR2 to PR2 match counter
Hours = 11 ' set clock starting hour here
Minutes = 52 ' set clock starting minutes here
Seconds = 0
PR2 = 249 ' 249 +1 extra cycle for TMR2 reset = 250*5*16*1uS=20mS
Match = 0 ' clear match flag
' setup & start TMR2
T2CON = %00100110 ' 1:5 postscale, 1:16 prescale, TMR2 on
Main:
' every 20mS the TMR2IF flag is set, and this routine is entered.
' Plenty of time to do other stuff.
IF Match THEN ' has TMR2 matched PR2? (should happen every 20mS)
Match = 0 ' yes. clear TMR2 to PR2 match flag bit
Time = Time + 1 ' increment 20mS count
IF Time = 50 THEN ' 50 x 20mS = 1 second
Time = 0 ' show time in 1 second intervals
HSEROUT ["Time = ", DEC2 Hours,":",DEC2 Minutes,":",DEC2 Seconds,13,10]
Seconds = Seconds + 1
ENDIF
IF Seconds = 60 THEN ' has 60 seconds passed?
Seconds = 0
Minutes = Minutes + 1 ' increment minute count
IF Minutes = 60 THEN ' have 60 minutes passed?
Minutes = 0 ' yes. roll-over minutes 00
Hours = Hours + 1 ' update hours
IF Hours = 24 THEN Hours = 0 ' roll-over hours from 24 to 00
ENDIF ' end IF Minutes = 60
ENDIF ' end IF Seconds = 60
ENDIF ' end IF Match
GOTO Main
END
Of course you'll want a 4MHz osc that's right on the money if you need really precise timing.
Bookmarks