16F PIC TMR2 Example

Written With
Proton
Here's an extract from the 16F87XA datasheet;
Timer2 is an 8-bit timer with a prescaler and a postscaler. It
can be used as the PWM time base for the PWM mode of the CCP module(s). The TMR2
register is readable and writable and is cleared on any device Reset. The input
clock (FOSC/4) has a prescale option of 1:1, 1:4 or 1:16, selected by control
bits T2CKPS1:T2CKPS0 (T2CON<1:0>).
The Timer2 module has an 8-bit period register, PR2. Timer2
increments from 00h until it matches PR2 and then resets to 00h on the next
increment cycle. PR2 is a readable and writable register. The PR2 register is
initialized to FFh upon Reset.
The match output of TMR2 goes through a 4-bit postscaler (which
gives a 1:1 to 1:16 scaling inclusive) to generate a TMR2 interrupt (latched in
flag bit, TMR2IF (PIR1<1>)). Timer2 can be shut-off by clearing control bit,
TMR2ON (T2CON<2>), to minimize power consumption.
So basically the TMR2 has a 2 bit prescaler
and will continue to cycle until it equals the register PR2, at this stage an
overflow flag is triggered, and the interrupt will be called. Great for small
delays and PWM generation. Here's an example of how to set it up, the settings
for PR2 and prescalers were found
using the TMR2 calculator
Device = 16F877A
Xtal = 4
Dim uS as Word
Dim mS as Word
Dim S as Word
Symbol GIE = INTCON.7 ' Global Interrupt Enable Bit
Symbol TMR2_uS = 200 ' Set time period register of TMR2
Symbol TMR2_Enable = PIE1.1 ' TMR2 interrupt enable
Symbol TMR2_Overflow = PIR1.1 ' TMR2 overflow flag
Symbol TMR2_On = T2CON.2 ' Enables TMR2 to begin incrementing
ON_INTERRUPT Int_Sub
Goto Initialization
Int_Sub:
GIE = 0
If TMR2_Overflow = 1 And TMR2_Enable = 1 Then
TMR2_Overflow = 0
uS = uS + TMR2_uS
If uS >= 1000 Then
uS = uS - 1000
mS = mS + 1
If mS >= 1000 Then
mS = mS - 1000
S = S + 1
EndIf
EndIf
EndIf
GIE = 1
Context Restore
Initialization:
TMR2_Enable = 0
INTCON.6 = 1 ' Peripheral Interrupts
T2CON.0 = 0 ' 00 = Prescaler is 1
T2CON.1 = 0 ' 01 = Prescaler is 4
'1x = Prescaler is 16
PR2 = 199 ' TMR2 Period
T2CON.3 = 0 ' 0000 = 1:1 postscale
T2CON.4 = 0 ' 0001 = 1:2 postscale
T2CON.5 = 0 ' 0010 = 1:3 postscale
T2CON.6 = 0 ' 1111 = 1:16 postscale
TMR2 = 0 ' Reset TMR2 Value
TMR2_Enable = 1
TMR2_On = 1
GIE = 1
Main:
Repeat ' Create a loop
Until S = 60 ' that waits for 60 seconds
' 60 seconds has occurred
S = 0 ' Clear the seconds register
Goto Main ' Loop for ever

 | Site Tutorial Index |
|  | 16F PIC Examples |
| |  | Motors |
| |  | Thermometers |
| |  | Code Snippets |
| | |  | Internal Timers |
|  | 18F PIC Examples |
|  | Handy Tips |