5 V10 kΩ01MCUATmega328Pcount0quiet-1void loop() {2 int r = digitalRead(BTN);3 if (r != last && r == LOW)4 count++;5 last = r;6}1void loop() {2 int r = digitalRead(BTN);3 if (r != last) t0 = millis();4 last = r;5 if (millis() - t0 > 506 && r != state) {7 state = r;8 if (r == LOW) count++;9 }10}01+1
0123405ms after the first touchvoltsPIN 2, ZOOMED INpin54 ms: count 10102030405060LOWHIGHms after the first touchTHE WHOLE PRESSpinstate
Back: 5 V, pull-up, button to ground, the pin-2 lamp and the chip with count and quiet timeFront: the firmware card, naive loop() first, then the debounced oneTokens: reads hopping into the chip and +1 hopping into count; the plots are computed from the modelA push button on pin 2 of an Arduino Uno R3, with a 10 kΩ pull-up: released reads HIGH, pressed reads LOW. The contacts bounce (4 touches in 3.1 ms in this example), so a loop() that counts every change counts 4. The debounced loop() waits until the reading has been quiet for more than 50 ms and counts 1, at 54 ms. The plots are computed from the same model.

The circuit

  1. The button sits between pin 2 and ground. A 10 kΩ pull-up resistor ties the pin to 5 V, as in the lesson on pull-up resistors. Released, nothing joins the pin to ground, so digitalRead gives HIGH: 1.

The problem: bounce

The fix: wait for quiet

What happens

// step 1/9 · circuit
board     Arduino Uno R3 (ATmega328P)
pin 2     pinMode(BTN, INPUT), 10 kOhm pull-up to 5 V
button    from pin 2 to GND
released  pin pulled up to 5 V  ->  HIGH (1)

The bounce in the figure is one example, drawn to scale as clean steps: 4 touches in 3.1 ms. Real contacts also give fuzzy voltages in between, and every press is different. Ganssle's 18 switches averaged 1557 µs, but two of them bounced for over 6.2 ms. The card shows only loop(). The whole sketch also declares last, state, t0 and count, and sets pinMode(BTN, INPUT) in setup(), because the 10 kΩ resistor is outside the chip. With no resistor you would use INPUT_PULLUP, which turns on the chip's own pull-up.