I am writing a mp3 player that writes info to a LCD display, I'd like to convert it from using the keyboard to using push buttons but I'm constantly getting too many key presses. I've tried pull up and falling/rising edge but I'm still getting the same result. Any one know off hand if this is a known issue or am I just doing something wrong? Oh, I'm also doing this entirely in C using wiringPi.

  • 1
    Just to add to the pot of software solutions, check out our friend in micro controllers. arduino.cc/en/Tutorial/Debounce
    – cubecubed
    Nov 25 '14 at 20:32
  • Here is a snippet from something I wrote a while back. if(digitalRead(data) && millis()-startTime > 10){ and set startTime ever time it enters for loop.
    – cubecubed
    Nov 25 '14 at 20:33
  • just wondering; what exactly would I set startTime to?
    – linuxgnuru
    Nov 26 '14 at 19:37
  • Some sorta time counter. Arduino has the function millis that gives time since start.
    – cubecubed
    Nov 26 '14 at 22:58
  • Ah ok, so does wiringPi wiringpi.com/reference/timing
    – linuxgnuru
    Nov 27 '14 at 3:04

Mechanical buttons and switches can suffer from switch bounce where they toggle rapidly between open and closed for several milliseconds.

You can try debouncing the button/switch in software or hardware.

Probably simplest in software.

If the level changes (on to off, or off to on) wait x milliseconds and read the gpio again. If it is still in the new state then assume it is a real transition. The value of x could be something like 20.

For hardware solutions look for this sort of post


Take the time to read Jack Ganssle's debouncing guide. The first page illustrates the problem in great detail, and the second how to deal with it in hardware or software. There isn't a 'perfect' debounce method, but there are a lot of bad ones!

This is a problem you will come across repeatedly if interfacing software with switches, so it's worth taking the time to understand it, and Jack's article is the most concise way I've seen to do that.


In applications which have a system ticker I usually implement a shift register.

unsigned char button_checker;

// inside the system ticker

button_checker <<= 1; 
button_checker += INPUT;

if (button_checker == 0xFF) 
    // button was pressed 

Of course, you should carry out the button press event only on a rising edge.

  • 1
    That's an interesting method. Easily customised (by masking off the most significant bits of button_checker) to require a varying number of consecutive reads.
    – joan
    Nov 25 '14 at 20:21

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.