I have a fairly large project running a Mega with a button that really needs to be debounced. I have no idea how to implement it (I've tried and just screwed everything up.)
So I have a zip of the project files. Could someone have a look at it and give me some pointers? The button in question is menuselect, or buttonstate [3]. All the files are part of the same project, all included.
//--- Initialize timer2 .. using 20ms for this example
MsTimer2::set(20, buttons);
MsTimer2::start();
... may need to adjust the (20) in the example.
Why and How?
When you only check a button state every (x) ms .. there is no need to debounce due to the fact that the button stops bounding around really quick compared to a 20ms timer (for example).
As funny as that was, here is a more serious answer. Some untested code to check for switch bounce...
boolean InitialValue = digitalRead(myPin);
boolean IsBouncing = false;
int n = 100; // you pick this number based on how bouncy your switch is
for (int i =0; i < n; i++)
{
if (digitalRead(myPin) != Initialvalue)
{
IsBouncing = true;
break;
}
}
Note there are some more robust ways to do this through direct port manipulation and interrupts that would catch rare instances where say the switch was bouncing at a frequency that matches the execution period of the for loop. But this should probably work for most hardware.
The general idea is to not accept that a switch has changed state until it is proven to hold that state without changing for a certain period of time.