Monday, September 6, 2010

PIC16F887/877 programming in C Tutorial 3-3 (Timer 2)

Timer 2:
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.

Prescaler and Postscaler - Timer2 is an 8-bit timer with a prescaler and a postscaler. Each allows to make additional division of the frequency clock source.
Prescaler divides the frequency clock source BEFORE the counting take place at the register TMR2, thus the counting inside the TMR2 register is performed based on the divided frequency clock source by the Prescaler.
Postscaler divides the frequency that comes out of the Comparator.
T2CON Register:

How to calculate the required values of the TIMER2: TIMER2 FORMULA
Fout – The output frequency after the division.
Tout – The Cycle Time after the division.
4 - The division of the original clock by 4, when using internal crystal as clock (and not external oscillator).
Count - A numeric value to be placed to obtain the desired output frequency - fout.
(PR2 – TMR2) - The number of times the counter will count.

Code
Lets write the code to toggle the bits of portc after 2 sec;

void main() {
     // using 4MHz ext xtal
     int count=0;
     trisc=0;
     portc=255;
/////////////////// comment this block if you are using 877///////////
     ansel=0;
     anselh=0;
     c1on_bit=0;
     c2on_bit=0;
////////////////////////////////////////////
    
     t2con=124;         //prescaler is 16
     pr2=255;            //final value to count
     tmr2=0;              //initial value

     while(1){
        while(!tmr2if_bit);        //tmr2 flag bit
        tmr2if_bit=0;
        cnt++;


     if(cnt==488){                //for 2 sec(16*256u*488=2sec)
         portc=~portc;
         cnt=0;
         }

  }   
}


Schematic:
Timer 0 schematic can be used (tutorial 3 part 1). 

2 comments:

  1. What is the actual difference between a pre-scaler & a post-scaler? any advantage of either? please explain with examples if possible.

    ReplyDelete
    Replies
    1. As mentioned above "Prescaler divides the frequency clock source BEFORE the counting take place at the register TMR2.
      Postscaler divides the frequency that comes out of the Comparator."

      Delete