LED Blinking PIC16F877A

This post provides the code to make an LED blink using PIC16F877 microcontroller. This code is written in C language using MPLAB with HI-TECH C compiler. This code is intended to be the first step in learning how to use PIC16F877 microcontroller in your projects. You can download this code from the 'Downloads' section at the bottom of this page.

Following figure shows the minimum circuit required to make an LED blink with PIC16F877.
LED Blinking.

In this figure, first thing to note is that there is a crystal of 20MHz used with PIC16F877[1]. You can use any crystal from 0 to 20MHz with PIC16F877MCLR master reset pin is pulled high to keep PIC16F877 out of reset. RB0 pin is being toggled in the code.

Code:

/*  Name             : main.c
 *  Purpose        : Main file for using LCD with PIC16F877 in 8bit mode.
 *  Programmer : Tahir Ahmed.
 *  Website         : tahirahmed.blogspot.com
 */
#include<htc.h>

// Configuration word for PIC16F877
__CONFIG( FOSC_HS & WDTE_OFF & PWRTE_ON & CP_OFF & BOREN_ON 
& LVP_OFF & CPD_OFF & WRT_ON & DEBUG_OFF);

// Define LED pin
#define LED  RB0

// Define CPU Frequency
// This must be defined, if __delay_ms() or 
// __delay_us() functions are used in the code
#define _XTAL_FREQ   20000000  


void main(void)
{
TRISB0 = 0;   // Make RB0 pin output
LED    = 0;   // Make RB0 low

while(1)
{
__delay_ms(500);       // Half sec delay
LED = 0;               // LED off
__delay_ms(500);       // Half sec delay
LED = 1;               // LED on
}
}


Whenever you are writing code for PIC microcontrollers, then you have to include "htc.h" file in the code. After including "htc.h" file, configuration bits are being set in the code shown above. To understand the details of how these configuration bits are being programmed, you can read this post.

After the configuration bits, LED pin is being defined as the RB0 pin. You can replace RB0 with any other pin name if you want (e-g RA0 etc). After LED pin definition, CPU frequency is being defined. You have to define _XTAL_FREQ macro, if you want to use built in delay functions like __delay_us() and __delay_ms(). Here CPU frequency is defined to be 20MHz, which is the crystal oscillator frequency attached with PIC16F877 in the circuit.

In the main function, firstly RB0 pin direction is set to be an output pin using TRISB0 = 0; statement. Using TRISx register[2], we can set the direction of any pin i-e if it is an input or output. Then LED pin is made low using LED = 0; statement.

LED pin is being toggled in the while loop after every half second. In this way you can easily make LED blink using PIC16F877 microcontroller.

You can leave your comments in the comment section below.

Downloads

LCD interfacing code using PIC16F877a was compiled in MPLAB v8.85 with HI-TECH C v9.83 compiler and simulation was made in Proteus v7.10. 
To download code and Proteus simulation Click Here .

Comments

Popular Posts