# If statement in an If else statement guidence

Hi all,
Apologies in advance if i make a mistake in making this post, it is my first time.

What im trying to achieve:
I have 2 push buttons, i want to push them in a certain order to make an LED turn on.
So Push button A must come on first, then Push button B, this will turn the LED on.
If Push button B comes on, then Push button A, the LED remains off.

I have tried researching all day how to use an if-else statement inside an if statement to achieve this, but it doesn't seem to work. When i push the push buttons in the desired order, the LED stays off.

I believe i don't fully understand how the if-else statement working inside an if statement.

My aim for the future is to use switches (instead of push buttons) with the same idea as above, how ever the moment one of the switches turns off, the led turns off. This is far down the line as i need to understand more basic problems first.

Thanks for you time!
Again sorry if i made a mistake in making this post.

I will also post my code underneath, i thought uploading the code would show it in the thread.

``````int ledPin = 7; //LED
int pb1 = 2;   //PushButton 1
int pb2 = 4;   //PushButton 2

void setup(){
//Serial.begin(9600);
pinMode(ledPin,OUTPUT);
pinMode(pb1,INPUT);
pinMode(pb2,INPUT);
}

void loop(){
if (pb1 == HIGH) { //If PushButton 1 is pressed, the next thing to look for is if PushButton 2 is on
//If PushButton 2 is on, LED must come on, If off, then LED must be off
if (pb2 == HIGH)
digitalWrite(ledPin, HIGH);

else
digitalWrite(ledPin, LOW);
}

}
``````

b20_trial_2.ino (568 Bytes)

` if (pb1 == HIGH)`Needs more digitalRead

Please remember to use code tags when posting code

In particular note the advice to Auto format code in the IDE and to use code tags when posting code here as it prevents some combinations of characters in code being interpreted as HTML commands such as italics, bold or a smiley character, all of which render the code useless

There is another basic flaw in your program. It responds to the state of the switches, not changes in the state of the switches. You need to code for when a switch BECOMES pressed, not just when it IS pressed.

Firstly, you need to read the state of button inside the loop() function.
Secondly, To detect the press event, detect the state change of instead of checking the state. => it will be simple if you use ezButton library. This library has isPressed() function and debouncing functionality

State change detection is simpler than it sounds, however. It's just basically:

Pseudocode:

``````value = some input
if value not equal to oldValue
{
report a change of state
oldValue = value
}
``````

UKHeliBob: