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)".
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.
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
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.