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.
4 Answers 4
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– Shpigford2016年04月02日 02:28:38 +00:00Commented Apr 2, 2016 at 2:28
-
@Shpigford you can reset the
flag = true
after a period of time.rebatoma– rebatoma2016年04月02日 02:30:51 +00:00Commented Apr 2, 2016 at 2:30
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
void loop() {
passButtonState = digitalRead(passButton);
if (passButtonState == LOW) {
Serial.println("PASSED!");
while (passButtonState == LOW) delay(1);
}
}
You can add a delay.
void loop() {
passButtonState = digitalRead(passButton);
if (passButtonState == LOW) {
Serial.println("PASSED!");
delay(1000);
}
}
-
1Could 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.aaa– aaa2016年04月05日 17:08:51 +00:00Commented Apr 5, 2016 at 17:08