---
title: Debouncing buttons
heading: One press, many edges, and how to count one
eyebrow: C12 · Lesson 8 · Debouncing buttons
xp: 40
---

::: hook
A button's contacts are two springy pieces of metal. When they meet, they bounce apart and together several times over a few milliseconds before they settle, and they do it again on release. A person presses once; a fast program reading the pin sees half a dozen presses. Every product with a button has to **debounce** it, in hardware with a capacitor or in software by refusing to believe a change until it has lasted long enough. The software way costs nothing but a little logic and a few milliseconds of delay.
:::

::: play
- The button is pressed three times, and its contacts bounce for 4 ms at every press and release. The program counts falling edges two ways and prints both counts at the end.
- The raw count takes every falling edge: it prints 21. The debounced count accepts a new level only once it has held for 10 ms: it prints 3.
- The timeline opens zoomed in on the first press, so the chatter shows. Change `DEBOUNCE_MS` to 0 and run again: with no wait, the debounced count is as wrong as the raw one.
:::
:::

```sim board
lang: c
attach: button P4 | press 0.1..0.25 s, 0.4..0.5 s, 0.7..0.8 s | bounce 4 ms
scope: P4 | 0.095..0.115 s
run: 1 s
show: debug
code:
#include "board.h"

#define DEBOUNCE_MS 10

uint32_t now_ms(void) { return SYS_CYCLES / 10000; }

int main(void) {
    GPIO_PULLUP = 1 << 4;
    int raw_count = 0, clean_count = 0;
    int last_raw = 1, stable = 1, candidate = 1;
    uint32_t since = 0, start = now_ms();
    while (now_ms() - start < 900) {
        int raw = (GPIO_IN >> 4) & 1;
        if (raw != last_raw) {          // every edge, bounces and all
            if (!raw) raw_count++;
            last_raw = raw;
        }
        if (raw != candidate) {         // the level changed: start timing it
            candidate = raw;
            since = now_ms();
        } else if (candidate != stable && now_ms() - since >= DEBOUNCE_MS) {
            stable = candidate;         // it held long enough: accept it
            if (!stable) clean_count++;
        }
    }
    print(raw_count);
    print(clean_count);
    return 0;
}
```

::: predict
## A button's contacts bounce 3 times on every press and 3 times on every release. How many falling edges does a fast program see for one press and release?

- [ ] 1
- [ ] 4
- [x] 7
- [ ] 12

::: reveal
7: the press gives its first closing plus 3 more as the contacts bounce closed again (4 falling edges), and the release, opening and closing 3 times on the way to open, gives 3 more. A count of presses taken from raw edges would read 7 for every real press.
:::
:::

::: nameit
## Contact bounce

Mechanical contacts typically bounce for 1 to 10 ms (cheap or worn ones longer) on both press and release. A program sampling faster than that sees every bounce.

## Software debouncing

- **Stable time:** accept a new level only after it has stayed unchanged for a time T longer than the bounce (10 to 20 ms). That's what the play's program does.
- **Counting samples:** sample every $T_s$ and accept a level after N equal samples in a row; it reacts $N T_s$ after the contacts settle.
- **Lockout:** act on the first edge immediately, then ignore the input for T. It responds fastest, but a noise spike counts as a press.

T has to be longer than the bounce and shorter than the quickest real presses a person makes (presses come at most about 10 per second).

## Hardware debouncing

A resistor and capacitor smooth the contacts' chatter into a slow ramp, $\tau = RC$, and a **Schmitt-trigger** input, with separate thresholds for rising and falling, turns the ramp into one clean edge. 10 kΩ and 1 µF give τ = 10 ms.
:::

::: example
## A debouncer samples every 2 ms and needs 5 equal samples in a row. How soon after the contacts settle does it react, at most?

::: solution
1. **Wait for the first settled sample.** That takes up to one sample interval.
2. **Then 4 more.** Five samples 2 ms apart take at most
   $$5 \times 2\ \text{ms} = 10\ \text{ms}$$
3. **What it ignores.** A press shorter than about 10 ms is ignored, which is what a debouncer should do with a 1 ms glitch.

**Answer:** at most 10 ms after the contacts settle.
:::
:::

::: example
## Can a lockout of 50 ms keep up with a person pressing as fast as they can?

