I have made some modification based on your suggestion.
-
If the switch is not pressed, do nothing.
-
If the switch is press and the status is 0 then turn the light on and set status to 1.
-
If the switch is press and the status is 1 then turn the light off and set status to 0.
The result that I got is
-
When the switch is pressed, the light turn on. When the switch is released, the light turn off.
-
When holding the switch, it toggles the light on and off every half second.
-
The Serial.println shows the status variable is always 0 unless the switch is pressed that when it will change to 1 and immediately goes back to 0.
What am I missing here? Thank you!
int sw1;
int LM1 = 6;
int LED1 = 4;
//Status variable, 0 is off and 1 is on
int Status_variable = 0;
void setup() {
pinMode(LM1, INPUT_PULLUP);
pinMode(LED1, OUTPUT);
digitalWrite(LED1, HIGH);
Serial.begin(9600);
}
void loop(){
sw1 = digitalRead(LM1);
if (sw1 == HIGH)
{
Serial.println(Status_variable);
}
if (sw1 == LOW && Status_variable == 0)
{
digitalWrite(LED1, LOW);
Status_variable = 1;
delay(500);
Serial.println(Status_variable);
}
if (sw1 == LOW && Status_variable == 1)
{
digitalWrite(LED1, HIGH);
Status_variable = 0;
delay(500);
Serial.println(Status_variable);
}
}