You can find the adafruit_debouncer library in the CircuitPython Library Bundle. When you get the appropriate zip file for your version of CircuitPython from circuitpython.org, open it and put the adafruit_debouncer.mpy file in your board's CIRCUITPY drive /lib folder.
To debounce an input pin we simply create an instance of Debouncer
, passing it a configured DigitalInOut
, TouchIn
, or any other object with a value
property:
import board import digitalio from adafruit_debouncer import Debouncer pin = digitalio.DigitalInOut(board.D12) pin.direction = digitalio.Direction.INPUT pin.pull = digitalio.Pull.UP switch = Debouncer(pin)
For the debouncer to do its job, it has to sample the pin frequently, track it's value, etc. etc. That's done by calling the update()
method, typically at the start of your main loop.
while True: switch.update()
The debouncer has three properties that we can use to see what the current state is.
value
which is the current stable value of the input. Stable means that it has stayed the same for some amount of time.
This is the most basic way to use the debouncer: getting the debounced value.
if switch.value: print('not pressed') else: print('pressed')
You can set the amount of time it takes for the value to stabilize by passing it (in seconds) into the constructor. If you don't, it defaults to 0.01 seconds (10 milliseconds). For example:
switch = Debouncer(pin, interval=0.05)
rose
- if this is True
if means that during the most recent update()
call, the stable value changed from False
to True
.
fell
- if this is True
if means that during the most recent update()
call, the stable value changed from True
to False
.
if switch.fell: print('Just pressed') if switch.rose: print('Just released')
These last two are especially useful. In fact, they are generally far more useful than value
. While value
will give you the current stable value, fell
and rose
tells you that it just changed. For example if you want to know when a button is pushed or released (as opposed as to whether or not it's currently being held down) these will provide that information. They tell you that the stable value has changed as of the most recent call to update()
. Furthermore, these will report True
once, and only once, for each change (i.e. for the most recent call to update
). By using them you can do something once, as soon as the state has changed.
For example, in his rotating drum sequencer project, John Park used debouncers on his infrared sensors to clean up their transition between black and white on the disk. Additionally, on the clock track sensor he used rose
to tell him when a clock pulse started. He used that to know when to read the instrument track sensors (using value
).
Other Basic Examples
See the examples folder in the adafruit_debouncer repository for TouchIn
and some other examples.
Text editor powered by tinymce.