Generating PDF…

Preparing…
← Back

Microcontrollers 1

Lecture: Switch Debouncing

Table of Contents

  • The Problem: What is Switch Bounce?
  • Visualizing the Problem
  • Solution 1: Hardware Debouncing (RC Filters)
  • Live Demo: Hardware Debouncing in Action
  • Solution 2: Software Debouncing
  • Live Demo: Software Debouncing in Action
  • Advanced Topic: Schmitt Triggers
  • Summary & Next Steps

Circuit Design: Simple Switch

The first step is drawing a sketch of the switch circuit.

Simple Switch Circuit Sketch

Circuit Design: Actual Switch Circuit

Now let's use GPIO 8 as input that is connected one swith end.

Physical Switch Photo
Physical switch used in the circuit
// Pin where the button is connected
const int buttonPin = 8;  

void setup() {
  // Initialize Serial communication
  Serial.begin(9600);

  // Configure button pin as input with internal pull-up resistor
  pinMode(buttonPin, INPUT_PULLUP);

  Serial.println("Ready! Press the button...");
}

void loop() {
  // Read the button state (LOW when pressed if using INPUT_PULLUP)
  int buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    Serial.println("Button pressed!");
    delay(200);  // small delay to avoid multiple prints due to bouncing
  }
}

The Problem: What is Switch Bounce?

When you press a mechanical switch, the metal contacts don't connect perfectly and instantly.

  • They physically "bounce" against each other for a few milliseconds before settling.
  • This creates a very noisy electrical signal.
  • Instead of one clean transition from HIGH to LOW, you get a series of rapid transitions.

Visualizing Switch Bounce

An oscilloscope trace of a single button press without debouncing looks like this:


  HIGH  +-------+       +---+     +-------
        |       |       |   |     |
  VOLT  |       +---+---+   +--_--+
        |           |
   LOW  +-----------+--------------------->
                             TIME
        

The microcontroller is so fast that it might read this single press as three, four, or more separate presses.

Solution 1: Hardware Debouncing

We can solve bouncing by adding a simple circuit to filter out the noise.

  • The most common method is an RC (Resistor-Capacitor) low-pass filter.
  • This circuit slows down the voltage transitions, effectively "absorbing" the quick bounces.

The circuit consists of a pull-up resistor and a capacitor to ground on the signal line.

The RC Filter's Effect

The RC filter turns the noisy, bouncy signal into a smooth, clean transition.


  Ideal Signal      Bouncy Signal       Filtered Signal
  +-----+           +--+ +-+            +------_
  |     |           |  | | |            |       '
  |     |           |  +-+ +--          |        '
  |     |           |                   |         \
  +-----+           +---------          +----------'
        

The capacitor resists instantaneous changes in voltage, smoothing out the curve.

Bench Demo: Setup

We will now look at a real switch on the bench connected to an oscilloscope.

Setup 1: No Debouncing

  • A momentary switch is connected with a pull-up resistor.
  • The filtering capacitor is disconnected.
  • We will observe the output on the oscilloscope when the button is pressed.

Bench Demo: Observing the Bounce

Result:

As seen on the oscilloscope, a single press creates a very "ugly" and noisy signal.

  • Multiple sharp spikes are visible.
  • The signal rapidly transitions between HIGH and LOW several times before settling.
  • This is the mechanical bounce we need to eliminate.

Bench Demo: Applying the Fix

Setup 2: Hardware Debouncing

  • We will now connect the capacitor from the signal line to ground.
  • This completes the RC filter circuit.
  • The components used are a 1kΩ pull-up, a 100Ω series resistor, and a 1µF capacitor.

Bench Demo: The Result

Result:

The oscilloscope now shows a clean, beautiful transition.

  • The rapid bounces are gone.
  • The signal now follows a smooth, exponential charge/discharge curve.
  • This is a reliable signal that the microcontroller can read accurately as a single event.

Solution 2: Software Debouncing

If you can't or don't want to add extra hardware, you can handle debouncing in your code.

The Core Idea:

  1. Detect a change in the button's state (e.g., from HIGH to LOW).
  2. When a change is detected, start a timer.
  3. Ignore any further changes from that button for a short period (e.g., 50-100 milliseconds).
  4. After the delay, read the button state again. This final state is considered the stable, debounced state.

Software Debouncing: Code

To implement this, we need to keep track of the button's state and time between reads.

We use static variables so they retain their values between calls to the `loop()` function.

// Variables to hold the switch states
static int switchCurrentState = 0;
static int switchLastState = 0;

// Variable to store the time of the last state change
static unsigned long switchDebounceStartTime = 0;

// The debounce delay period in milliseconds
long debounceDelay = 100;

Software Debouncing: Logic

