0

I want to detect if a button has been pressed, but what I don't want is for it to keep returning the "pressed" state more than once within a second or two.

For example, with this code:

void loop() {
 passButtonState = digitalRead(passButton);
 if (passButtonState == LOW) {
 Serial.println("PASSED!");
 }
}

Would spit out something like this with a single quick press of the button:

PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!

But what I want is for a single button press to just return PASSED! once for that single button press.

rebatoma
5593 gold badges12 silver badges22 bronze badges
asked Apr 2, 2016 at 2:22

4 Answers 4

0

To avoid this problem you can use a boolean variable as a flag that permit to enter inside the if only once.

bool flag = true;
void loop() {
 passButtonState = digitalRead(passButton);
 if (passButtonState == LOW && flag) {
 Serial.println("PASSED!");
 flag = false;
 }
}
answered Apr 2, 2016 at 2:25
2
  • But this permanently disables that button from then on. I just want it to only return once for each press as opposed to a dozen. Commented Apr 2, 2016 at 2:28
  • @Shpigford you can reset the flag = true after a period of time. Commented Apr 2, 2016 at 2:30
1

If I understand the problem correctly, I think the answer might be a pretty common one. Your circuit may be suffering from "bounce" and the solution is called "debounce."

Check out this link for a possible solution: Software Debounce

answered Apr 2, 2016 at 16:43
0
void loop() {
 passButtonState = digitalRead(passButton);
 if (passButtonState == LOW) {
 Serial.println("PASSED!");
 while (passButtonState == LOW) delay(1);
 }
}
answered Aug 14, 2022 at 17:07
-1

You can add a delay.

void loop() {
 passButtonState = digitalRead(passButton);
 if (passButtonState == LOW) {
 Serial.println("PASSED!");
 delay(1000);
 }
}
answered Apr 2, 2016 at 3:45
1
  • 1
    Could you explain why this would be a good solution? While it may be trivial to you and me, it certainly won't be to everyone. Also, you should state that adding a delay will "slow" the whole program. You might even give alternative solutions. Commented Apr 5, 2016 at 17:08

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.