Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Interrupts and Timers

Debouncing and Software Timers

Learn why mechanical switches bounce, how to debounce with sampling counters, and how to build many software timers from one hardware tick with wraparound-safe time math.

A hardware timer is a precious resource: a chip may have only three or four. But a program often needs dozens of time-based jobs: debounce a button, blink an LED, time out a serial reply, sample a sensor every 50 ms, keep a display on for five seconds. The standard answer is to run one hardware timer as a steady tick (usually 1 ms) and build any number of software timers on top of it.

This lesson covers two related skills that every firmware author needs: debouncing mechanical inputs, and designing software timers that keep working when the millisecond counter wraps around.

Why switches bounce

A push button is two pieces of metal that touch. When they close, they do not make a single clean contact; they spring apart and touch again several times for a few milliseconds (typically 1 to 20 ms, worse for old or cheap switches). A fast pin therefore sees a burst of edges: 0 1 0 1 1 0 1 1 1 1. If each edge raises an interrupt or increments a counter, one press registers as many.

Debouncing can be done in hardware (an RC filter and a Schmitt-trigger input) or in software. Software is free and flexible, and there are three common methods:

  1. Delay and re-check. After the first edge, wait about 20 ms and read the pin again. Simple, but a blocking delay stalls the whole program, so use it only in toy code.
  2. Sample counter (integrator). Sample the pin every millisecond. Only accept a new state after it has been stable for N consecutive samples.
  3. Shift-register history. Shift each sample into a byte or word and accept a change only when the history is all ones (pressed) or all zeros (released). Fast and compact; one byte per button.

All of them rely on a regular tick, which is what a timer interrupt provides (see timers, counters and PWM).

A sampling debouncer

The program below plays a recorded signal, one character per millisecond, with chatter at the press (around samples 6 to 12), a one-sample glitch in the middle, and chatter at the release. The debouncer keeps a counter and flips the stable state only after five identical samples.

C Debounce a bouncing button

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Compare the number of raw edges with the number of clean events: the chatter and the one-sample glitch disappear. The price is a delay of N milliseconds before a press is reported, so pick the smallest N that works for your switch (5 to 20 ms is typical). Longer is not better: users notice lag above roughly 50 to 100 ms.

Two refinements are common in real products. Press-and-hold detection counts how long the debounced state has been active, to distinguish a tap from a long press. Auto-repeat emits a repeated event every few hundred milliseconds while the button is held, as in a keyboard.

From one tick to many timers

Now the second half. Suppose a timer interrupt increments a 32-bit variable every millisecond:

C
static volatile uint32_t ms_ticks;

void SysTick_Handler(void) {     // read-only sketch: runs every 1 ms
    ms_ticks++;
}

uint32_t millis(void) {          // 32-bit read: atomic on Cortex-M, not on 8-bit parts
    return ms_ticks;
}

A software timer stores a start time and a duration and asks whether enough time has elapsed. The obvious code compares absolute times:

C
if (millis() >= start + timeout) { ... }     // WRONG near the wrap

This breaks when start + timeout overflows. A 32-bit millisecond counter wraps after about 49.7 days. A device that has to run for months will hit the wrap, and the bug will appear exactly then, perhaps in the field.

The robust method uses unsigned subtraction:

C
if ((uint32_t)(millis() - start) >= timeout) { ... }     // correct, even across the wrap

Unsigned arithmetic is modular in C, so now - start gives the elapsed time even if now has wrapped past zero, as long as the real elapsed time is smaller than half the counter range (about 24.8 days for a 32-bit millisecond counter). Always compare durations, never timestamps.

The next program builds a small timer service on this idea. It supports periodic and one-shot timers with callbacks, and the simulated clock starts just below the wrap point so you can watch the wraparound being handled.

C A software timer service with wraparound

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The "blink" timer fires 10, 20 and 30 ms after the start (the second firing happens right after the clock wraps to 4) and "timeout" fires once, at 25 ms, even though the clock passes through zero at the sixteenth tick. The loop stops at 39 ms, so a fourth blink is never reached. Note t->last += t->period_ms rather than t->last = now. Setting last to the current time would add the loop's lateness to every period; adding the period keeps the average rate exact.

Design notes

  • Tick resolution. 1 ms suits most control and UI work. Faster ticks cost more interrupt overhead; slower ones make timers coarse.
  • Where to run callbacks. Run them from the main loop (as above), not inside the tick ISR, so they are free to take longer and need no volatile care.
  • Overruns. If a callback takes longer than the period, the timer is "late" and fires again immediately on the next pass. Log or count that situation in production code.
  • Absolute deadlines vs. delays. For a fixed-rate loop, advance an absolute target (next += period) instead of waiting period after each iteration. It prevents drift.
  • Low power. A software tick wakes the CPU every millisecond, which is expensive. Low-power designs use a tickless approach: program the hardware timer for the next deadline and sleep until then (see low-power design).

Common mistakes

  • Using a blocking delay_ms(20) for debouncing and freezing the rest of the program.
  • Comparing timestamps (now >= deadline) instead of durations, which fails across the wrap.
  • Using a 16-bit tick counter on a 1 ms tick: it wraps every 65 seconds, and the half-range limit is only 32 seconds.
  • Debouncing in the interrupt that counts the edges, so every bounce still costs an interrupt. Prefer a timer-driven sampler, or disable the pin interrupt for the debounce time.
  • Forgetting that two events can fall in the same tick and handling only one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a mechanical button need debouncing?

    The metal contacts spring apart and reconnect, so the input toggles several times before settling.
  2. 2. Which expression correctly checks that 100 ms have passed since 'start', even if the 32-bit tick counter wrapped?

    Unsigned subtraction is modular in C, so the elapsed time is correct across the wrap, as long as it is under half the counter range.
  3. 3. After how long does a 32-bit counter incremented every millisecond wrap around?

    2^32 ms is about 4.29 million seconds, or 49.7 days.
  4. 4. In the timer service, why use 'last += period' instead of 'last = now' when a timer fires?

    Using now would add any lateness of the check to every period, so the timer would slowly slow down.

Summary

  • Switch contacts bounce for milliseconds; accept a new state only after it has been stable for several samples.
  • Run one hardware tick and build many software timers on it, executing callbacks from the main loop.
  • Compare durations with unsigned subtraction so timers survive counter wraparound.
  • Advance deadlines by the period to avoid drift, and move to tickless timing when power matters.

Next: UART and Serial Communication