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). 

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

Timer 1:
The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L) which are readable and writable. The TMR1 register pair (TMR1H:TMR1L) increments from 0000h to FFFFh and rolls over to 0000h.

Timer1 can be enabled/disabled by setting/clearing control bit, TMR1ON (T1CON<0>). The TMR1CS bit of the T1CON register is used to select the clock source. When TMR1CS = 0, the clock source is FOSC/4. When TMR1CS = 1, the clock source is supplied externally.

The TMR1 interrupt, if enabled, is generated on overflow which is latched in interrupt flag bit, TMR1IF (PIR1<0>). This interrupt can be enabled/disabled by setting/clearing TMR1 interrupt enable bit, TMR1IE (PIE1<0>). 

TMR1IF – TMR1 overflow Interrupt Flag bit.
This flag marks the end of ONE cycle count. The flag need to be reset in the software if you want to do another cycle count. We can read the value of the register TMR1 and write into. We can reset its value at any given moment (write) or we can check if there is a certain numeric value that we need (read).  

Timer1 has four prescaler options allowing 1, 2, 4 or 8 divisions of the clock input. The T1CKPS bits of the T1CON register control the prescale counter. The prescale counter is not directly readable or writable; however, the prescaler counter is cleared upon a write to TMR1H or TMR1L.

T1CON Register;
We perform all the necessary settings with T1CON register. As we can see, the size of the register is 8 bits. Let’s explore the relevant bits:
Where as T1CON of 887 also have bit 6 & 7;
bit 7               T1GINV: Timer1 Gate Invert bit(1)
                      1 = Timer1 gate is active-high (Timer1 counts when gate is high)
                      0 = Timer1 gate is active-low (Timer1 counts when gate is low)

bit 6             TMR1GE: Timer1 Gate Enable bit(2)
                     If TMR1ON = 0:
                     This bit is ignored

                     If TMR1ON = 1:
                     1 = Timer1 counting is controlled by the Timer1 Gate function
                     0 = Timer1 is always counting

Calculating Count, Fout, and Timer1 values

If using INTERNAL crystal as clock, the division is performed as follow:
TIMER1 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.
(65536 - TMR1) - The number of times in the timer will count based on the register TMR1.

Code:
Now lets write the code to toggle the bits of portc after 1 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;
 ///////////////////////////////////////////////////////
     
     t1con=1;             //tmr1on bit is set
     tmr1h=0;           //begin with 0
     tmr1l=0;
   
     while(1){
        while(!tmr1if_bit);        //tmr1 flag bit
        tmr1if_bit=0;
        count++;
         
         
     if(count==16){               //for 1 sec delay
         portc=~portc;             //16*65535us=1sec
         count=0;
         }

  }
}

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

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

Timers
Both PIC16f887 and 877 have three timers; timer 0, timer 1, and timer 2. Timer 0 is 8-bit and can also be use as counter, Timer 1 is 16-bit timer as well as a counter, where as Timer 2 is 8-bit timer and can be used as the PWM time base for the PWM mode of the CCP module(s). 

Timer 0:
The Timer0 module timer/counter has the following features:
  • 8-bit timer/counter
  • Readable and writable
  • 8-bit software programmable prescaler
  • Internal or external clock select
  • Interrupt on overflow from FFh to 00h
  • Edge select (rising or falling) for external clock
Timer mode is selected by clearing bit T0CS (OPTION_REG<5>). In Timer mode, the Timer0 module will increment every instruction cycle (without prescaler).

Counter mode is selected by setting bit T0CS (OPTION_REG<5>). In Counter mode, Timer0 will increment either on every rising or falling edge of pin RA4/T0CKI. The incrementing edge is determined by the Timer0 Source Edge Select bit, T0SE
(OPTION_REG<4>). Clearing bit T0SE selects the rising edge.

Timer0 has a register called TMR0 Register, which is 8 bits of size. We can write the desired value into the register which will be increment as the program progresses. Frequency varies depending on the Prescaler. Maximum value that can be assigned to this register is 255.

TMR0IF - TMR0 Overflow Interrupt Flag bit.
The TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h. This overflow sets bit TMR0IF (INTCON<2>).

Prescaler - Frequency divider.
We can use prescaler to further divide the clock frequency, the options ere: 
      PS2:PS0             TMR0 rate
         000                       1:2
         001                       1:4
         010                       1:8

         011                       1:16
         100                       1:32

         101                       1:64
         110                       1:128

         111                       1:256


Option Register:
Option reg is a 8-bit register used to initialize the timer0.

Calculating Count, Fout, and TMR0 values:

If using INTERNAL crystal as clock, the division is performed as follow: 

TIMER0 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.

(256 - TMR0) - The number of times in the timer will count based on the register TMR0.

 If using EXTERNAL clock source (oscillator), the division is performed as follow:

TIMER0 formula

In this case there is no division by 4 of the original clock. We use the external frequency as it is.


Code:
Now lets write the code for 0.5 sec delay;


void main() {
   // using 4MHz ext xtal
     int count=0;
     trisc=0;
     portc=255;
     tmr0=0;

 ///////////////// comment 4 pic16f877/////////
     ansel=0;
     anselh=0;
    
     c1on_bit=0;
     c2on_bit=0;
////////////////////////////////////////////


     t0se_bit=0;          //  low to high edge trigger
     t0cs_bit=0;          // using internal clk
     psa_bit=0;            //using prescaler
     ps0_bit=1;            //prescaler 256
     ps1_bit=1;
     ps2_bit=1;

    while(1){


        while(!tmr0if_bit);
        tmr0if_bit=0;
        cunt++;


     if(cunt==8){                       //delay 0.5 sec(256*256u*8)
         portc=~portc;
         cunt=0;
     }
 }
}


