0

Hey guys need your help in verifying out this program about toggling the LED ON and OFF using 2 push buttons.What i actually want is to let my LED stay ON when i press and even leave the push button-1 , and on pressing and leaving the push button-2 i want the led to turn off and no matter how many times i press the push button-1 i want it to turn ON the LED and the push button-2 should only turn off the LED.but with my program i am only able to see the LED to be at HIGH state,It is not shifting to LOW state on clicking push button-2.

This is my sketch :-

    /* LED CONTROLLED WITH 2 PUSH BUTTON PROJECT
       BY ARSH BANSAL 

 CIRCUIT :-
 i) LEDPIN CONNECTED PIN 13.
 ii) PUSHBUTTON1 CONNECTED TO PIN 8.
 iii) PUSHBUTTON2 CONNECTED TO PIN 7.
 iv) BOTH THE PUSH BUTTONS CONNECTED PARALLELY, EACH WITH A 1K PULLUP RESISTOR AND BOTH THE PUSH BUTTONS CONNECTED TO 5V SUPPLY.
   */

 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

 void setup() 
 { 
   pinMode(ledpin,OUTPUT);
   pinMode(pushbutton1,INPUT);
   pinMode(pushbutton2,INPUT);
 }

 void loop()
 {
   if ( digitalRead(pushbutton1)== HIGH && digitalRead(pushbutton2) == LOW && lastbuttonstate1 == LOW )
    { digitalWrite (ledpin,HIGH) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW && lastbuttonstate1 == HIGH)
    ; { digitalWrite (ledpin,HIGH) ; }

    if ( digitalRead(pushbutton1)== LOW && digitalRead(pushbutton2) == HIGH  && lastbuttonstate2 == LOW)
    { digitalWrite (ledpin,LOW) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW  && lastbuttonstate2 == HIGH)
    ; { digitalWrite (ledpin,LOW) ; }
    }
1

You are better off, in this case, remembering the state of the LED not the state of the buttons:

  • If the LED is OFF and BUTTON1 is PRESSED then turn the LED on.
  • If the LED is ON and BUTTON2 is PRESSED then turn the LED off.

For example:

void loop() {
    static bool ledState = false; // LED is off by default
    if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
        digitalWrite(ledpin, HIGH);
        ledState = true;
    }
    if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
        digitalWrite(ledpin, LOW);
        ledState = false;
    }
}
  • I just understood my mistake i should have used if statement after else to check the respective conditions well thanks for your efforts. – ElectroManiac Mar 27 '16 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.