0

When pushing a button I want to read the value...once. If I push(hold) the button I get a continuous print of button1Pushed

 if(button1State == LOW) { 
 Serial.println("button1Pushed");
 }

But if I try to solve it like this, nothing happens, not a single print. What am I missing?

 int button1State = digitalRead(button1);
 int lastButton1State;
 
 if(button1State != lastButton1State){
 if(button1State == LOW){
 Serial.println("button1Pushed");
 }
 }
 lastButton1State = button1State;
asked Oct 18, 2020 at 19:48

1 Answer 1

2

lastButton1State is not initialized and therefore has no strictly defined value. In your case, it appears to have a value of 0 (which is random, it's not due to implicit initialization, which is only done for global variables). The condition if(button1State != lastButton1State) becomes true only if the button is released.

You can check that by changing

if(button1State == LOW){
 Serial.println("button1Pushed");
}

to

if(button1State == HIGH){
 Serial.println("button1 released");
}

The following should work:

int last_button_state=HIGH; // initialize to HIGH, so the button does not teigger on very first iteration
void setup () {
 // whatever you want to do here
}
void loop() {
 int button_state=digitalRead(button1);
 if (button_state!=last_button_state && button_state==LOW) {
 Serial.println("button pressed");
 }
 else if (button_state!=last_button_state && button_state==HIGH) {
 Serial.println("button released");
 }
 last_button_state=button_state;
}
answered Oct 18, 2020 at 20:07
5
  • your suggestion gives me the same result, still an endless repeat of the serial.print Commented Oct 18, 2020 at 20:24
  • Did you see the change I made? I forgot to add last_button_state=button_state;... if it still doesn't work, please post the entire code Commented Oct 18, 2020 at 20:26
  • I tried your suggestion in a blank sketch and it works! There is probably something buggy in the rest of my code (its pretty huge..for me..as a amateur) Commented Oct 18, 2020 at 20:32
  • Found it! I put int last_button_state=HIGH; in the loop.....pff..time for bed Commented Oct 18, 2020 at 20:36
  • @Niles please see my comment Commented Oct 18, 2020 at 20:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.