</>EmbeddedInterview

What is debouncing and how do you implement it?

EasyEmbedded C

Short answer: Mechanical switches and buttons "bounce": the contacts open and close several times for a few milliseconds (typically 1–10 ms, sometimes more) when pressed or released. Debouncing means accepting a new state only after the input has been stable for a period. Do it in software by sampling periodically, or in hardware with an RC filter and a Schmitt-trigger input.

Software: shift-register (integrating) debounce, called every 1 ms

#include <stdbool.h>
#include <stdint.h>

static bool pressed;

void button_poll_1ms(void)
{
    static uint8_t history;
    history = (uint8_t)((history << 1) | (read_pin() ? 1u : 0u));
    if (history == 0xFFu)      pressed = true;    /* 8 consecutive samples high */
    else if (history == 0x00u) pressed = false;   /* 8 consecutive samples low  */
    /* mixed samples: keep the previous state */
}

Counter-based debounce for several buttons at once (vertical counters) is a common efficient variant: process up to 8 or 32 buttons in parallel with bitwise operations.

Edge detection after debouncing:

bool now = pressed;
if (now && !last) on_press();      /* rising edge of the debounced state */
last = now;

Interrupt-based approach: an edge interrupt starts a timer (and disables the pin interrupt); when the timer expires (e.g. 20 ms later), read the pin and re-enable the interrupt. This keeps the CPU asleep when nothing happens, which matters for battery devices.

Hardware debouncing: an RC low-pass filter (e.g. 10 kΩ and 100 nF, time constant 1 ms) smooths the bounce; a Schmitt-trigger input (most MCU GPIOs have hysteresis) turns the slow edge into a clean transition. Dedicated debouncer ICs exist too.

Why not just use an edge interrupt on a raw switch? Each bounce triggers an interrupt, so one press produces a burst of 5–50 interrupts, and the press may be counted many times.

Interview follow-ups: long press vs short press (count how long the debounced state stays pressed), and scanning a matrix keypad (see the next question).