Inside the loop, we read the switch and compare its current state to its last known state, but only after a delay.

The `millis()` function returns the number of milliseconds since the Arduino started.

// Read the current physical state
switchCurrentState = digitalRead(SWITCH_PIN);

// Check if the state has changed
if (switchCurrentState != switchLastState) {
    // If it has changed, reset the debounce timer
    switchDebounceStartTime = millis();
}

Software Debouncing: Final Check

After a state change is detected and the timer is reset, we wait for the `debounceDelay` period to pass. If the button state is still the same after the delay, we can trust it as a valid press.

if ((millis() - switchDebounceStartTime) > debounceDelay) {
    // If 100ms has passed and the state is stable...
    // then the current state is the "real" state.
    // You can now act on the button press here.
    
    // Example: Print the stable state
    if(switchCurrentState == LOW) {
        Serial.println("Button Pressed!");
    }
}

// Update the last state for the next loop iteration
switchLastState = switchCurrentState;

Software Demo: In Action

Let's upload the code and observe the Serial Monitor.

  • With a 100ms delay, pressing and releasing the button on the rotary encoder gives a clean output.
  • `State is 0` (Pressed)
  • `State is 1` (Released)
  • No matter how quickly the button is pressed, we don't see multiple "0" or "1" outputs for a single action. The software successfully filters the bounce.

Tuning the Delay

The `debounceDelay` value is important:

  • Too Short: If the delay is too short (e.g., 10ms), you might still "catch" a mechanical bounce and register a false press.
  • Too Long: If the delay is too long (e.g., 2000ms), the button will feel unresponsive. You could press and release it within the delay period, and the event would be completely missed.

A value between 50ms and 150ms is typically a good starting point.

Hardware vs. Software

Which method is better?

Hardware Debouncing (RC Filter)

  • Pros: Offloads work from the CPU. "Fire and forget" solution. The signal is clean before it even reaches the microcontroller.
  • Cons: Requires extra components, cost, and board space.

Software Debouncing

  • Pros: No extra components needed. Flexible and easy to adjust timing.
  • Cons: Uses CPU cycles and adds complexity to the code.

Hardware is often preferred for reliability, but software is extremely common due to its cost-effectiveness.

Advanced Topic: Schmitt Triggers

A downside of RC filters is that they create slow, rounded signal edges.

  • Some digital logic inputs require very fast, sharp edges to function correctly.
  • A slow-rising signal can cause oscillations or unpredictable behavior at the input gate.

A Schmitt Trigger is a hardware solution to this problem.

What is a Schmitt Trigger?

A Schmitt trigger is a special type of input that "cleans up" signals.

  • It takes a slow-moving or slightly noisy input and converts it into a clean, sharp digital output.
  • It uses a concept called hysteresis.

    Slow/Noisy Input          Schmitt Trigger Output
         ,---.
       ,'     `.                    +-----------+
      /         \                   |           |
    -'           `-.                |           |
                     `---           |           |
                                    +-----------+
            

Hysteresis Explained

Hysteresis means there are two different voltage thresholds: one for a rising signal and one for a falling signal.

  • Rising Threshold (VT+): The input must rise ABOVE this voltage for the output to switch HIGH.
  • Falling Threshold (VT-): The input must fall BELOW this (lower) voltage for the output to switch LOW.

This gap between thresholds provides excellent noise immunity. Small fluctuations around a threshold won't cause the output to chatter.

The 7414 Schmitt Trigger IC

A classic and common component for this task is the 7414 Hex Schmitt-Trigger Inverter.

  • It's an integrated circuit (IC) that contains six inverters, each with a Schmitt trigger input.
  • You feed your filtered (but slow-edged) signal into one of the inverters.
  • The output will be a clean, sharp, and inverted signal, perfect for connecting to other digital logic.

The symbol for a Schmitt trigger input on a schematic often includes a small hysteresis loop inside the logic gate symbol.

The Ultimate Hardware Solution

For a robust, mission-critical input, you can combine these techniques:

Switch Output → RC Filter → Schmitt Trigger → Microcontroller Input

  1. The RC Filter removes the high-frequency mechanical bounces.
  2. The Schmitt Trigger takes the resulting slow-edged signal and converts it back into a fast, clean digital signal.
  3. The Microcontroller receives a perfect signal, and the software doesn't need any complex debouncing logic.

Lecture Summary

  • Mechanical switches produce "bounces"—noisy signals that can be misread by a microcontroller.
  • Hardware Debouncing uses an RC filter to physically smooth the signal. It's robust but requires extra components.
  • Software Debouncing uses a timer-based algorithm to ignore rapid signal changes. It's free but uses CPU resources.
  • Schmitt Triggers are used to clean up slow or noisy signals, providing sharp edges and noise immunity through hysteresis.