Buttons and switches: clean digital inputs from noisy contacts

A push button is two metal contacts and a spring. When you push it, the contacts touch and connect two pins. The ESP32 cannot see “connected”. It only sees a voltage on a GPIO pin, so you must add a pull resistor that sets the level when the button is open. Real contacts also bounce: they open and close several times in the first milliseconds. Your code must debounce the signal, or one press becomes many presses. This page shows the wiring, the bounce, and code for clicks, double clicks, long presses and interrupts. The same rules apply to toggle switches, slide switches, limit switches and reed switches.

Three small tactile push buttons next to a ruler: a surface-mount button, a 6 mm through-hole button with a black cap, and a sealed button with a red cap
Tactile push buttons. The 6 mm through-hole type (middle) fits a breadboard.
Photo: Scwerllguy, CC BY-SA 3.0

Push the button and look at the pin

Click, double-click or hold
LED driven by the raw pin (pin is HIGH)
LED driven by the debounced state
Single click: release, then no second press for 400 ms. Double click: second press within 400 ms. Long press: hold for 800 ms.

Purple shading = your finger is on the button. Below: a zoomed view of the most recent edge. Each raw change starts the debounce timer again (yellow). The debounced output changes only when the timer completes.

How it works

Pull-up: active LOW

Connect the button between the GPIO and GND. Use pinMode(pin, INPUT_PULLUP). A resistor of about 45 kΩ in the chip holds the pin HIGH when the button is open. A press connects the pin to GND, so the pin reads LOW when pressed. This is the usual wiring, because you need no extra parts.

Pull-down: active HIGH

Connect the button between the GPIO and 3V3. Connect a 10 kΩ resistor from the GPIO to GND, or use INPUT_PULLDOWN. The pin reads HIGH when pressed. Use this wiring when a HIGH level must mean “on”. Never connect the button to 5 V, because the ESP32 pins accept 3.3 V maximum.

Floating inputs

A pin with no pull resistor is floating. Its level changes at random when your hand comes near, or when a wire moves. Select “None” in the simulator to see this. Always give each input a defined level with a pull-up or a pull-down.

Contact bounce

When the metal contacts hit, they spring apart and touch again several times. Bounce usually lasts 1–10 ms. Old, large or low-cost switches can bounce for 20 ms or more. Some switches also bounce when you release them. The ESP32 reads a pin in less than a microsecond, so it sees every bounce.

Software debounce

Time-based: accept a new level only after the pin is stable for a set time (5–50 ms). This is the method in the simulator. State machine: keep a state (released, maybe pressed, pressed, maybe released) and change state only after the timer. A lockout method acts on the first edge and then ignores the pin for some milliseconds. It reacts faster, but it also accepts noise spikes.

Edges and gestures

Usually you want to act once per press, so detect the edge: compare the debounced state with the previous state. “Released → pressed” is a press. “Pressed → released” is a release. Measure how long the button stays pressed to find a long press. Measure the time between two presses to find a double click.

Interrupts

An interrupt runs a function on each edge, also during delay(). Mark the function IRAM_ATTR and keep it very short. Bounce causes many interrupts for one press. Do not use delay() or Serial in the ISR. Save the time and set a flag, then debounce in loop() (sketch 4).

Hardware debounce

An RC filter slows the edges: a 10 kΩ pull-up and a 100 nF capacitor across the button give a time constant of 1 ms. Use 1 µF for about 10 ms. A slow edge can cross the input threshold several times, so add a Schmitt trigger buffer such as a 74HC14 (powered from 3.3 V). Add 100 Ω in series with the capacitor to limit the discharge current through the contacts.

Other switches

Toggle and slide switches stay in position. Read their level, and debounce the change. Limit switches (microswitches) have COM, NO and NC pins. Use COM and NC for safety stops: a broken wire then reads as “stop”. Use them with steppers and DC motors.

Wiring

ESP32 3V3 GPIO 26 GPIO 34 GPIO 27 GND 3V3 ≈45 kΩ inside B2 10 kΩ B2: active HIGH 3V3 10 kΩ B3 B3: active LOW B1 B1: INPUT_PULLUP, active LOW
B1 is the simplest wiring: one button from GPIO 27 to GND and the internal pull-up. B2 gives HIGH when pressed. B3 is on input-only GPIO 34. GPIO 34–39 have no internal pull resistors, so add an external 10 kΩ pull-up.

Connections

ButtonPin sideOther sidePressed reads
Sketch 1GPIO 25, INPUT_PULLUPGNDLOW
B1GPIO 27, INPUT_PULLUPGNDLOW
B2GPIO 26 + 10 kΩ to GND, INPUT3V3HIGH
B3GPIO 34 + 10 kΩ to 3V3, INPUTGNDLOW
TouchGPIO 4 (T0) to a metal pad—touchRead() value drops

A 4-pin tactile button has two pairs of pins that are always connected. Use two pins on diagonally opposite corners, so you always get the switched pair. Good inputs with internal pull resistors: GPIO 4, 13, 14, 16–19, 21–23, 25–27, 32, 33. Do not use the strapping pins 0, 2, 5, 12 and 15 for buttons (GPIO 2 is good as an LED output). Refer to GPIO.

Build steps

  1. Put the button across the center gapPush the 6 mm button into the breadboard across the center channel.
  2. Connect B1Connect one corner to GPIO 27. Connect the diagonal corner to GND.
  3. Upload sketch 2Open the Serial Monitor at 115200 baud. Push the button several times.
  4. Make the debounce time 0Change DEBOUNCE_MS to 0 and upload again. Count the extra presses.
  5. Add more buttonsUse one GPIO for each button. For many buttons, use sketch 5 with arrays.

Touch pins as buttons

Ten ESP32 pins have capacitive touch sensing. Connect a wire to a metal pad or foil. touchRead(4) gives a number that drops when you touch the pad (ESP32 classic). Measure the untouched value first. Then use a threshold at about 70 % of that value. Touch pins need no pull resistor and do not bounce, but they are sensitive to long wires and moisture.

Code

1 · Button-controlled built-in LED

Connect a button from GPIO 25 to GND (use diagonally opposite corners). The LED on GPIO 2 comes on while you push the button. The sketch accepts a new button state only after the pin is stable for 20 ms. This is the debounce.

button_led.ino


              const int BUTTON_PIN = 25;   // to GND
              const int LED_PIN = 2;       // built-in LED
              const unsigned long DEBOUNCE_MS = 20;

              int lastReading = HIGH;
              unsigned long lastChangeMs = 0;

              void setup() {
                pinMode(BUTTON_PIN, INPUT_PULLUP);  // pushed = LOW
                pinMode(LED_PIN, OUTPUT);
              }

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

                // The pin changed (or bounced): start the timer again.
                if (reading != lastReading) {
                  lastReading = reading;
                  lastChangeMs = millis();
                }

                // The pin did not change for 20 ms: use the reading.
                if (millis() - lastChangeMs >= DEBOUNCE_MS) {
                  if (reading == LOW) {
                    digitalWrite(LED_PIN, HIGH);  // pushed: LED on
                  } else {
                    digitalWrite(LED_PIN, LOW);   // released: LED off
                  }
                }
              }
            

Many ESP32 boards (for example the DOIT DevKit V1) have a blue LED on GPIO 2. Some boards, for example the Espressif DevKitC, have only a power LED. On those boards, connect an LED and a 220 Ω resistor from GPIO 2 to GND. To make the button switch the LED on and off with each push, use the edge detection in sketch 2.

2 · Debounce and edge detection

This sketch uses the same method as the simulator. It needs no library.

button_debounce.ino


              const int BTN_PIN = 27;              // button to GND
              const uint32_t DEBOUNCE_MS = 20;

              bool stableState = HIGH;             // debounced level (HIGH = released)
              bool lastReading = HIGH;
              uint32_t lastChangeMs = 0;
              uint32_t pressCount = 0;

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

              void loop() {
                bool reading = digitalRead(BTN_PIN);
                if (reading != lastReading) {      // the raw pin changed: restart the timer
                  lastReading = reading;
                  lastChangeMs = millis();
                }
                if (millis() - lastChangeMs >= DEBOUNCE_MS && reading != stableState) {
                  stableState = reading;           // stable for DEBOUNCE_MS: accept it
                  if (stableState == LOW) {        // edge: released -> pressed
                    pressCount++;
                    Serial.printf("Pressed (%lu)\n", pressCount);
                  } else {                         // edge: pressed -> released
                    Serial.println("Released");
                  }
                }
              }
            

3 · Click, double click and long press (OneButton)

Install OneButton by Matthias Hertel in the Library Manager. Call tick() often, so do not use long delay() calls in loop().

button_gestures.ino


              #include <OneButton.h>

              const int BTN_PIN = 27;
              // pin, activeLow = true, pullupActive = true (INPUT_PULLUP)
              OneButton button(BTN_PIN, true, true);

              void onClick()       { Serial.println("Single click"); }
              void onDoubleClick() { Serial.println("Double click"); }
              void onLongStart()   { Serial.println("Long press started"); }
              void onLongStop()    { Serial.println("Long press ended"); }

              void setup() {
                Serial.begin(115200);
                button.setDebounceMs(20);
                button.setClickMs(400);   // time to wait for a second click
                button.setPressMs(800);   // hold time for a long press
                button.attachClick(onClick);
                button.attachDoubleClick(onDoubleClick);
                button.attachLongPressStart(onLongStart);
                button.attachLongPressStop(onLongStop);
              }

              void loop() {
                button.tick();
              }
            

4 · Interrupt with debounce in loop()

The ISR only saves the time of the edge. A bounce makes the ISR run several times, but each run only updates the time. loop() reads the pin when the edges stop.

button_interrupt.ino


              const int BTN_PIN = 27;
              const uint32_t DEBOUNCE_MS = 20;

              volatile uint32_t lastEdgeMs = 0;
              volatile bool edgeSeen = false;
              bool stableState = HIGH;

              void IRAM_ATTR onEdge() {
                lastEdgeMs = millis();      // short: no delay(), no Serial
                edgeSeen = true;
              }

              void setup() {
                Serial.begin(115200);
                pinMode(BTN_PIN, INPUT_PULLUP);
                attachInterrupt(digitalPinToInterrupt(BTN_PIN), onEdge, CHANGE);
              }

              void loop() {
                if (edgeSeen && millis() - lastEdgeMs >= DEBOUNCE_MS) {
                  edgeSeen = false;
                  bool level = digitalRead(BTN_PIN);
                  if (level != stableState) {
                    stableState = level;
                    Serial.println(level == LOW ? "Pressed" : "Released");
                  }
                }
                // ... other work. The ISR catches the edge also during delay().
                delay(5);
              }
            

5 · Many buttons (Bounce2)

Install Bounce2 by Thomas O Fredericks. Each Bounce2::Button object debounces one pin.

buttons_bounce2.ino


              #include <Bounce2.h>

              const int PINS[] = {27, 26, 25, 33};
              const int N = sizeof(PINS) / sizeof(PINS[0]);
              Bounce2::Button buttons[N];

              void setup() {
                Serial.begin(115200);
                for (int i = 0; i < N; i++) {
                  buttons[i].attach(PINS[i], INPUT_PULLUP);
                  buttons[i].interval(20);            // debounce time in ms
                  buttons[i].setPressedState(LOW);    // active LOW wiring
                }
              }

              void loop() {
                for (int i = 0; i < N; i++) {
                  buttons[i].update();
                  if (buttons[i].pressed()) {
                    Serial.printf("Button %d pressed\n", i);
                  }
                  if (buttons[i].released()) {
                    // previousDuration() = how long the button was held
                    Serial.printf("Button %d released after %lu ms\n", i, buttons[i].previousDuration());
                  }
                }
              }
            

6 · Touch pad as a button

touch_button.ino


              const int TOUCH_PIN = 4;          // T0
              uint32_t threshold;
              bool touched = false;

              void setup() {
                Serial.begin(115200);
                delay(200);
                uint32_t sum = 0;
                for (int i = 0; i < 16; i++) sum += touchRead(TOUCH_PIN);
                threshold = (sum / 16) * 7 / 10;  // 70 % of untouched
                Serial.printf("Threshold: %lu\n", threshold);
              }

              void loop() {
                // ESP32 classic: a lower value = touched
                bool now = touchRead(TOUCH_PIN) < threshold;
                if (now != touched) {
                  touched = now;
                  Serial.println(touched ? "Touch" : "Release");
                }
                delay(20);
              }
            

On the ESP32-S2 and ESP32-S3, the touch value increases when you touch the pad. Change the comparison for those chips.

Troubleshooting

One press counts two or more times

This is contact bounce. Increase the debounce time to 20–50 ms. Make sure that you act on the debounced edge. Do not act on the level. If you use interrupts, debounce in loop().

Random presses with nothing pressed

The pin floats. Add INPUT_PULLUP or an external resistor. On GPIO 34–39 you must add an external 10 kΩ pull-up. For long wires, use a stronger external pull-up (4.7 kΩ) and a 100 nF capacitor.

The button always reads pressed

You used two pins of the 4-pin button that are always connected. Turn the button 90° or use diagonal pins. Also make sure that your code expects LOW for “pressed” with pull-up wiring.

Resources