This post provides an example code to use PIC16F877 pins as inputs. After going through this example, you will understand how to make PIC16F877 pins as inputs and how to read their value in the code. This code is written in C language using MPLAB with HI-TECH C compiler.You can download this code from the 'Downloads' section at the bottom of this page.

It is assumed that you know how to blink an LED with PIC16F877 microcontroller. If you don't then please read this page first, before proceeding with this article.

Following figure shows the circuit used to demonstrate how to get input in PIC16F877 micro-controller.
Figure 1.   PIC16F877 pin as input demonstrating circuit
In this figure, PIC16F877 is running on external crystal of 20MHz[1]. RB0 pin is being used as the input pin. When the push button is in the pushed state then, RB0 pin is high, otherwise RB0 pin is low. Whenever RB0 pin is high, then RD0 pin (Attached with the LED) is also made high just to indicate correct reading of RB0 pin status in the micro-controller.

Code

The code for reading the status of RB0 pin is shown below.
Figure 2.   GPIO pins as input for PIC16F877 main code
In the main function, firstly RB0 pin is made an input and RD0 is made an output. Using TRISx register[2], we can set the direction of any pin i-e if it is an input or output. So, TRISB0 = 1; makes RB0 pin an input pin. And TRISD0 = 0; makes RD0 pin an output pin. Also, using the statement RD0 = 0; RD0 pin is made low.

In the while(1) loop, status of RB0 pin is constantly being checked, if it becomes high then RD0 is also made high. If RB0 is low, then RD0 is also made low as well.

You can leave your comments in the comment section below.

Notes and References

[1]  Because every PIC microcontroller has an architecture which executes an instruction in 4 CPU cycles, when CPU frequency is defined to be 20MHz, then actual speed of this PIC microcontroller will be 5 MIPS (Million of instructions per second). You can attach any crystal from 0 to 20MHz with PIC16F877.
[2]  For details please refer to PIC16F877 datasheet.

Downloads

Input pin code using PIC16F877 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.

Further Reading Suggestions

9

View comments

Loading