How to Program Switch and LED Connected with PIC16F877A

The following code demonstrate, how to write a program that scan the switch status and turn on and off LED. The switch is connected at PORTE bit-0 and LED connected on PORTB bit-0. When switch is read as high state, the LED is turn-on and when switch state is low, LED is turn-off. The switch debouncing rate is 5msec. The code is written in “mikroC PRO for PIC v.5.6.1” IDE and simulation is done with Proteus 8.0 SP0. At the end of code, you can find complete project files for download.
Picture 2017-04-20 22_01_05

Code in mikroC

// switch connected on porte
#define SW_AT_PORT PORTE
// debounce rate 5msec
#define DBOUNCE_RATE 5
// direction signal
sbit LED_dir at TRISB.B0;
sbit SW_dir at TRISE.B0;
// bit labels portb
sbit LED at PORTB.B0;
sbit SW at PORTE.B0;
// old state save flag
bit oldstate_one_to_zero;
bit oldstate_zero_to_one;
void main(void)
{
// set porta and porte as digital
ADCON1 = 0x06;
// set direction as output
LED_dir = 0;
// set direction as input
SW_dir = 1;
// init LED
LED = 0;
// init old state flag
oldstate_one_to_zero = 0;
oldstate_zero_to_one = 0;
while(1)
{
// Detect logical one
if(Button(&SW_AT_PORT, 0, DBOUNCE_RATE, 1))
{
// Update flag
oldstate_one_to_zero = 1;
}
// Detect one-to-zero transition
if (oldstate_one_to_zero && Button(&SW_AT_PORT, 0, DBOUNCE_RATE, 0))
{
// Update flag
oldstate_one_to_zero = 0;
// LED ON
LED = SW;
}
// Detect logical zero
if(Button(&SW_AT_PORT, 0, DBOUNCE_RATE, 0))
{
// Update flag
oldstate_zero_to_one = 1;
}
// Detect zero-to-one transition
if (oldstate_zero_to_one && Button(&SW_AT_PORT, 0, DBOUNCE_RATE, 1))
{
// Update flag
oldstate_zero_to_one = 0;
// LED OFF
LED = SW;
}
}}

Download Files

For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.

Comments

Popular posts from this blog

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program Interrupts in PIC16F877A

How to Program SPI in PIC16F877A (Slave Mode)