PIC16f877A LED Blink Code

PIC16F877A is comparable to Arduino microcontroller ATmega328P explained in the tutorial PIC Microcontroller similar to ATmega328P(Arduino).Here's a simple LED blinking code for the PIC16F877A microcontroller using the MPLAB X IDE and XC8 compiler. This example assumes that an LED is connected to PORTB, pin RB0.

LED Blinking Code (XC8):

// PIC16F877A Configuration Bit Settings
// 'C' source line config statements

#include <xc.h>

// CONFIG
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Code protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)

#define _XTAL_FREQ 20000000 // Define crystal oscillator frequency, 20MHz for PIC16F877A

void main(void) {
TRISB0 = 0; // Set RB0 as output (LED pin)

while(1) {
RB0 = 1; // Turn on LED connected to RB0
__delay_ms(500); // Delay of 500 milliseconds (0.5 seconds)

RB0 = 0; // Turn off LED
__delay_ms(500); // Delay of 500 milliseconds (0.5 seconds)
}
}


Explanation:

  1. Configuration Bits: These settings specify the hardware configuration for the PIC16F877A, including oscillator selection, watchdog timer, low-voltage programming, and other system options.
  2. _XTAL_FREQ: Defines the frequency of the external oscillator (20 MHz in this case). This is necessary for proper delay functions.
  3. TRISB0 = 0: Sets PORTB pin RB0 as an output.
  4. RB0 = 1: Turns the LED on.
  5. RB0 = 0: Turns the LED off.
  6. __delay_ms(500): A 500-millisecond delay between toggling the LED.

Make sure to connect the LED with a suitable current-limiting resistor (220 ohms to 1K ohms) to the RB0 pin and the ground.

The circuit diagram below shows how to connect the LED to the PIC16F877A microcotroller pin along with crystal oscillator and reset button.

PIC16f877A LED Blink Code

Post a Comment

Previous Post Next Post