Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 274 of 9364. Peripheral Interfacing and ControlFree lesson

Applying Debouncing Techniques for Mechanical Switches

Students will develop software routines to filter electrical noise and signal bouncing from physical buttons to ensure accurate input detection.

In this lesson, you will learn how to refine your button input logic to filter out electrical "chatter" caused by the physical limitations of mechanical switches.

When you press a mechanical button, the metal contacts inside don't connect perfectly on the first touch. Instead, they bounce against each other for a few milliseconds, creating a series of rapid high-low transitions that your microcontroller interprets as multiple button presses. If your code simply reads the GPIO input register, it will register these false events as distinct clicks.

To solve this, we implement a software debounce routine. The simplest approach is the "wait-and-verify" method. When you detect the initial change in state, you wait for a short, stable period—typically 10 to 50 milliseconds—using a hardware timer delay. After this delay, you read the input again to see if the signal has settled.

Here is how you might structure a basic polling-based debounce routine:

// Pseudo-code for debouncing an input
if (read_pin(BUTTON_PIN) == PRESSED) {
    // Wait for mechanical contact to settle
    delay_ms(20); 
    
    // Verify the state is still active
    if (read_pin(BUTTON_PIN) == PRESSED) {
        // Now safely process the button logic
        execute_button_action();
    }
}

By adding this short temporal buffer, you effectively ignore the initial mechanical chaos. If the pin is still in the active state after the 20ms delay, you can be statistically certain that the user intended a deliberate press rather than electrical noise. For more complex systems, you can move away from blocking delay_ms() calls by using timer interrupts to sample the pin state at regular intervals, confirming consistency over several consecutive polls. This ensures your system remains responsive while ignoring transient signal glitches.

Key Takeaway: Mechanical switches require a temporal delay or verification logic to filter out the rapid, transient electrical signals produced during the physical contact process, ensuring only intentional inputs are registered by your firmware.