Another place that we sometimes see time.sleep() used is for a sort of minimal "debouncing" effect with push buttons. Some code for that might look like this:

Download: file
import time
import board
from digitalio import DigitalInOut, Direction, Pull

btn = DigitalInOut(board.SWITCH)
btn.direction = Direction.INPUT
btn.pull = Pull.UP

while True:
    if not btn.value:
        print("BTN is down")
    else:
        #print("BTN is up")
        pass

    time.sleep(0.1) # sleep for debounce

In this situation, the time.sleep() aims to reduce the speed at which the button will continue registering more actions if the button is held down. 

Instead, we could store a variable containing the state of the button from the previous iteration, and then compare against it each time. That way, the button will only trigger a single action when it's pressed, or when it's released if we want that instead.

"""
This example script shows how to read button state with
debouncing that does not rely on time.sleep().
"""

import board
from digitalio import DigitalInOut, Direction, Pull

btn = DigitalInOut(board.SWITCH)
btn.direction = Direction.INPUT
btn.pull = Pull.UP

prev_state = btn.value

while True:
    cur_state = btn.value
    if cur_state != prev_state:
        if not cur_state:
            print("BTN is down")
        else:
            print("BTN is up")

    prev_state = cur_state

Now that this code no longer relies on time.sleep(), it can play nicely without interrupting LED animations, servos, and other tasks that your Circuit Python device is handling. If we do it this way, we get a single action when the button is pressed, and another single action when the button is released.

This process of looking for for the change in button state is known as debouncing, and there is a CircuitPython library created  to help make it easier called adafruit_debouncer. If you stick to using this library, you won't have to worry about the debouncing logic interfering with other tasks. This guide covers its usage: Python Debouncer Library for Buttons and Sensors

This guide was first published on Oct 08, 2020. It was last updated on Oct 08, 2020.

This page (Buttons) was last updated on Apr 10, 2021.

Text editor powered by tinymce.