state detection of pushbutton

int LED = 10;
int Button = 2;

int ButtonValue = 0;
int previousButtonValue = 0;

int State = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(LED, OUTPUT);
pinMode(Button, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
ButtonValue = digitalRead(Button);

  if(ButtonValue == HIGH && previousButtonValue == LOW)
  {
      State = 1 - State;
      delay(100);
  }   
      previousButtonValue = ButtonValue;
      
        if(State == 1)
        {
          digitalWrite(LED, HIGH);  
        } else
         {
          digitalWrite(LED, LOW);
         }
        
}

i have this code given to me by my friend. im confused how the first ifstatement works.

"if(ButtonValue == HIGH && previousButtonValue == LOW)" Is this statement equal to "if(ButtonValue == LOW && previousButtonValue == HIGH)".

Will the next block of code still be executed??

It is not equivallent for sure !

They both mean "if state has changed" but you are not entering the if at the same state

Now for blinking a LED - that might get you something similar depending of initial conditions of previousButtonValue

No, that says that if it's currently high and the previous (a few microseconds ago) was low, then we know that the button input has just changed to the high state.

Normally you wire your buttons so they go LOW when pressed. This saves one resistor on your board because there are internal pullup resistors. Use pinMode(Button, INPUT_PULLUP); and make the button connect that input to the ground.

What I understand is this:

When button is pressed this executes the block of code inside the first ifstatement(State = 1 - State) and LED turns on.
Then the previousButtonValue will become the Current button state right?? which is HIGH.
and when button is released this makes the ButtonValue == LOW and PreviousButtonValue == HIGH which makes the ifstatement not true and then will not execute the block of code inside it thus LED must be off. Sorry for my english. im not good at it :frowning:

so my question is why is it that when upon release my LED still on??

Is something wrong in my understanding in this code??

That code should only toggle the led when the button is pressed. There is no code there related to release so the led should keep its state until you push the button again.

It's the variable State that determines whether the led should be lit. It changes anytime the input goes from low to high. Even after you release the button there is no other code to change State.

so does this mean that the button state will only be read when button is pressed??

bembe24:
so does this mean that the button state will only be read when button is pressed??

The button state is read anytime digitalRead is called on that pin. Looks like that happens every time through loop.

I get it now!! i misunderstood "==" and "=". Thanks for the help! :wink: