I am trying to write best program to turn on LED if switch is pressed but if the switch is not pressed. don't turn LED
I have written code in two way which is best way to read the switch ?
Code:
////8051 and keil compiler
#include <REG51.h>
sbit Switch = P0^1; // switch connected to P0.1
sbit LED = P2^0; // LED connected to p2.0
/* This is delay function */
void Delay (unsigned int n)
{
unsigned int i;
for (i = 0; i <n; i++);
{
}
}
void main (void)
{
while (1) //infinite loop
{
if(Switch == 0) //If the switch is pressed
{
Delay(40); //Switch Debounce
if(Switch == 0) //If the switch is still pressed
{
LED = 1; //LED ON
Delay(1000); // Delay
LED = 0; //LED OFF
}
}
}
}
Code:
#include <REG51.h>
sbit Switch = P0^1; // switch connected to P0.1
sbit LED = P2^0; // LED connected to p2.0
#define TRUE 1
#define FALSE 0
void Delay (unsigned int n)
{
unsigned int i;
for (i = 0; i <n; i++);
{
}
}
bit check_Switch(void)
{
if(Switch == 0) //If the switch is pressed
{
Delay(40); /* */
if(Switch == 0) /* check switch again */
return TRUE; /* switch is really pressed */
}
return FALSE;
}
void main (void)
{
while (1) //infinite loop
{
if (check_Switch == TRUE)
{
LED = 1; //LED ON
Delay(1000); // Delay
LED = 0; //LED OFF
}
}
}