Switch Interfacing with 8051 

What is a Switch?

A switch is a device or component used to control the flow of electricity in a circuit. It works by opening (breaking) or closing (completing) an electric path. 

Push Button:-

Push buttons or switches connect two points in a circuit when you press them, and when the push button is open (not pressed), there is no connection between the two legs of the button.

Image And Symbol of Switch:-


Task 1:- Turn on the LED when the switch is pressed.

Code:-

#include<reg51.h>

sbit sw=P2^2;

sbit led=P2^0;

void main ()

{

while(1)

{

if (sw==0)

{

led=0;

                        while(sw==1);

}

}

}

Output:-


Task 2:- Turn on the LED when switch 1 is pressed and turn it off when switch 2 is pressed.

Code:-

#include<reg51.h>

sbit sw=P2^2;

sbit sw1=P2^4;

sbit led=P2^0;

void main ()

{

while(1)

{

if (sw==0)

{

led=0;

while(sw==0);

}

else if (sw1==0)

{

led=1;

}

}

} 

Output:-

Task 3:- Turn on/off led using single switch.
Code:-
Method 1:-

#include<reg51.h>

sbit sw=P2^2;

sbit led=P2^0;

int led_state=1;

void main ()

{

int switch_state=1;

while(1)

{

if (sw==0 && switch_state==1)

{

led_state=!led_state;

led=led_state;

while(sw==0);

}

}

} 

Method 2:-

#include<reg51.h>

sbit sw=P2^2;

sbit led=P2^0;

int count=1;

void main ()

{

while(1)

{

if (sw==0)

{

count++;

while(sw==0);

if (count%2==0)

{

led=0;

}

else

{

led=1;

}

}

}

}

Output:-