Basic Debouncing

circuitpython_trampoline.jpg
From https://learn.adafruit.com/led-trampoline

To debounce an input pin we simply create an instance of Debouncer, passing it a configured DigitalInOut:

Download: file
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.

Download: file
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. 

Download: file
    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:

Download: file
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.

Download: file
        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).

This guide was first published on Jan 08, 2019. It was last updated on Jan 08, 2019. This page (Basic Debouncing) was last updated on Nov 14, 2019.