
2010 Microchip Technology Inc.
Preliminary
DS41350E-page 109
PIC18F/LF1XK50
11.6
Using Timer1 as a Real-Time Clock
Adding an external LP oscillator to Timer1 (such as the
above) gives users the option to include RTC function-
ality to their applications. This is accomplished with an
inexpensive watch crystal to provide an accurate time
base and several lines of application code to calculate
the time. When operating in Sleep mode and using a
battery or supercapacitor as a power source, it can
completely eliminate the need for a separate RTC
device and battery backup.
The application code routine, RTCisr, shown in
increment a counter at one-second intervals using an
Interrupt Service Routine. Incrementing the TMR1
register pair to overflow triggers the interrupt and calls
the routine, which increments the seconds counter by
one; additional counters for minutes and hours are
incremented on overflows of the less significant
counters.
Since the register pair is 16 bits wide, a 32.768 kHz
clock source will take 2 seconds to count up to over-
flow. To force the overflow at the required one-second
intervals, it is necessary to preload it; the simplest
method is to set the MSb of TMR1H with a BSF instruc-
tion. Note that the TMR1L register is never preloaded
or altered; doing so may introduce cumulative error
over many cycles.
For this method to be accurate, Timer1 must operate in
Asynchronous mode and the Timer1 overflow interrupt
must be enabled (PIE1<0> = 1), as shown in the
routine, RTCinit. The Timer1 oscillator must also be
enabled and running at all times.
EXAMPLE 11-1:
IMPLEMENTING A REAL-TIME CLOCK USING A TIMER1 INTERRUPT SERVICE
RTCinit
MOVLW
80h
; Preload TMR1 register pair
MOVWF
TMR1H
; for 1 second overflow
CLRF
TMR1L
MOVLW
b’00001111’
; Configure for external clock,
MOVWF
T1CON
; Asynchronous operation, external oscillator
CLRF
secs
; Initialize timekeeping registers
CLRF
mins
;
MOVLW
.12
MOVWF
hours
BSF
PIE1, TMR1IE
; Enable Timer1 interrupt
RETURN
RTCisr
BSF
TMR1H, 7
; Preload for 1 sec overflow
BCF
PIR1, TMR1IF
; Clear interrupt flag
INCF
secs, F
; Increment seconds
MOVLW
.59
; 60 seconds elapsed?
CPFSGT
secs
RETURN
; No, done
CLRF
secs
; Clear seconds
INCF
mins, F
; Increment minutes
MOVLW
.59
; 60 minutes elapsed?
CPFSGT
mins
RETURN
; No, done
CLRF
mins
; clear minutes
INCF
hours, F
; Increment hours
MOVLW
.23
; 24 hours elapsed?
CPFSGT
hours
RETURN
; No, done
CLRF
hours
; Reset hours
RETURN
; Done