Debounce a Push Button
A button is sampled every 1 ms by a timer ISR that calls debounce(raw), where raw is the current pin level (1 = pressed). The function should return:
1exactly once when the button becomes stably pressed (raw is 1 for 5 consecutive samples),-1exactly once when it becomes stably released (5 consecutive 0s),0otherwise.
Bounces shorter than 5 samples must be ignored. The initial state is released.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Keep the current stable state and a counter. Count samples that differ from the stable state; reset the counter whenever a sample agrees with it.
#include <stdio.h>
#include <stdint.h>
#define STABLE_SAMPLES 5u
int debounce(int raw)
{
static int stable; /* 0 = released, 1 = pressed */
static unsigned cnt;
if (raw == stable) {
cnt = 0; /* agrees with current state */
return 0;
}
if (++cnt >= STABLE_SAMPLES) {
stable = raw;
cnt = 0;
return stable ? 1 : -1;
}
return 0;
}
This is a two-state machine with a counter. Any sample matching the stable state resets the count, so a glitch has to last the full 5 ms to register. Events are edge-triggered, which is what application code usually wants ("button pressed" rather than "button is down").
A compact alternative keeps an 8-bit shift-register history and checks for 0x1F/0xE0 patterns. Avoid debouncing with edge interrupts alone: a bouncing contact can fire dozens of interrupts. Five milliseconds suits most tactile switches; check the switch datasheet.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
static int feed(const char *s) /* returns sum of events, counts presses*10 */
{
int presses = 0, releases = 0;
for (; *s; s++) { int e = debounce(*s == '1'); if (e == 1) presses++; if (e == -1) releases++; }
return presses * 10 + releases;
}
int main(void)
{
CHECK(feed("0000") == 0);
CHECK(feed("1010110") == 0); /* bouncing, no event */
CHECK(feed("11111") == 10); /* one press */
CHECK(feed("1111111111") == 0); /* held: no repeat */
CHECK(feed("0100100") == 0); /* short glitches while held */
CHECK(feed("00000") == 1); /* release */
CHECK(feed("1111100000") == 11);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}