We use switches a lot in our projects. Pushbutton switches, slide switches, micro switches. We also have touch sensors, light sensors, sound sensors, and many others.

These physical devices are messy. By that I mean that the change from one state to the other (e.g. pressing or releasing a button) bounces back and forth before settling into the new state. You can see this in the oscilloscope trace below.

From wikipedia CCO by Super Rad!

These bounces are fast. The bouncy section of the above trace lasts for a couple milliseconds. If you hooked a switch to an LED as below, you'd never notice the bounce. They're far to fast for that.

By Dave Astels

However code running on a microcontroller is a lot faster that our eyes and brains. It can see those bounces. If you have code that's looking for the push and release of a switch, it might be something like this:

Download: file
import board
import digitalio

pin = digitalio.DigitalInOut(board.D12)
pin.direction = digitalio.Direction.INPUT
pin.pull = digitalio.Pull.UP

button_state = False
while True:
    pressed = pin.value
    if pressed != button_state:
    button_state = pressed

Some switches bounce more than others and with some CircuitPython code won't see the bounces whereas C++ code would. Python's slower performance can actually do you a favor sometimes. But not always. And as the microcontrollers CircuitPython runs on get faster, bouncing will be more of a problem.

This guide introduces the adafruit_debouncer library and its Debouncer class. It starts with the basic usage and proceeds to more advanced capabilities.

This guide was first published on Jan 08, 2019. It was last updated on Jan 08, 2019.

This page (Overview) was last updated on Feb 20, 2021.

Text editor powered by tinymce.