Wednesday, 1 July 2015

Lesson 1 Led Interfacing with PIC 16F877A (MikroC)

Lesson 1
Led Interfacing with PIC 16F877A
Please check the datasheet of the target microcontroller (MCU) to know the Registers associated with it. The data sheet can be downloaded  from www.microchip.com


We will use the Input/Output (I/O) registers very often. Two registers are associated with the I/O port:

  • The Data register - The data register is named after the port it controls. For PIC 16F MCU the data register is called PORT register e.g PORTA,PORTB etc. The data register sets the Port to high (Logic 1) and Low (Logic 0). For example PORTA = 255 sets all the bit of PORTA to high(Logic 1).  PORTA=0 sets all the bit of PORTA to Low(Logic 0). 
  • The Direction Register - The direction register is known as Tri-State Register as the name suggests, it is used to set the direction of the Port. It is written as TRIS together with the Port letter. E.g TRISA,TRISB,TRISC etc. TRISA=255 sets all the bit of PORTA to input. TRISA=0, sets all the bits of PORTA to output.


An LED can be connected in 2 ways to a MCU.
1. In current Sourcing mode - when it is connected in this mode , the LED will be ON when output PORT is at Logic 1.


2. In current sinking mode - when connected in this mode, the LED will be ON when output PORT is at Logic 0.


A MCU can source and  sink 25mA of current and the output voltage of a MCU is 5V.  LED requires about 2V, so it should be connected to a resistor. The value of the resistor can be calculated thus depending on the current you want through the LED. Most LEDs require 10mA of current.


  Resistor Value = ( Output Voltage of MCU (5v) - LED Voltage (2v)) / (LED current)

This is the C source code for LED Interfacing with 16F877A:

/**********************************
Project Name :
   LED BLINKING
Description :
   This project demonstrate blinking of an LED connected to PORTB BIT ZERO and an LED light chaser program
MCU:  PIC 16F877A
Oscillator: XT 8.0000 MHz, 8.0000 MHz Crystal
***********************************/


void led_blink(){     // function that executes LED blinking
 TRISB.B0 = 0;    // sets PORTB Bit Zero to OUTPUT
 while(1)
 {
  PORTB.B0 = 1;   // Turns ON PORTB Bit Zero
  delay_ms(200);
  PORTB.B0 = 0; // turns OFF PORTB Bit zero
  delay_ms(200);
 } // end of while loop
}

void led_light_chaser(){    // function that executes LED light chaser
  int i;
  TRISB = 0;
while(1){
  PORTB = 1;
  delay_ms(100);

for(i=0;i<=7;i++){
  PORTB = PORTB<<1;
  delay_ms(100);
  } // end of for loop
}  // end of while loop
}
void main() {
led_blink();     //LED Blink function call
//led_light_chaser();    //LED light chaser function call. Uncomment for LED light chaser
}

This is the proteus schematic:




No comments:

Post a Comment