2.2. Button Debounce

In the previous example we saw how we can detect when a button is pressed by reading a value on digital input pin, but in the end we saw that one button press actually generated multiple presses at once. This is due to their mechanical and physical issues, what we see as one press the actual button switch physically makes and breaks contact several times in very short amount of time. To counteract this, we use software debouncing which adds a smally delay in code to ignore fast state changes.
At the end of this example you will learn:
- What is debouncing, how it happens
- How to debounce a button input by adding a time delay
Parts required:
- Soldered NULA Mini Board
- Breadboard
- 1 x LED (any color)
- 2 x 330 Ohm resistor
- 1 x Pushbutton
- Some jumper wires

Putting the components together
- Place the pushbutton on the breadboard, connect one terminal of the button to pin 19, and the other terminal to 3.3V or VCC.
- To connect an LED, connect the longer (positive) leg to the pin 5 via jumper wire, and shorter (negative) leg to GND via 330 Ohm resistor.

Code Example
Import necessary libraries for pin declaration and delay.
from machine import Pin
import time
Define pins used for LED and Pushbutton.
led_pin = 5
button_pin = 19
Initialize the LED as an OUTPUT and button as an INPUT with PULL_DOWN configuration which sets the pins value LOW (0) while not pressed.
led = Pin(led_pin, Pin.OUT)
btn = Pin(button_pin, Pin.IN, Pin.PULL_DOWN)
Set initial LED state to low (OFF), and declare variable to keep track of last LED state. Because we declared pushbutton as PULL_DOWN, 0 means not pressed.
led.value(0)
last_state = 0
Next we define variables to keep track of the last time button was pressed and how long before we can read next press.
last_pressed_time = 0
debounce_delay = 50 # milliseconds
Infinite loop that continuously checks the button and updates the LED. If the button was previously not pressed (last_state == 0) and now is pressed (current_state == 1): method led.toggle() then flips the LED state only if enough time has passed between two presses.
while True:
# Read current voltage level of the button pin (0 when not pressed, 1 when pressed)
current_state = btn.value()
# Save current time
time_now = time.ticks_ms()
# Check for moment when button state changes -> toggle the LED state accordingly
if last_state == 0 and current_state == 1:
if time.ticks_diff(time_now, last_pressed_time) >= debounce_delay:
# Save the last time button was pressed
last_pressed_time = time.ticks_ms()
led.toggle() # Flips the LED state: ON -> OFF; OFF -> ON
print("Button pressed, toggling LED")
# Update last state
last_state = current_state
# Pause the program briefly to allow some time for CPU
time.sleep_ms(10)