Datasheet
PICkit™ 3 Debug Express Lessons
© 2009 Microchip Technology Inc. DS41370C-page 33
3.5 LESSON 5: USING TIMER0
Timer0 is used to time delays while rotating the demo board LEDs, instead of using
program loop delays. The demo board switch reverses the direction of the rotation.
3.5.1 The PIC18F45K20 Timer0 Module
The Timer0 module is the timer/counter peripheral of the PIC18FXXXX microcontroller
that may be used to count oscillator clock cycles or external events on the T0CKI pin.
It can be configured as an 8-bit or 16-bit timer, which means it can count from 0 to 255
or 0 to 65535. A bit flag is set when the counter rolls over from the maximum value back
to zero.
The Timer0 module also includes an optional prescaler, which may be configured to
divide the timer clock source before it reaches the timer/counter itself. For example,
with a 1:1 prescaler, the timer would increment once every instruction clock cycle.
(Remember that the instruction clock cycle TCY is the F
OSC oscillator clock/4.) With a
1:8 prescaler, the timer would increment once every eight clock cycles. The prescaler
is cleared on every write to the timer.
FIGURE 3-24: SIMPLIFIED 16-BIT TIMER0 BLOCK DIAGRAM
When Timer0 is configured as a 16-bit timer, care must be taken when reading and
writing the timer value. The lower byte of the timer is directly readable and writable as
the SFR TMR0L. However, the high byte is not directly accessible. Instead, it is
buffered through the SFR TMR0H. TMR0H is updated with the value of timer high byte
when TMR0L is read. A write of TMR0L also writes the contents of TMR0H to the
Timer0 high byte. This allows the entire 16-bit timer to be read or written at once.
Therefore, to read the timer, always read TMR0L first, then TMR0H. To write the timer,
always write TMR0H first then TMR0L.
Timer0 operation is controlled by the T0CON SFR, shown in Figure 3-24.
Key Concepts
- Timer0 is hardware counter implemented in the microcontroller that can
count clock cycles or external events.
- Using a timer instead of processor delay loops frees up the processor to do
useful work instead of counting cycles.
- A timer “prescaler” sets the number of clock cycles or events required to
increment the timer by 1, allowing it to be run faster or slower off the same
frequency clock.
TCY (Fosc / 4)
or T0 CKI Pin
Prescaler TMR0L
TMR0H
TMR0
High Byte
INTCON
TMR0IF Bit
Prescaler may be set to
divide by 2, 4, 8, 16, 32,
64, 128, or 256.
Timer high byte is buffered into TMR0H on a read of TMR0L.
TMR0H is written to timer high byte on TMR0L write.
Flag bit set when TMR0
overflows, and must be
cleared in software.