Using Push Button With Microcontroller
Introduction
This project is particularly for beginners.In this project we will connect a push button-switch to Micrcontroller-PIC16F877 to control an LED on and off.When the push button is pressed , LED is On (HIGH) , when push button is released , the LED is Off (LOW).
MikroC Compiler is used.This tutorial assumes you have basic knowledge about prgogramming PIC Microcontroller , if not , start with this tutorial and this.
MikroC Compiler is used.This tutorial assumes you have basic knowledge about prgogramming PIC Microcontroller , if not , start with this tutorial and this.
To see more connections click here
Schematic
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.
PIC 16F877A has no internal oscillator, so we should connect external oscillator. Two 22pF capacitors are used to stabilize the operation of the Crystal Oscillator. A low on MCLR pin will reset the PIC, so we tie it to VDD to avoid accidental RESET.
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.
PIC 16F877A has no internal oscillator, so we should connect external oscillator. Two 22pF capacitors are used to stabilize the operation of the Crystal Oscillator. A low on MCLR pin will reset the PIC, so we tie it to VDD to avoid accidental RESET.
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 ()
{
TRISB.F0 = 0; //Configure 1st bit of PORTD as input
TRISD.F0 = 1; //Configure 1st bit of PORTB as output
PORTB.F0 = 0; //LED OFF
while(1) { // Infinite loop
if (PORTD.F0==1) //If the switch is pressed
{ PORTB.F0 = 1; } //LED ON
else // If the switch is released
{ PORTB.F0 = 0; } //LED OFF
}}
{
TRISB.F0 = 0; //Configure 1st bit of PORTD as input
TRISD.F0 = 1; //Configure 1st bit of PORTB as output
PORTB.F0 = 0; //LED OFF
while(1) { // Infinite loop
if (PORTD.F0==1) //If the switch is pressed
{ PORTB.F0 = 1; } //LED ON
else // If the switch is released
{ PORTB.F0 = 0; } //LED OFF
}}