Switch Debouncing Explained: What Contact Bounce Looks Like and How to Filter It in Hardware or Firmware
Why a single button press can register as several, what measured bounce actually looks like, and how RC filters, SR latches and timer-driven firmware each remove it, with a runnable Arduino debouncer.
A pushbutton looks like the simplest input a microcontroller can have: closed or open, one bit. In practice, a mechanical switch does not move cleanly between those two states. When metal contacts meet, they collide, rebound and chatter for a short time before settling, and a fast digital input faithfully reports every one of those rebounds. The result is the classic embedded bug: one press increments a counter by three, a menu skips two entries, or a remote control jumps past the channel the user wanted. Removing that chatter is called debouncing, and it can be done with a few passive parts, with a logic gate, or entirely in firmware.
What bounce actually looks like
The most widely cited measurements come from embedded systems consultant Jack Ganssle, who put 18 different switches on an oscilloscope, including pushbuttons, toggles, slide switches and joystick buttons, and actuated them in many different ways. Excluding two badly behaved parts, the remaining 16 averaged about 1.6 ms of bounce, with a worst case of 6.2 ms. One switch bounced for up to 157 ms when opening while barely bouncing at all when closing, and one took 11.3 ms to close fully on a single trial. Two supposedly identical switches of the same model differed by a factor of two.
Several findings from that work matter more than the averages:
- Bounce happens on release as well as on press, and some switches are worse in one direction than the other.
- The same switch can produce sub-microsecond glitches on one actuation and hundreds of microseconds of chatter on the next, so a few test presses on the bench prove very little.
- Much of the noise is not clean ones and zeros. The contact voltage can wander through the region between valid logic low and valid logic high, where a digital input may read either value at random.
- Very short pulses, some under 100 ns, are common, which is fast enough to trigger edge-sensitive logic many times per press.
The practical conclusion is to design for bounce that is worse than anything measured. Most switches settle in under 10 ms, but a debounce window in the range of 20 to 50 ms leaves margin for wear, temperature and the occasional unusual part, while still feeling instantaneous to a person pressing the button.
Option 1: an RC filter into a Schmitt trigger
The classic hardware fix for a single-pole, single-throw switch is a resistor and capacitor that slow the signal down. While the switch is open, the capacitor charges through a pull-up path. When the switch closes, the capacitor discharges through a resistor rather than instantly, so brief rebounds only nudge the voltage instead of slamming it between rails. The time constant, R multiplied by C, sets how long the filtered voltage takes to cross the input threshold, and it should be comfortably longer than the bounce period.
The catch is that the filter output is now a slow analog ramp, and a slow ramp passing through the undefined region of an ordinary logic input can make that input oscillate. That is why the filtered node should drive a gate with hysteresis, such as a 74HC14 or 74AHCT14 Schmitt-trigger inverter, or a microcontroller pin whose datasheet guarantees Schmitt-trigger input behaviour. Hysteresis gives the input two different switching thresholds, one for rising and one for falling signals, so a slowly changing voltage produces exactly one clean transition.
A worked RC example
In Ganssle's worked design, a 5 V supply feeds a 74AHCT14 inverter and the target debounce time is about 20 ms. Choosing the capacitor first is sensible because capacitor size and cost vary more than resistor values. With C = 1 µF, the discharge resistor works out to about 18 kΩ, which gives a discharge time constant of 18 kΩ × 1 µF = 18 ms. The charging path runs through both resistors and needs roughly 100 kΩ in total, so an 82 kΩ pull-up plus the 18 kΩ resistor completes the design. Trying C = 0.1 µF instead would push the discharge resistor to around 180 kΩ, high enough that leakage current at the input starts to shift the voltage noticeably. Component tolerances matter too: resistors are commonly ±5 percent, while electrolytic capacitors can be off by +80/−20 percent, so leave generous margin.
Option 2: an SR latch for double-throw switches
If the switch is single-pole, double-throw, meaning it has two fixed contacts and a moving arm that touches one or the other, there is a cleaner hardware answer. Two cross-coupled NAND gates form a set-reset latch, with each fixed contact pulled up and the arm connected to ground. When the arm first touches a contact, the latch flips. Bounce makes the arm leave and re-touch that same contact, but it never travels far enough to reach the opposite one, so the latch simply holds its state. The output has no delay and no time constant to tune. The cost is a more expensive, bulkier switch and an extra gate package, although the same logic works in firmware by wiring both contacts to two input pins.
Option 3: debounce in firmware
Most modern designs skip the extra parts and filter in software, since an input pin and a few bytes of RAM are nearly free. The method that holds up best is periodic sampling: read the raw pin at a fixed interval, typically every 1 to 5 ms, and only accept a new state after it has been seen consistently for the whole debounce window. Driving the sampling from a timer or a millisecond clock, rather than from busy-wait delay loops, keeps the timing independent of compiler settings and clock speed, and leaves the processor free for other work.
The sketch below implements that idea for an Arduino-compatible board. The button connects pin 2 to ground and uses the internal pull-up, so the pin reads HIGH when released and LOW when pressed. Every 5 ms the code takes one sample; six consecutive samples that disagree with the current debounced state, about 30 ms in total, are required before the state changes. Any sample that agrees with the current state resets the count, so bounce keeps restarting the window instead of slipping through.
const uint8_t BUTTON_PIN = 2; // button between pin 2 and GND
const unsigned long SAMPLE_MS = 5; // sample period
const uint8_t STABLE_SAMPLES = 6; // 6 x 5 ms = 30 ms debounce window
int stableState = HIGH; // debounced level, HIGH = released
uint8_t agreeCount = 0; // consecutive samples that differ from stableState
unsigned long lastSample = 0;
unsigned long pressCount = 0;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
unsigned long now = millis();
if (now - lastSample < SAMPLE_MS) return;
lastSample = now;
int raw = digitalRead(BUTTON_PIN);
if (raw == stableState) {
agreeCount = 0; // still in the old state, or bounce: restart
} else if (++agreeCount >= STABLE_SAMPLES) {
stableState = raw; // new state held for the whole window
agreeCount = 0;
if (stableState == LOW) { // act on the press edge only
pressCount++;
Serial.print("press ");
Serial.println(pressCount);
}
}
}Two details in that code are deliberate. The elapsed-time check uses now - lastSample with unsigned arithmetic, which stays correct when the millisecond counter wraps around after 2^32 ms, roughly 49.7 days. And the press action fires on the debounced edge rather than on the raw level, so holding the button down produces one event, not a stream of them. To debounce press and release with different windows, keep two thresholds and choose between them based on the current state.
The shift-register variant
A compact alternative shifts each new sample into an integer and compares the result against a pattern. With a 16-bit variable, a press can be declared when the last dozen samples were all closed after an earlier open reading, which is a single shift, OR and compare per sample. The same structure maps neatly onto assembly or FPGA logic. For many buttons on one port, a short circular buffer of whole-port readings can be ANDed together to find bits that have been stable for every sample, and XORed against the previous result to find which ones changed.
Common mistakes
- Wiring an undebounced switch to an edge-triggered interrupt pin. Each bounce can fire the interrupt, and very short glitches can violate the minimum pulse width of the input logic. If an interrupt is needed, for example to wake from sleep, debounce in hardware first or use the interrupt only as a wake-up and then switch to timed sampling.
- Reading the pin twice a few milliseconds apart and calling it debounced. Two agreeing samples can both land inside a burst of noise.
- Using a one-shot (monostable) timer as a debouncer. It turns each press into a fixed-length pulse rather than a clean change of state, which is usually not what the rest of the design expects.
- Connecting an RC filter straight to a non-Schmitt logic input, which can make the slow ramp oscillate at the threshold.
- Choosing a window from a handful of bench presses. Bounce varies between units, directions, temperature and age, so pick a window several times longer than anything observed.
Choosing an approach
For most microcontroller projects, timer-driven firmware sampling with a 20 to 50 ms window is the default: it costs no parts and handles any number of buttons. Reach for an RC filter and Schmitt trigger when the signal feeds an interrupt, a counter or logic with no processor in the loop, or when firmware cannot spare the cycles. Use an SR latch when a double-throw switch is already in the design and zero added delay matters. Whichever route is chosen, test it with deliberately sloppy presses, slow releases and long holds, because bounce rarely appears during a careful demo and almost always appears in the field.
The guiding principle from the measurement work is simple: assume the switch is worse than any test suggests, and give the filter enough margin to survive it.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter