Datasheet

PICkit™ 3 Debug Express Lessons
© 2009 Microchip Technology Inc. DS41370C-page 35
T0PS2:T0PS0 = 000
Since the prescaler is not assigned, these bits are “don’t care.”
And finally:
TMR0ON = 0
This bit turns the timer on and off. It’s set to zero now as the timer will be turned on
once it is has been set up.
To configure Timer0 with these settings, the binary value 0b0000100 is written to
T0CON.
The PIC18F45K20 has 3 other configurable timers: Timer1, Timer2 and Timer3. More
information on all four timer modules can be found in the PIC18F45K20 Data Sheet
(DS41303), Sections 11 through 14.
3.5.2 Exploring the Lesson 5 Source Code
Open the lesson source code file 05 Timer.c and header file 05 Timer.h in editor
windows if they are not open already.
Note that in 05 Timer.h two custom enumerated variable types have been defined:
typedef enum { LEFT2RIGHT, RIGHT2LEFT}
LEDDirections;
typedef enum {FALSE, TRUE} BOOL;
This allows us to declare variables using these types and initialize them in main():
LEDDirections Direction = LEFT2RIGHT;
BOOL SwitchPressed = FALSE;
The Direction variable keeps track of which direction the LEDs are rotating in, and
SwitchPressed remembers if the switch has been pressed or not, as the LED
rotation direction should only be changed once when it is pressed.
The following code before the while(1) loop sets up the Timer0 module as discussed
previously.
Using the line numbers in the comments as references, let’s discuss the function of
each line in setting up the timer.
Line 1 clears the TMR0IF flag in the INTCON SFR. This bit flag is set whenever the
timer overflows (rolls over), so the program will poll it to know when the LED rotation
delay is up. However, the flag will not reset by hardware, it must be reset in software
so the program makes sure it is clear before starting the timer.
Line 2 loads the settings into T0CON to configure the timer as discuss previously in this
lesson.
Line 3 clears the TMR0H buffer. Remember that TMR0H only buffers the high byte of
the timer. The ‘0’ value will not actually be written to the timer upper byte until TMR0L
is written.
Line 4 clears TMR0L, which also causes TMR0H to be written to the high byte of the
timer. Thus, the entire 16-bit timer is loaded with the hex value 0x0000.
// Init Timer
INTCONbits.TMR0IF = 0; // line 1
T0CON = 0b00001000; // line 2
// T0CON = 0b00000001; (ignore commented line for now)
TMR0H = 0; // line 3
TMR0L = 0; // line 4
T0CONbits.TMR0ON = 1; // line 5