English
Language : 

PIC18F1220_07 Datasheet, PDF (109/308 Pages) Microchip Technology – 18/20/28-Pin High-Performance, Enhanced Flash Microcontrollers with 10-bit A/D and nanoWatt Technology
PIC18F1220/1320
12.7 Using Timer1 as a
Real-Time Clock
Adding an external LP oscillator to Timer1 (such as the
one described in Section 12.2 “Timer1 Oscillator”,
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
Example 12-1, demonstrates a simple method to
increment a counter at one-second intervals using an
Interrupt Service Routine. Incrementing the TMR1 reg-
ister 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 as the previous counter overflow.
Since the register pair is 16 bits wide, counting up to
overflow the register directly from a 32.768 kHz clock
would take 2 seconds. To force the overflow at the
required one-second intervals, it is necessary to pre-
load it; the simplest method is to set the MSb of TMR1H
with a BSF instruction. 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 12-1: IMPLEMENTING A REAL-TIME CLOCK USING A TIMER1 INTERRUPT SERVICE
RTCinit
RTCisr
MOVLW
MOVWF
CLRF
MOVLW
MOVWF
CLRF
CLRF
MOVLW
MOVWF
BSF
RETURN
0x80
TMR1H
TMR1L
b’00001111’
T1OSC
secs
mins
.12
hours
PIE1, TMR1IE
BSF
BCF
INCF
MOVLW
CPFSGT
RETURN
CLRF
INCF
MOVLW
CPFSGT
RETURN
CLRF
INCF
MOVLW
CPFSGT
RETURN
MOVLW
MOVWF
RETURN
TMR1H, 7
PIR1, TMR1IF
secs, F
.59
secs
secs
mins, F
.59
mins
mins
hours, F
.23
hours
.01
hours
; Preload TMR1 register pair
; for 1 second overflow
; Configure for external clock,
; Asynchronous operation, external oscillator
; Initialize timekeeping registers
;
; Enable Timer1 interrupt
; Preload for 1 sec overflow
; Clear interrupt flag
; Increment seconds
; 60 seconds elapsed?
; No, done
; Clear seconds
; Increment minutes
; 60 minutes elapsed?
; No, done
; clear minutes
; Increment hours
; 24 hours elapsed?
; No, done
; Reset hours to 1
; Done
© 2007 Microchip Technology Inc.
DS39605F-page 107