The contact bounce of mechanical buttons (5-20ms high-frequency level fluctuations) is a common pain point in microcontroller input modules. If not addressed, it can lead to false triggering. This article focuses on a collaborative solution of hardware filtering and software algorithms, distilling the latest debouncing technology details from 2025, avoiding vague terms like ‘moderate selection’, and directly providing reproducible hardware parameters and code logic.

1. Hardware Debouncing: Low-Cost Physical Filtering
RC Filtering Circuit: Connect a 0.1μF ceramic capacitor in parallel across the button terminals and a 10kΩ resistor in series to ground. This utilizes the charging and discharging characteristics of the capacitor to smooth the bouncing waveform, typically reducing the bounce time to under 2ms.
Schmitt Trigger: Use chips like the 74HC14 to create a voltage hysteresis region, shaping the bouncing signal into a stable level, suitable for high-noise environments (such as industrial control scenarios).
Bistable Circuit: An RS flip-flop locks the state through a feedback mechanism, ensuring that even if the contacts bounce, the output remains unchanged, suitable for single buttons or simple matrix keyboards.
2. Software Debouncing: Precise Control at the Algorithm Level
Delay Debouncing Method: After detecting a level change, delay for 10-20ms (greater than the bounce time) and re-sample to confirm the state. For example, in 51 microcontroller code, debounce is achieved through delay_ms(15) + a second GPIO read.
Timer Interrupt Method: Utilize the microcontroller’s timer (like STM32’s TIM2) to trigger an interrupt every 1ms, confirming the key press as valid only if the accumulated press time exceeds a threshold (e.g., 12ms), avoiding main program blocking.
State Machine Method: Design a state machine with states IDLE→PRESS_DETECT→PRESS_CONFIRM→RELEASE_DETECT, which can be extended to recognize long presses, double clicks, and other complex operations, with clear and maintainable code logic.
3. Solution Selection and Optimization
Resource-Sensitive Scenarios: Prioritize hardware debouncing (like RC circuits) to reduce CPU usage; use software state machines when the number of buttons is high to avoid skyrocketing hardware costs.
High Real-Time Requirements: Use the timer interrupt method instead of simple delays to ensure the main program remains responsive (e.g., in motor control scenarios).
Interference Resistance Needs: Combine hardware filtering (Schmitt trigger) with software confirmation to form a dual insurance mechanism, suitable for harsh EMC environments.
This article is an original piece by Wanyi Education. Please indicate the source when reprinting!