Sorry if I sound unconstructive from time to time - this is due to some needed comic relief :-)
What is bouncing? When a switch is closed, it will shortly reopen after that due to mechanical elasticity, this is the same as if you let go a ball to the floor which will bounce many times until it rests. The length of this bouncing phase differs greatly between switches, not only between brands but also between specimen, and also depends on age and wear.
A "last bounce" can even happen 100ms after the switch is pressed.
Note that there can be no bouncing when a switch is re-opend, but there is a similar though much shorter electrical effect.
It is considered good practice in software debouncing not to wait until the bouncing is over, but to immediately act at the first edge because you know that the key has been pressed!
Now after some internal activities are over you are wait.ing again that the key has been pressed. You can be in of three situations:
- The key is still bouncing
- The key is still pressed
- The key is already open
How to handle this depends on whether you look at a rising edge - often leading to an interrupt - or if you are polling looking at the level.
The solution of BetterSense is excellent, if the time of "do stuff" is long enough to have left the bouncing phase.
Generally there will be no advantage whith interupts. At the place where you check the dummyVar-flag you can as well read digitalInput(). (Except the key press is very short and you are in danger to miss it!)
The tricky thing comes when the processing of the keypress event is over. Now you have to look for an open key phase, long enough so it cannot be confused with a bounce spike (those spikes are very short btw and in fact difficult to probe without edge sensitive hardware...)
In cases when you can poll regularly, you can use a state variable openCounts to know that a resonably open time has passed
The Code for this might go (sorry no check, just typed in)
// poll button
if (digitalRead(buttonPin) {
if (openCounts>2) {
// do things
}
openCounts= 0;
} else
openCounts ++;