Lesson 3 / 8
Module 2Lesson 3⏱ 45 min study

Digital Input/Output, Pull-Ups & Mechanical Switch Debouncing

Understand electrical logic levels, configure digital pin registers, prevent floating inputs using internal pull-up resistors, and implement robust software contact debouncing.

✦ Key Architectural Takeaways
  • •Digital pins operate in two discrete voltage states: HIGH (5V, logic 1) and LOW (0V, logic 0)
  • •An unconnected digital input pin is in a 'floating' high-impedance state, picking up ambient electromagnetic noise and fluctuating randomly between HIGH and LOW
  • •Configuring INPUT_PULLUP engages the internal 20k to 50k ohm resistor tied to 5V VCC, holding the pin reliably at HIGH until an active-low switch closes to Ground
  • •Mechanical switch contacts physically bounce for 5 to 20 milliseconds upon closing; software debouncing verifies state stability across a time window before registering a press

## Interfacing with the Physical World: Digital Logic

In digital electronics, binary numbers represent electrical voltage states. On standard 5V Arduino boards:

  • Logic HIGH (1): Defined as any voltage between 3.0V and 5.0V (typically 5V).
  • Logic LOW (0): Defined as any voltage between -0.5V and 1.5V (typically 0V / Ground).

Connecting external electrical components requires careful circuit analysis to prevent exceeding the microcontroller's physical current limitations.

§

1. Electrical Limits & Ohm's Law for LEDs

Every I/O pin on the ATmega328P can sink or source a maximum of 40 mA, with 20 mA recommended for continuous safe operation. Driving an LED without a current-limiting resistor creates a direct short circuit, permanently destroying the microcontroller pin driver!

TEXTSYSTEM SCHEMATIC
  CALCULATING CURRENT-LIMITING RESISTOR (OHM'S LAW):
  
  Supply Voltage (Vs)  = 5.0 Volts (Arduino pin HIGH)
  LED Forward Voltage (Vf) = 2.0 Volts (Standard Red LED)
  Desired Forward Current (If) = 15 mA (0.015 Amperes)

  Voltage across resistor (Vr) = Vs - Vf = 5.0V - 2.0V = 3.0 Volts
  
         Vr       3.0 V
  R = -------- = --------- = 200 Ohms  ===> Standard 220 Ohm Resistor!
         If      0.015 A
§

2. The Floating Pin Hazard & Internal Pull-Up Resistors

When a digital pin is configured as pinMode(pin, INPUT), its input resistance is extremely high (~100 Megaohms). If no voltage source is connected, the wire acts as a radio antenna, picking up electrostatic fields from fluorescent lights, power cables, and human fingers:

TEXTSYSTEM SCHEMATIC
  FLOATING INPUT CIRCUIT (UNRELIABLE):
  Arduino Pin D2 <-----------+----------- (Pushbutton) -----------> +5V
                             |
                   (When switch is OPEN, pin D2 is connected to NOTHING!
                    Voltage floats unpredictably between 0V and 5V)

  INTERNAL PULL-UP CIRCUIT (STABLE & RELIABLE):
  Arduino Pin D2 <-----------+----------- (Pushbutton) -----------> GND
                             |
                  [ Internal 30k Resistor ]
                             |
                            +5V VCC
  - When switch is OPEN: Internal resistor pulls Pin D2 to steady +5V (HIGH).
  - When switch is PRESSED: Closes to GND; Pin D2 drops to steady 0V (LOW).
  - This is an ACTIVE-LOW configuration: LOW = Pressed, HIGH = Released!
§

3. Switch Contact Bounce Physics & Software Debouncing

Mechanical pushbuttons and switches consist of flexible metal contacts. When pressed, the contacts do not make clean instantaneous electrical contact; they physically strike each other and bounce for 5 to 20 milliseconds before settling:

TEXTSYSTEM SCHEMATIC
  ELECTRICAL VOLTAGE GRAPH OF MECHANICAL SWITCH BOUNCE:
  
  5V (HIGH) ---                                  /-----------------
                  /  /                        /
                 /  /                        /
  0V (LOW)  ---------------+--------------------+-------------------
            |<--- 10-20ms Bouncing --->| Stable PRESSED State |

If a microcontroller counts pulses directly, a single human button press may register as 15 to 25 separate button presses!

Robust Non-Blocking Debounce Implementation

CPPSYSTEM SCHEMATIC
// =============================================================================
// PRODUCTION NON-BLOCKING BUTTON DEBOUNCE ALGORITHM
// =============================================================================

const uint8_t BUTTON_PIN = 2; // Connected to GND (Active-Low)
const uint8_t LED_PIN = 13;

int buttonState = HIGH;         // Current filtered button state
int lastReading = HIGH;         // Previous raw electrical reading
uint32_t lastDebounceTime = 0;  // Last time the reading flickered
const uint32_t DEBOUNCE_DELAY = 50; // 50ms debounce stability window

void setup() {
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
}

void loop() {
    int rawReading = digitalRead(BUTTON_PIN);

    // If electrical reading changed due to noise or pressing, reset timer
    if (rawReading != lastReading) {
        lastDebounceTime = millis();
    }

    // Check if the reading has remained stable longer than debounce delay
    if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
        // If state has meaningfully changed
        if (rawReading != buttonState) {
            buttonState = rawReading;

            // Trigger action on transition to PRESSED (active-low LOW)
            if (buttonState == LOW) {
                digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED
            }
        }
    }

    lastReading = rawReading;
}