Tuesday, January 13, 2015

PIC Microcontroller Timer2 Module

PIC16F877A Microcontroller Timer2 Module
The following tow topics shows how to use Timer0 and Timer1 modules of PIC16F877A, now we will complete this tutorial by talking about Timer2 module.

 PIC16F877A Microcontroller Timer0 module

 PIC16F877A Microcontroller Timer1 Module

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.
Timer2 Example:
Let's make our timer interrupts 50 times to make a delay of 1 s an led of the previous example, so every timer1 should interrupt every 20 ms.
Prescaler= 1:16, postscaler = 1:15, Timer2 preload = 250.
MikroC Code:

unsigned char i;
 void Interrupt(){
      if (TMR2IF_bit){
           PORTB.F1 = ~PORTB.F1;}
      TMR2IF_bit = 0; }
 void main() {
 T2CON  = 0x76;         //Timer2 postscaler 1:15, prescaler 1:16
  PR2   = 250;          //Timer2 preload
  TMR2IE_bit = 1;       //Enable timer2 module
  INTCON  = 0xC0;       //Enable interruptes
 TRISB.F1 = 0;          //Configure PORTB.F1 as output
 PORTB.F1 = 0;
 while(1);              //Endless loop

  Informations are from PIC16F877A datasheet.