Contents
Introduction
This article is meant for beginners in the field of microcontrollers. When I started with microcontrollers, as everyone I also need to learn how to interface a switch with microcontroller. Here we use PIC Microcontroller 16F877A and MikroC Pro compiler. This tutorial assumes you have basic knowledge about programming PIC Microcontroller, else you read the article Blinking LED using PIC Microcontroller.
In this tutorial we use a push button switch, when we press on it an LED glows for a second. Push Buttons are mechanical switches. Then can make or break connection between two terminals and comes back to stable state when released. They are called as Push to ON or Push to OFF switches respectively.
Circuit Diagram
Note: VDD and VSS of the pic microcontroller is not shown in the circuit diagram. VDD should be connected to +5V and VSS to GND.
Push button switch is connected to the first bit of PORT D (RD0) which is configured as an input pin. Which is connected to a pull up resistor such that this pin is at Vcc potential when the switch is not pressed. When the switch is pressed this pin RD0 will be grounded. The LED is connected to the first bit of PORT B (RB0) and a resistor is connected in series with it to limit the current.
MikroC Program
void main() { TRISD.F0 = 1; //Configure 1st bit of PORTD as input TRISB.F0 = 0; //Configure 1st bit of PORTB as output PORTB.F0 = 0; //LED OFF do { if(PORTD.F0 == 0) //If the switch is pressed { Delay_ms(100); //Switch Debounce if(PORTD.F0 == 0)//If the switch is still pressed { PORTB.F0 = 1; //LED ON Delay_ms(1000); //1 Second Delay PORTB.F0 = 0; //LED OFF } } }while(1); }
In the above program you may noticed that the switch is checked twice with a 10 millisecond delay. This is to avoid invalid clicks by Switch Bouncing.