Button debounce: Short & Long press without blocking

Hey there, currently I am running a python script that uses a button attached to the GrovePi using a screw terminal. Until now it had only one function in each “mode”, however I would like to add short and long press functions without (further) delaying the program. Any thoughts on this?

Currently this is my function to read the button:

def pushcallback():
	readingpush = grovepi.digitalRead(pinpushbutton)
	if (readingpush == grovepi.digitalRead(pinpushbutton)):
		return readingpush

Hi @jeroenveenvan,

Here are some suggestions for you:

  • Use threads (one for each button) - it’s going to let your main program run just as before.

  • Read more frequent the button’s state in the same period of time: i.e.: instead of reading the button’s state, then wait 200ms and then check again, try reading the button’s state for say … 5 times during those 200ms.

  • Use some statistical analysis for eliminating noise during the reads - maybe the user doesn’t push as with much force the button in order to trigger it, so I think this approach is going eliminate these errors.

What do you think?

Thank you!

I know the topic is quite old, but I did want to share my own solution. I didn’t want to be bothered using threads (still don’t know how to use them… my bad!) This is a very simple solution which works good /enough/.

def pushcallback():
    readingpush = grovepi.digitalRead(pinpushbutton)
    timepush = time.time()
    if (readingpush != grovepi.digitalRead(pinpushbutton)):
        return None
        if (readingpush == 0):
            return 0
        while (readingpush == grovepi.digitalRead(pinpushbutton)):
            if (grovepi.digitalRead(pinpushbutton) == 0):
                newtime = time.time() - timepush
                print newtime
                return newtime
1 Like