::: solution
1. **How fast a person taps.** Fast tapping is about 10 presses per second, 100 ms apart.
2. **How long each part lasts.** Each press and release takes at least 30 to 50 ms.
3. **Compare with the lockout.** A 50 ms lockout after each edge still leaves room, though it's close.
4. **A safer choice.** 20 ms is a safer choice when the bounce is under 10 ms.

**Answer:** yes, though it's close; 20 ms is safer when the bounce is under 10 ms.
:::
:::

::: example
## A switch bounces for up to 8 ms. Why does simply sampling it every 10 ms debounce it?

::: solution
1. **Compare the spacing with the bounce.** Two samples are 10 ms apart, longer than any bounce, so at most one sample lands in a bounce.
2. **What that sample reads.** It reads either the old or the new state, both of which are legitimate, and the next sample is stable.
3. **The result.** The press is seen once, at most 10 ms late.
4. **The cost.** Very short presses, under 10 ms, may be missed.

**Answer:** at most one sample can land in the bounce, and whatever it reads is a legitimate state, so each press is seen once, at most 10 ms late.
:::
:::

::: check
given: p = 1 | 3 | 10; k = 2 | 3 | 5
answer: p*(1 + 2*k)
tolerance: 0

## A button's contacts bounce {k} times on every press and {k} times on every release. How many falling edges does a fast program see for {p} presses?

::: right
Right. $1 + 2k$ per press: {answer}.
:::

::: misses
- [p*(1 + k)] The release bounces too.
- [p] That's the presses; the program sees every bounce.
- [any] Not yet. Count the press's falls (1 plus the bounces) and the release's.
:::
:::

::: check
given: Ts = 1 | 2 | 5; N = 3 | 5 | 8
answer: N*Ts
unit: ms
tolerance: 0.5%

## A debouncer samples every {Ts} ms and accepts a level after {N} equal samples in a row. About how long after the contacts settle does it react?

::: right
Right. About $N T_s$ = {answer} ms.
:::

::: misses
- [Ts] One sample isn't enough: it waits for {N}.
- [any] Not yet. {N} samples at {Ts} ms each.
:::
:::

::: check
given: R = 4.7 | 10 | 47; C = 0.1 | 1 | 2.2
answer: R*C
unit: ms
tolerance: 0.5%

## A hardware debouncer uses {R} kΩ and {C} µF. What's its time constant?

::: right
Right. $RC$ = {answer} ms.
:::

::: misses
- [any] Not yet. τ = RC; kΩ times µF gives ms.
:::
:::

::: check
given: b = 2 | 5 | 10; m = 1.5 | 2 | 3
answer: b*m
unit: ms
tolerance: 0.5%

## The worst bounce measured is {b} ms. With a safety margin of {m}×, what stable time should the debouncer require?

::: right
Right. {answer} ms.
:::

::: misses
- [any] Not yet. Bounce time times the margin.
:::
:::

::: check
given: r = 5 | 10 | 15
answer: 1000/r
unit: ms
tolerance: 0.5%

## Someone presses a button {r} times a second. How far apart are the presses?

::: right
Right. {answer} ms: the debounce time must be well under this.
:::

::: misses
- [any] Not yet. One second over the rate.
:::
:::

::: check
kind: choice

## Which debouncing method responds to a press with the least delay?

- [ ] Waiting for the level to hold for 10 ms
- [ ] Counting 5 equal samples 2 ms apart
- [x] Acting on the first edge, then ignoring the input for a lockout time
- [ ] An RC filter with a 10 ms time constant

::: misses
- [1] It waits 10 ms after the bounce stops.
- [2] It waits for five samples.
- [4] The capacitor takes about a time constant to cross the threshold.
:::
:::

::: check
kind: micropython
attach: button P4 | press 0.1..0.2 s, 0.3..0.4 s, 0.5..0.6 s, 0.7..0.8 s | bounce 4 ms
run: 1
expect: print = 4

## The button on P4 (to ground, bouncing for 4 ms) is pressed 4 times in the first second. Count the presses, debounced, and print the count once, at 0.95 s.

```micropython starter
from machine import Pin
import time

button = Pin(4, Pin.IN, Pin.PULL_UP)
count = 0
last = 1
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < 950:
    now = button.value()
    if now != last and now == 0:
        count += 1
    last = now
print(count)
```

