Can someone debounce a button for me?

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.

Project is here:

You might try to setup a timer with buttons function as the callback function.

Find timer at
Add include…

#include <MsTimer2.h>

add code to setup()

  //--- Initialize timer2 .. using 20ms for this example
  MsTimer2::set(20, buttons);

… 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).

Hope that helps - good luck with your project

Can someone debounce a button for me?

Here's how I do it:

You may need to adjust the length of the wire in the example.


Pretty funny. I think that is a hardware solution though. I think OP was looking for a software solution. Perhaps a piece of string, instead.

I see that you are as fond of people referring to switches as buttons as I am.

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;

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.