Datasheet
PICkit™ 3 Debug Express
DS41370C-page 36 © 2009 Microchip Technology Inc.
Line 5 sets bit 7, TMR0ON, of the T0CON register to turn on the timer so it begins
incrementing. Using one of the SFR unions to access bits, like T0CONbits.TMR0ON,
can change bits without affecting the other bits.
In the while(1) loop, the LED_Display global variable is updated to rotate the ‘1’ bit
based on the Direction variable value, and then LATD is updated.
The do{…}while() loop then polls the switch looking for a switch press while it waits
for the timer to overflow and set the TMR0IF flag bit. This is a simplistic example of how
using a timer allows the microcontroller to do work while waiting on a time delay,
instead of wasting processing time counting cycles in an instruction loop.
Once the switch it pressed, the Direction variable value is reversed. Follow the
if – else if logic flow in the do{…}while() loop to see how once the switch is
pressed, the direction is reversed only once until it is released and pressed again.
Lastly, once Timer0 overflows and sets the TMR0IF flag the do{…}while() loop is
exited. TMR0IF is then cleared in the software program so the next timer overflow can
be detected.
3.5.3 Build and Program the Lesson 5 Code
Build and program the Lesson 5 project. The LEDs will rotate, and pressing the Demo
Board button will reverse them.
3.5.4 Assigning the Timer0 Prescaler
Now we’ll go back to that commented-out line of code in the Timer0 setup statements.
Comment out the T0CON assignment statement, and un-comment the other statement
so the Timer0 setup code looks like this:
INTCONbits.TMR0IF = 0;
//T0CON = 0b00001000;
T0CON = 0b00000001;
TMR0H = 0;
TMR0L = 0;
T0CONbits.TMR0ON = 1;
Take a look at what this changes:
PSA = 0
The prescaler is now assigned to Timer0, and the values of T0PSx will set the
prescaler clock divider ratio.
T0PS2:T0PS0 = 001
This value sets the prescale value to 1:4, which means Timer0 will now increment
once every 4 instruction cycles instead of once every instruction cycle. It now takes
4 times as long for it to count up to 65536 – just over 1 second!
Rebuild and reprogram the Lesson 5 project with change in the source code. The LEDs
will rotate more slowly, 4 times slower to be exact, than before.
Note: Be aware that some cases using an SFR union to access a bit may affect
other bits. What actually happens during this instruction execution is the
register is read, the bit is modified, and the entire register is re-written. This
operation is called Read-Modify-Write. If a bit reads a different value than
what it was last set as, this operation may affect register bits other than the
intended one. Check the SFR bit definitions carefully. In the case of
T0CON, all bits are Read/Write and all are set by software only; the hard-
ware will not affect any bit setting.