Why can one press of a push button register as several presses, and how is that fixed?
The metal contacts bounce: for a few milliseconds the switch opens and closes rapidly before it settles, so the pin sees several edges. Debouncing accepts a new state only after it has been stable for a while, typically 10-50 ms.
* The chip is fast enough to see every bounce as a separate edge. *
A mechanical contact is a springy piece of metal hitting another. It does not close cleanly. It rebounds a few times, and each rebound is a short open-close. A person sees one press, but the ESP32 samples in microseconds and sees a burst of transitions. Measurements of real switches find most bounces settle within about 10 ms. Some switches take far longer, especially when they open.
This matters most when the program counts presses or toggles on each one. A button meant to switch the LED on can switch it on, off, on and off in one press, and the result looks random. When the LED simply follows the button while it is held, the bounce only shows as a few milliseconds of flicker that nobody notices.
Fixes, in software or hardware:
- Sample slowly. Read the pin every 10-20 ms instead of continuously. Bounces shorter than the period are never seen.
- Wait for stability. On a change, wait about 20 ms and read again. Accept the new state only if it is still there.
- Lock out. After accepting an edge, ignore further edges for a short time.
- Hardware. An RC filter (resistor and capacitor) smooths the edges, ideally followed by a Schmitt-trigger input.
Go deeper:
Jack Ganssle — A guide to debouncing — oscilloscope measurements of real switches and the hardware and software fixes.
Wikipedia — Switch: contact bounce — why contacts bounce and the standard countermeasures.