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.

circuitpython_Bouncy_Switch.png
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.

circuitpython_switch_led.png
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:

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:
        print(pressed)
    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.

There are two straightforward ways of doing debouncing in CircuitPython.

  • The keypad module returns debounced key or button press and release events. keypad is the preferred way to do debouncing, but it is not available on SAMD21 builds for space reasons. For more information on keypad, see the Keypad and Matrix Scanning in CircuitPython guide.
  • 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 Mar 08, 2024.

This page (Overview) was last updated on Mar 08, 2024.

Text editor powered by tinymce.