Debouncing a button in C with a counter state machine
A mechanical switch does not change cleanly. For a few milliseconds the contacts bounce, and the pin reads 1, 0, 1, 1, 0, 0, 1 before settling. If you count edges directly, one press looks like several. Debouncing means turning that mess into one clean press event and one clean release event.
Why not a delay?
The beginner fix is "see an edge, wait 20 ms, read again". It blocks everything else, behaves badly with several buttons, and wastes the processor. The robust approach is non-blocking: sample the pin periodically from a timer tick and let a small state machine decide.
The idea
Keep the accepted state (released or pressed) and a counter. Each tick:
- If the raw sample equals the accepted state, reset the counter. Nothing is changing.
- If it differs, increment the counter. When the counter reaches
N, the new level has been stable forNticks, so accept it and emit an event.
At a 1 ms tick and N = 5, a change must hold for 5 ms. Bounces shorter than that never get through, and a bounce that restarts the disagreement resets the count when the raw sample briefly returns to the old level.
Tested code
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
typedef enum { EV_NONE, EV_PRESS, EV_RELEASE } event_t;
typedef struct {
bool pressed; /* accepted (debounced) state */
uint8_t count; /* consecutive samples that disagree with it */
} button_t;
#define DEBOUNCE_TICKS 5u
static event_t button_tick(button_t *b, bool raw_pressed)
{
if (raw_pressed == b->pressed) {
b->count = 0;
return EV_NONE;
}
if (++b->count >= DEBOUNCE_TICKS) {
b->pressed = raw_pressed;
b->count = 0;
return raw_pressed ? EV_PRESS : EV_RELEASE;
}
return EV_NONE;
}
int main(void)
{
/* one sample per millisecond: noisy press, steady hold, noisy release */
const char *trace = "000100110111111111111111100101000000";
button_t b = {false, 0};
unsigned presses = 0, releases = 0;
for (unsigned t = 0; trace[t]; t++) {
event_t e = button_tick(&b, trace[t] == '1');
if (e == EV_PRESS) { presses++; printf("t=%2u ms: PRESS\n", t); }
if (e == EV_RELEASE) { releases++; printf("t=%2u ms: RELEASE\n", t); }
}
printf("%u press, %u release from %zu raw samples\n", presses, releases, strlen(trace));
/* a 3 ms glitch must be ignored completely */
button_t g = {false, 0};
unsigned spurious = 0;
const char *glitch = "00001110000000";
for (unsigned t = 0; glitch[t]; t++) if (button_tick(&g, glitch[t] == '1') != EV_NONE) spurious++;
printf("3 ms glitch produced %u events\n", spurious);
return (presses == 1 && releases == 1 && spurious == 0) ? 0 : 1;
}
t=13 ms: PRESS t=34 ms: RELEASE 1 press, 1 release from 36 raw samples 3 ms glitch produced 0 events
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
The noisy input has several 0/1 flips on press and on release, and the output is exactly one event for each.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
Choosing N
Typical mechanical switches bounce for 1 to 10 ms; some are worse. Measure yours on a scope or logic analyzer rather than guessing. A debounce time of 5 to 20 ms is typical and still feels instant to a person. If you also need long-press or double-click detection, build it on top of the clean events, not on the raw pin.
Scaling to many buttons
For a keypad, keep one counter per button, or debounce a whole port at once with bit operations: keep a few vertical counters in parallel so that eight inputs cost the same as one. If you want to find which inputs changed, XOR the old and new state and walk the set bits as in bit tricks for firmware.
Where the tick comes from
Call button_tick from a periodic timer interrupt or from a scheduler task running at a fixed rate. Because it never waits, it is safe at any priority, and the events can be handed to the main loop through a ring buffer.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.