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.

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;
  }
}
  • 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. – Shpigford Apr 2 '16 at 2:28
  • @Shpigford you can reset the flag = true after a period of time. – rebatoma Apr 2 '16 at 2:30
0

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

-1

You can add a delay.

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
    delay(1000);
  }
}
  • 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. – Paul Apr 5 '16 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.