switch callback on press & release

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
smhodge
Posts: 14
Joined: Tue Jan 22, 2019 2:16 am

switch callback on press & release

Post by smhodge » Thu Jun 06, 2019 3:58 pm

Is it possible to have a callback on a switch release as well as the initial press? If so, how do you configure it?

User avatar
dhylands
Posts: 3227
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: switch callback on press & release

Post by dhylands » Thu Jun 06, 2019 5:36 pm

You can by using ExtInt: http://docs.micropython.org/en/latest/l ... xtInt.html

The switch module is built internal using the ExtInt module,

I have an example that uses ExtInt for decoding a rotary encoder on rising and falling edges: https://github.com/dhylands/upy-example ... /rotary.py

You could also modify the mpconfigboard.h file. For the PYBV11, for example, this is what determines which edges cause the switch callback to be invoked:
https://github.com/micropython/micropyt ... oard.h#L78

You would use GPIO_MODE_IT_RISING_FALLING to have the callback called on both edges.
Note that you'll want to have some debounce circuitry or logic since you may get multple presses/releases per button press otherwise.

smhodge
Posts: 14
Joined: Tue Jan 22, 2019 2:16 am

Re: switch callback on press & release

Post by smhodge » Fri Jun 07, 2019 1:11 am

Thanks. Another gem in the documentation I missed. Usually I use MAX681x switch debouncers. Pricey little hummers but they are worth it in my book. Steve

User avatar
pythoncoder
Posts: 3599
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: switch callback on press & release

Post by pythoncoder » Fri Jun 07, 2019 7:58 am

Another approach is to use asynchronous programming with uasyncio. This repo contains various resources including a tutorial on uasyncio. It also offers classes for debounced Switch and Pushbutton objects. The former supports open and close callbacks, the latter extends it to include long press and double-click callbacks.
Pricey little hummers
And, as a software solution, it's free ;)
Peter Hinch

Post Reply