```micropython solution
from machine import Pin
import time

button = Pin(4, Pin.IN, Pin.PULL_UP)
count = 0
stable = 1
candidate = 1
since = time.ticks_ms()
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < 950:
    now = button.value()
    if now != candidate:
        candidate = now
        since = time.ticks_ms()
    elif candidate != stable and time.ticks_diff(time.ticks_ms(), since) >= 10:
        stable = candidate
        if stable == 0:
            count += 1
print(count)
```

::: right
Right. A new level counts only after it has held for 10 ms.
:::
:::

::: check
kind: c
attach: led P0; button P4 | press 0.1..0.2 s, 0.35..0.45 s, 0.6..0.7 s | bounce 5 ms
run: 0.9
expect: edges(P0) = 3; level(P0) = 1

## Make each press of the button on P4 (bouncing for 5 ms) toggle the LED on P0 exactly once.

```c starter
#include "board.h"

int main(void) {
    GPIO_DIR = 1 << 0;
    GPIO_PULLUP = 1 << 4;
    int last = 1;
    while (1) {
        int now = (GPIO_IN >> 4) & 1;
        if (now != last && !now) GPIO_TOGGLE = 1 << 0;
        last = now;
    }
}
```

```c solution
#include "board.h"

uint32_t now_ms(void) { return SYS_CYCLES / 10000; }

int main(void) {
    GPIO_DIR = 1 << 0;
    GPIO_PULLUP = 1 << 4;
    int stable = 1, candidate = 1;
    uint32_t since = now_ms();
    while (1) {
        int raw = (GPIO_IN >> 4) & 1;
        if (raw != candidate) {
            candidate = raw;
            since = now_ms();
        } else if (candidate != stable && now_ms() - since >= 10) {
            stable = candidate;
            if (!stable) GPIO_TOGGLE = 1 << 0;
        }
    }
}
```

::: right
Right. Three presses, three toggles, however much the contacts chatter.
:::
:::

::: check
kind: parts
given: T = 1 | 2 | 5; N = 3 | 5 | 8

## A debouncer samples every {T} ms and needs {N} equal samples in a row.

::: part
answer: T*N
unit: ms
tolerance: 0.5%

### At most how long after the contacts settle does it react?

::: misses
- [T*(N - 1)] Count the wait for the first sample too: N samples.
- [any] N samples × the period.
:::
:::

::: part
answer: 1000/(2*T*N)
unit: Hz
tolerance: 0.5%

### What is the fastest press-and-release rate it can follow, needing a full count for each?

::: misses
- [any] Each press and each release takes N samples.
:::
:::
:::

::: check
kind: parts
given: L = 20 | 50 | 150

## A debouncer ignores the button for {L} ms after each accepted press.

::: part
answer: 1000/L
tolerance: 0.5%

### At most how many presses a second can it accept?

::: misses
- [any] One per lockout.
:::
:::

::: part
answer: step(1000/L - 7)
tolerance: 0

### Can it keep up with a person pressing about 7 times a second (1 for yes)?

::: misses
- [any] Compare with 7.
:::
:::
:::

::: explain
## Why does a debouncer that waits for the input to stay unchanged for 10 ms ignore bounces but still catch every real press?

::: model
Bounces are rapid changes that last a few milliseconds at most: during a bounce the level never stays put for 10 ms, so every bounce restarts the timer and none is accepted. Once the contacts settle, the level stops changing, the timer runs to 10 ms, and the new level is accepted once. A real press holds the contacts closed for far longer than 10 ms, and presses are at least about 100 ms apart, so every press and every release eventually holds steady long enough to be counted, just 10 ms late.
:::
:::

::: practice

::: check
given: p = 2 | 6; k = 1 | 4
answer: p*(1 + 2*k)
tolerance: 0

## Falling edges for {p} presses bouncing {k} times each way?

::: misses
- [any] $p(1 + 2k)$.
:::
:::

::: check
given: Ts = 4 | 10; N = 2 | 4
answer: N*Ts
unit: ms
tolerance: 0.5%

## Reaction time, {N} samples at {Ts} ms?

::: misses
- [any] $N T_s$.
:::
:::

::: check
given: R = 22 | 100; C = 0.47 | 0.1
answer: R*C
unit: ms
tolerance: 0.5%

## τ for {R} kΩ and {C} µF?

::: misses
- [any] RC.
:::
:::
:::
