ABC of Electronics cosycom.com
ESP32 BASICS · LESSON 05

Digital Input: Reading a Push Button

Pull-up and pull-down resistors, debouncing, and reading a switch without weird false triggers.

A push button is just a switch: pressed, it connects two points; released, it doesn't. The tricky part isn't the button — it's making sure the pin reads a clean, unambiguous level when the button isn't pressed.

Button GPIO pin digitalRead() if statement Signal path from switch to program

Pull-up vs pull-down

An input pin left floating (connected to nothing) picks up electrical noise and reads randomly. A pull-up or pull-down resistor fixes the "released" state to a known level. The ESP32 has internal pull-up and pull-down resistors you can enable in software, which usually means no external resistor is needed at all.

button.ino
#define BUTTON_PIN 14

void setup() {
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
  bool pressed = digitalRead(BUTTON_PIN) == LOW;
  if (pressed) {
    Serial.println("Button pressed");
    delay(200); // crude debounce
  }
}

Debouncing

A mechanical switch's contacts bounce for a few milliseconds when pressed, which can register as several presses instead of one. A short delay after detecting a press is a quick fix; a more robust approach tracks the time since the last change and only accepts a new state after it's been stable for a few milliseconds.

KEY IDEA
With INPUT_PULLUP, the logic is inverted: the pin reads HIGH when the button is untouched and LOW when pressed.