Tuesday, September 7, 2010

PIC16F887/877 programming in C Tutorial 4 (Counter)

Counter:
Timer 0 and Timer 1 can be used as counter, as well. The only difference is Timer0 can count till 256 where as Timer1 till 65536; as Timer0 is 8-bit and Timer1 is 16-bit.

To use Timer 1 in counter just set the TMRCS (Timer1 Clock Source Select) bit, of T1CON reg. It will count when the signal is applied at T1CK1 pin, RC0. 
Where as, if you want to use Timer0; then set the T0CS (TMR0 Clock Source Select) bit of option reg. It will count when the signal is applied at T0CK1 pin, RA4. You can also select the edge, rising or falling, to trigger your counter by T0SE bit.

Code: 
Now lets write a code that will count till 65536 and display its count on LEDs attached to portD & portB;

void main() {
     //using 4MHz ext xtal
     trisd=0;
     portd=0;
     trisb=0;
     portb=0;

//////////////////////comment for 877 //////////////////////////
     ansel=0;
     anselh=0;
     c1on_bit=0;
     c2on_bit=0;
/////////////////////////////////////////////////////////////

     tmr1l=0;
     tmr1h=0;
     t1con=3;
     while(1){
          if(!tmr1if_bit) {             
              portd=tmr1l;
              portb=tmr1h;
          }
          tmr1if_bit=0;

     }
  }

Schematic:

No comments:

Post a Comment