Schematic:

Friday, September 3, 2010

PIC16F887/877 programming in C Tutorial 2 (S.S Display Interfacing)

Interfacing Seven Segment (c.c) Display

In this tutorial i will show you how to interface S.S display with PIC16F887/877. For this we required 74hc573 latches, 74hc238 decoder, and 74ls48 bcd2dec converter.

Latches are used to enable/disable the S.S, 74hc234 a 3x8 decoder selects the appropriate latch to be enable/disable. 74ls48 just converts the bcd input to respective decimal output to operate S.S properly. 

Now lets write a small program that display the digital manual input at S.S, enter by the user; by using 8-way dip switch.

Code:   
void main() {

     int x,y,i,j;
     trisc=0;
     portc=0;
     trisd=255;      //all bits for input

 ///////////////// comment 4 pic16f877/////////
     ansel=0;
     anselh=0;
    
     c1on_bit=0;
     c2on_bit=0;
////////////////////////////////////////////

     while(1){
       j=0;
       i=3;
       x=portd;

       while(i>0){
          y=x%10;
          y=y|j;
          delay_ms(100);
          portc=y;
          x=x/10;
          i--;
          j=j+16;

     }

  }
}

Now come towards the code; portc is utilized for o/p, and manual i/p is applied at portd, here. As the ports are 8-bit so, maximum i/p would be 255(0-255); we have to display them on three S.S, for this we have to separate the digits of i/p. Modulus '%'  do this job; let say the i/p is 255, then first we have to display 5 then 5 and then 2; to do this we use x%10. Where x is an integer that has the manual i/p. Where modulus operator returns the remainder of integer division, so after this we have 5 stored in y (as 255%10 = 5, remainder is 5).

After getting the digit, it should be display on 3rd S.S; so to select this latch just or '|' y with proper integer, which in this case is 0 (as my 3rd S.S as attached to 0 o/p of latch, 2nd is to 1st and so on). So, after doing this we have 5 in 8-bit and latch 0 is selected. Now display it by assigning it to port.

To display 2nd digit first reduce the i/p by dividing it with 10; 255/10 gives 25, as we are storing this value in an integer; so x is equal to 25, now. J is incremented by 16 because we have to select the first latch (see the diagram for more detail).



In the same fashion, to display the first digit; select proper latch, divide and take modulus and display it, that is it. Here i is used to run this process for three times (means to display all the i/p digit on three S.S).


Schematic:   
For reset circuitry  please refer to first tutorial.
connection diagram

Thursday, September 2, 2010

PIC16F887/877 programming in C Tutorial 1 (Getting Started)

PIC16F887 and PIC16F877 are the members of PIC16F88X and PIC16F87X families respectively. PIC16F887 is the new version launched by microchip to take place of PIC16F877.For detail information please refer to their datasheets.

In this tutorial i will show you how to program PIC16F887/877 in C.
So first of all download mikroc pro for pic compiler also download its user manual. After this create a new project choose P16F887 or 877 whatever you have, and 4MHz crystal etc. If you dont know how to create a new project refer to its manual or download document 'how to create first project' from its site.

Note that i will use PIC16F887 and 4MHz external crystal (although PIC16F887 also have internal crystal) you can use 8MHz and what so ever. For 4MHz oscillator setting should be XT where as for 8MHz or above it should be HS (see fig below).

Lets start with a simple program 'LED Chaser', before we start this lets check out the PIC16F887 pin out.
pinout of pic16f887
As you can see there are five multiplex i/o ports, in PIC16F887, from portA to portE. For our first program we need only one port let say portD and 5v at pins 11 & 32, ground pins 12 & 31, 4MHz xtal at pins 13 & 14. Dont be panic to see more than one name of pins, i will tell you the pin functions when we use them.

After creating the project just write the below code in mikroc ide and build it(CTRL + F9), if you want to change the project setting, fuse bits, clock etc,  goto>>project>>edit project.

Code:
void main() {
        int x[]={1,2,4,8,16,32,64,128,256};  // int array
        int i;
        portc=0;      //to clear port
        trisc=0;        //as output

///////////////////// comment this block if you are using pic16f877a/////////
        ANSEL  = 0;                        // Configure AN pins as digital I/O
        ANSELH = 0;
       
        C1ON_bit = 0;                      // Disable comparators
        C2ON_bit = 0;
 ////////////////////////////////////////////////////////////////////

 while(1){
  
      for(i=0; i<=8; i++){
         portc=x[i];
         delay_ms(100);
      }          //for bracket

         }            //while bracket 

}                //main bracket

Now come towards code; firt select the port you want to use, i this case it is portc. Then clear the port by assigning it 0. Trisx, the SFR  is used to set the port as input or output, where x can be a,b,c,d, and e; the port which you are using. Trisc=0 means the portc is selected for output. For input change it to Trisc=255; means all pins of portc as ready for input. If you want take i/p at single pin instead of whole then use trisxy_bit=1, where y could be from 0 to 7; the pin you at want to take i/p and y is the respective port.

There are two comparators in 887, to disable them assign 0 to c1 and c2 bits. Also to use pins as digital i/o assign 0 to ansel and anselh; dont be panic when we do ADC i will tell you about this. Note that for 877a these two thing is not required.

Now for loop; as for led chaser we want to on led at power of 2 sequence that is 1,2,4 till 256 as port is 8-bit so 2^8=256; that is why have save these values in a array.
To get visual we have to add some delay, to do this just write delay_ms(100); for 100 ms delay. You can increase it if you want.

As we want to see our o/p continuously not only for a single time, we use while loop; while(1) means this loop will run forever.

project setting
Schematic: 
Give the hex file path, of this project, to isis and simulate it. Dont forget to attach reset circuitry.

Reset Circuit: