Digital Inputs and Debounce
Digital Inputs and Debounce
Overview
Section titled “Overview”Buttons, limit switches, hall sensors and the press-switch on a joystick are all digital inputs: a level changes, nothing more. The hard part is making sure “one press” is read exactly once. By the end of this section you will be able to:
- Configure GPIO internal pull-up/pull-down and decide which scheme your module needs
- Remove 5–10 ms contact bounce in software without using
delay() - Handle a module that presents three inputs at once (joystick: two analogue plus one digital)
- Wake an ESP32 from deep sleep with a button, and know why only certain pins can do it
Prerequisites
Section titled “Prerequisites”Before starting this section, make sure you:
- Completed Section 1 of Chapter 25 and can apply the four-question framework
- Have a 2- or 3-pin button module and a two-axis joystick module (PS2 style)
- Have a PlatformIO or Arduino IDE project set up (see Chapter 02)
Key Concepts
Section titled “Key Concepts”A button is not a sensor, but treat it as a signal source
Section titled “A button is not a sensor, but treat it as a signal source”Strictly speaking a button is not a sensor — it is a digital input device that pulls one node to the other rail when pressed. It still carries the engineering problems common to every digital input, which is why it opens this chapter.
Three typical pin-outs:
| Form | Pins | Fixed biasing on board | Usage note |
|---|---|---|---|
| Bare switch (2 pins) | 2 | No | You must provide a pull-up/pull-down, internally or externally, otherwise the pin floats and jitters |
| 3-pin module | VCC/GND/OUT | Yes (on-board pull-up plus comparator) | Check the module documentation for active-high or active-low |
| Key module with LED | 3–4 | Partial | The LED draws current continuously — a concern on battery products |
Bounce is physics, not a code bug
Section titled “Bounce is physics, not a code bug”Mechanical contacts chatter on closure, producing several level transitions within roughly 5–10 ms. Edge-counting firmware will happily count one press as three to seven.
Two ways to deal with it:
- Hardware debounce: an RC filter (typically 10 kΩ plus 100 nF), ideally with a Schmitt-trigger input. Right for interrupt counting and high-frequency presses.
- Software debounce: record when the level last changed and accept a state only after it has been stable for a few milliseconds. Right for most projects and costs nothing.
Rule of thumb: anything a human presses gets software debounce first. If events still get lost or duplicated, add the RC network.
Pull-up or pull-down depends on where the button pulls
Section titled “Pull-up or pull-down depends on where the button pulls”A button is usually wired between the signal pin and GND (press = pull to ground). That arrangement needs an internal pull-up: idle high, pressed low, so the logic is inverted. If your breakout already outputs “high when pressed”, read it as-is and do not stack another pull-up.
How to decide in ten seconds: with a multimeter, measure the module output while pressing and releasing, then choose INPUT_PULLUP or plain INPUT from the observation — not from the sample sketch.
One module, three inputs: the two-axis joystick
Section titled “One module, three inputs: the two-axis joystick”A PS2-style joystick contains two potentiometers plus a push switch and exposes five wires: VCC, GND, VRX, VRY, SW.
| Signal | Type | Connect to | Caution |
|---|---|---|---|
| VRX | Analogue voltage | ADC pin | On the original ESP32 avoid ADC2 (conflicts with Wi-Fi) |
| VRY | Analogue voltage | ADC pin | Keep it in the same ADC1 group as VRX so filtering is uniform |
| SW | Digital (press to GND) | GPIO input | Use INPUT_PULLUP and invert the logic |
| VCC/GND | 3.3 V or 5 V | Supply | If fed with 5 V, analogue swing may exceed the ADC range — confirm the maximum pin voltage first |
Only all three together give you a “direction plus confirm” human interface, which is why joysticks appear on equipment panels and inspection boxes.
A design trap that can only be avoided at wiring time: on the original ESP32, GPIO34–39 are input-only and have no internal pull-up or pull-down. Putting joystick X/Y on 34/35 is therefore ideal, but the push switch must not live there — it needs INPUT_PULLUP, so use GPIO32/33 or any normal bidirectional GPIO.
Implementation
Section titled “Implementation”Button: debounce and press counting without delay
Section titled “Button: debounce and press counting without delay”const uint8_t BUTTON_PIN = 4;
const unsigned long DEBOUNCE_MS = 30; // stability window; 20–50 ms suits a human press
uint8_t lastLevel = HIGH;uint8_t stableLevel = HIGH;unsigned long lastChangeMs = 0;uint32_t pressCount = 0;
void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); // button wired to GND → internal pull-up}
void loop() { uint8_t raw = digitalRead(BUTTON_PIN); unsigned long now = millis();
if (raw != lastLevel) { lastChangeMs = now; // an edge appeared, restart the clock lastLevel = raw; }
// accept a state only after it stayed stable longer than the window if (stableLevel != lastLevel && now - lastChangeMs >= DEBOUNCE_MS) { stableLevel = lastLevel; if (stableLevel == LOW) { // pull-up wiring: LOW means pressed pressCount++; Serial.printf("press #%lu @ %lu ms\n", pressCount, now); } }}Note there is no delay() anywhere. Debouncing with delay() drops other events during the wait and collides with MQTT keep-alive and deep-sleep logic.
Joystick: merging three inputs with a dead zone
Section titled “Joystick: merging three inputs with a dead zone”const uint8_t X_PIN = 34; // ADC1 group, usable while Wi-Fi is upconst uint8_t Y_PIN = 35; // ADC1const uint8_t SW_PIN = 32; // ADC1-capable but also a normal input with pull-upconst uint8_t DEADZONE = 400;
int8_t axisFrom(uint16_t raw) { const uint16_t center = 2048; if (raw < center - DEADZONE) return -1; // left / down if (raw > center + DEADZONE) return 1; // right / up return 0;}
void setup() { Serial.begin(115200); analogSetPinAttenuation(X_PIN, ADC_11db); analogSetPinAttenuation(Y_PIN, ADC_11db); pinMode(SW_PIN, INPUT_PULLUP);}
void loop() { uint16_t x = analogRead(X_PIN); uint16_t y = analogRead(Y_PIN); int8_t dirX = axisFrom(x); int8_t dirY = axisFrom(y); bool pressed = digitalRead(SW_PIN) == LOW;
if (dirX || dirY || pressed) { Serial.printf("joystick x=%d y=%d raw=(%u,%u) sw=%d\n", dirX, dirY, x, y, pressed); } delay(20); // sampling throttle only — never part of the debounce logic}The dead zone matters: potentiometers drift by several hundred counts around centre, and without a dead zone you emit constant phantom directions.
Waking from deep sleep with a button
Section titled “Waking from deep sleep with a button”const uint8_t WAKE_PIN = 36; // must be an RTC GPIO (original ESP32: 0, 2, 4, 12–15, 25–39)
void setup() { Serial.begin(115200); esp_sleep_wakeup_cause_t reason = esp_sleep_get_wakeup_cause(); Serial.printf("boot, wakeup cause=%d\n", (int)reason);
esp_sleep_enable_ext0_wakeup((gpio_num_t)WAKE_PIN, 0); // wake on LOW Serial.println("entering deep sleep..."); esp_deep_sleep_start();}Hard constraint: only RTC-domain pins can wake the chip from deep sleep — plain GPIO cannot. Check your board’s silkscreen and place the button on an RTC pin during wiring design; otherwise the code is right and the board still sleeps forever.
Verification
Section titled “Verification”Button checks
Section titled “Button checks”| Check | Expected result | Verified |
|---|---|---|
Nothing connected, INPUT_PULLUP active |
Readings stay HIGH (internal pull-up present) | |
| One press and release | Exactly one serial line, no duplicates | |
| Ten rapid presses | Count = 10, no more, no less | |
| Shrink the window from 30 ms to 5 ms | Duplicates should start appearing (proves bounce is real) |
Joystick checks
Section titled “Joystick checks”| Action | Expected raw reading | Verified |
|---|---|---|
| Released (centre) | Roughly 1600–2600, depends on pot tolerance | |
| Pushed fully left | Near 0–200 | |
| Pushed fully right | Near 4000–4095 | |
| Press SW | Output shows sw=1 |
If the centre reading sits far from 2048, measure the module’s actual VCC before blaming the potentiometer.
Troubleshooting
Section titled “Troubleshooting”Issue 1: the button jitters although nobody touches it
Section titled “Issue 1: the button jitters although nobody touches it”Symptoms: press lines stream continuously; the level flips randomly.
Possible causes:
- Plain
INPUTwith no pull-up, so the pin floats and picks up noise - The button’s other end goes to 3.3 V instead of GND — logic is inverted
- Very long jumper wires acting as antennas
Solutions:
- Switch to
INPUT_PULLUPand see whether it stabilises immediately - Verify with a multimeter that pressing gives near 0 Ω from the signal pin to GND
- For long cables add a 100 nF capacitor to ground, or use a module with a comparator
Issue 2: pressing does nothing
Section titled “Issue 2: pressing does nothing”Symptoms: no serial output however hard you press.
Possible causes:
- Active level assumed wrongly (module outputs high when pressed)
- Debounce window plus a condition that demands stability inside the window
- Pin already claimed by I2C/SPI
Solutions:
- Print the raw level temporarily:
Serial.println(digitalRead(BUTTON_PIN)); - If the raw level changes, the bug is in your logic; if it does not, it is wiring or a pin conflict
- Move to an unused GPIO and retest
Issue 3: the joystick reports directions while untouched, or never reaches full scale
Section titled “Issue 3: the joystick reports directions while untouched, or never reaches full scale”Symptoms: dirX/dirY non-zero at rest, or pushing right still yields 0.
Possible causes:
- Dead zone too small; centre noise is read as direction
- The sample pin is on ADC2 while Wi-Fi is active, so the value is frozen
- Joystick powered at 5 V while the ADC was calibrated for 3.3 V, so full scale is unreachable
Solutions:
- Start with a 400–600 dead zone, then narrow it after measurement
- Move X/Y into the ADC1 group (GPIO32–39 on the original ESP32)
- Confirm whether the module clamps its output; if not, add a divider or power it at 3.3 V
Best Practices
Section titled “Best Practices”- ✅ Do: standardise the “edge timestamp + stability window” debounce structure into a reusable class instead of rediscovering it per project
- ✅ Do: on battery products, put the button on an RTC pin as the wake source and keep the board asleep until pressed
- ✅ Do: record multi-input modules in the wiring sheet as “2 analogue + 1 digital”, not as “one sensor”
- ❌ Do not: use
delay(50)as debounce — it wrecks keep-alive, repeat presses and sleep logic - ❌ Do not: put a switch that needs an internal pull-up on GPIO34–39 (no pulls, input-only)
- ❌ Do not: sample a joystick from ADC2 while Wi-Fi is connected on the original ESP32
- ❌ Do not: enable the internal pull-up and add an external pull-up “for stability” — it only moves thresholds and can hide the press
Summary
Section titled “Summary”Key points of this section:
- Floating inputs and contact bounce are the real problems in digital inputs — bounce is about 5–10 ms and is handled by a stability window
- Wiring decides configuration: button to GND →
INPUT_PULLUPwith inverted logic; on a 3-pin module, confirm the active level first - One module can occupy several inputs: joystick = 2 ADC plus 1 GPIO, and the analogue pins must dodge ADC2 while Wi-Fi runs
- Deep-sleep wake-up only works on RTC pins, so this is a wiring-stage decision
- Debounce never uses
delay(): measure windows withmillis(); a 20 ms sampling throttle is a separate concern
Next section: analogue reading and voltage dividers — why potentiometers, NTC thermistors and photoresistors all need a divider network first.
We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.
💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.
First published attutorial.imagrove.com/sensor-module-selection/02-digital-inputs-and-debounce/Please credit Imagrove and link back to this page when quoting or republishing.
Questions or issues with this tutorial?
Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.
© Imagrove · ESP32 IoT Tutorial