yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
ESP32 Core Board📖
1. ESP32 Introduction
  • 1. ESP32S3 Overview
  • 2. Environment Setup Introduction
  • 3. Dev Board Introduction
2. ESP-IDF Development Tutorial
1. Before Development
  • 1. Environment Setup (Windows)
  • 2. Environment Setup (Linux)
  • 3. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. DMA
  • 8. ADC
  • 9. PWM Breathing LED
  • 10. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. PSRAM External Memory Experiment
  • 5. Flash Read and Write Experiment
  • 6. USB Emulated Mass Storage Experiment
4. FreeRTOS operating system
  • 1.FreeRTOS Core Concepts Theory
  • 2.Task Creation and Management
  • 3.Queue
  • 4.Binary Semaphore
  • 5.Mutex
  • 6.Event Groups
  • 7.Software Timer
  • 8.Task Scheduler
  • 9.Low Power Mode
  • 10.Deadlock
  • 11.Priority Inversion
5. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. Socket Programming Basics
  • 9. HTTP Client Experiment
  • 10. HTTP Server Experiment
  • 11. MQTT IoT Communication Protocol
  • 12. WIFI OTA Upgrade
  • 13. Bluetooth Fundamentals
  • 14. Bluetooth Slave Mode
  • 15. Bluetooth Master Mode
6. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
7. Xiaozhi AI Voice
  • 1. Burn Xiaozhi Firmware
  • 2. Network and Configuration
  • 3. AI Agent Settings
  • 4. Program Analysis
  • 5. Free Chat
3. Arduino Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. ADC
  • 8. PWM Breathing LED
  • 9. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication
  • 2. I2C OLED Display
  • 3. SPI Bus Communication
  • 4. Flash Read and Write
  • 5. USB Emulated Mass Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Server Experiment
  • 5. UDP Client Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT IoT Communication Protocol
  • 11. WIFI OTA Upgrade
  • 12. Bluetooth Fundamentals
  • 13. Bluetooth Slave Mode
  • 14. Bluetooth Master Mode
5. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
4. MicroPython Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
  • 3. Thonny IDE
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. TIMER_IT
  • 5. Watchdog Timer
  • 6. ADC
  • 7. PWM Breathing LED
  • 8. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. Flash Read and Write Experiment
  • 5. Print Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT
  • 11. Bluetooth Fundamentals
  • 12. Bluetooth Slave Mode
  • 13. Bluetooth Master Mode
5. Audio Applications
  • 1. I2S Audio Playback Experiment
  • 2. Repeater Experiment
Download
  • Code
  • Hardware_Info
  • 3D_Model_File
  • Software_Tools
  • VMware
  • VM_File
Download ZIP

Welcome to ESP32 Core Board repository

2. Button Detection

Button Detection


Button Detection1. Button Detection Overview2. Core Concepts2.1 GPIO Input Mode2.2 Mechanical Button Bounce2.3 Falling Edge Detection Principle3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Explanation5.1 Macro Definitions and Global Variables5.2 setup() — GPIO Initialization5.3 loop() — Main Loop and Button Detection (Core)6. Operation Flow6.1 Build and Flash6.2 Normal Operation6.3 Boundary Testing7. Common Issues


1. Button Detection Overview

Buttons are the most common human-machine interaction input devices. The MCU determines the button state by reading the GPIO input level. This experiment uses the BOOT button (GPIO0) to control LED on/off toggling, demonstrating GPIO input configuration, software debouncing, and falling edge detection. Each press toggles once, and holding does not repeat triggering.

Typical Application Scenarios:

Application TypeExample
Digital InputUser buttons, switch state reading, sensor digital signals, rotary encoders
Pull-Up InputButton connected to GND, limit switches, reed switches, photoelectric switches
Debounce ProcessingMechanical buttons, relay contact detection, DIP switches

2. Core Concepts

2.1 GPIO Input Mode

When GPIO is configured in input mode, the pin presents high impedance state, and the level is determined by the external circuit.

Key Functions of Pull-Up/Pull-Down Resistors:

ConfigurationGPIO Default LevelWhen Button PressedApplicable Scenario
Internal Pull-Up (Pull-Up)High (1)Low (0)Button one end connected to GND, conducts when pressed
Internal Pull-Down (Pull-Down)Low (0)High (1)Button one end connected to VDD, conducts when pressed
No Pull-Up/Pull-DownUncertain (floating)UncertainNot recommended, floating pins are susceptible to interference

This experiment uses internal pull-up (INPUT_PULLUP), with one end of the button connected to GND and the other end to GPIO0:

​x
VDD ──→ Internal pull-up resistor (~45kΩ) ──→ GPIO0 ──→ Button ──→ GND

Button released: GPIO0 pulled up to VDD → Read 1 (HIGH)
Button pressed: GPIO0 directly connected to GND → Read 0 (LOW)

2.2 Mechanical Button Bounce

When mechanical buttons are pressed and released, metal contacts experience bouncing, producing a string of irregular high/low level pulses:

xxxxxxxxxx
Ideal waveform:  ────┐             ┌────
               └────────────┘
Actual waveform:  ────┐ ┌┐ ┌┐ ┌┐ ┌┐ ┌┐ ┌┐ ┌────
               └┘ └┘ └┘ └┘ └┘ └┘ └┘
                ├─ Bounce period ─┤
               (typical 5~20ms)

Without debouncing, the MCU may misinterpret one press as multiple triggers. Arduino uses falling edge detection + delay debouncing: after detecting the button changing from high to low (falling edge), it uses delay(20) to skip the entire bounce period, which is simple and efficient.

2.3 Falling Edge Detection Principle

xxxxxxxxxx
loop() each iteration:
  keyState = digitalRead(KEY_PIN)     // Read current level
  |
  +-- keyState == LOW  &&  lastKeyState == HIGH ?
      |
      YES → Falling edge confirmed → Toggle LED → delay(20) debounce
      NO  → Holding or bouncing, no action
      |
  lastKeyState = keyState            // Save this reading for next comparison
keyStatelastKeyStateResult
LOW (0)HIGH (1)Falling edge — Trigger toggle
LOW (0)LOW (0)Holding — No trigger
HIGH (1)HIGH (1)Releasing — No trigger
HIGH (1)LOW (0)Rising edge — No trigger

Why can delay(20) debounce? After confirming the falling edge, delay(20) makes the program "pause" for 20ms, which exactly covers the 5~20ms bounce period. When delay returns, bouncing has ended, and loop() resumes normal polling. The trade-off is that the CPU is completely blocked during delay, which is perfectly adequate for simple projects.


3. Hardware Dependencies

PinPeripheralConfigurationDescription
GPIO43LEDOUTPUTCommon anode connection, low level lights up
GPIO0BOOT buttonINPUT_PULLUPPressed = low level, released = high level

GPIO0 is also a Strapping pin, which affects the boot mode during power-on. After normal operation, using it as button input is fine, but external circuits should not force GPIO0 low, otherwise the chip may fail to boot.


4. Project Architecture and Flow

xxxxxxxxxx
setup()                          // Executes only once
  ├─ pinMode(LED_PIN, OUTPUT)    // LED push-pull output
  └─ pinMode(KEY_PIN, INPUT_PULLUP) // Button pull-up input

loop()                           // Infinite loop
  ├─ keyState = digitalRead()    // Read current level
  ├─ if (keyState==LOW && lastKeyState==HIGH)  // Falling edge?
  │    ├─ ledState = !ledState   // Toggle LED state
  │    ├─ digitalWrite(ledState)
  │    └─ delay(20)              // Skip bounce period
  └─ lastKeyState = keyState     // Save state → Back to start

Key Design Principles:

  • ledState saves the LED output level (LOW=on, HIGH=off), and !ledState toggles to switch

  • lastKeyState records the previous button level, which is the foundation of edge detection — forgetting to update it will cause "falling edge" to be detected every cycle when holding

  • The main loop has no blocking delay (except for the 20ms debounce), ensuring timely button response


5. Source Code Explanation

Full source code: Source Code → Arduino → 1.Basic Peripherals → 2.KEY_LED → 2.KEY_LED.ino

5.1 Macro Definitions and Global Variables

First define the pin numbers, then use two global variables to remember the LED current state and the previous button level.

xxxxxxxxxx
#define LED_PIN     43  // Onboard LED
#define KEY_PIN     0   // BOOT button, pressed to ground

int ledState = LOW;           // LED current output level, LOW=on (common anode)
int lastKeyState = HIGH;      // Previous button level, initial HIGH=not pressed

Why is the initial value of lastKeyState HIGH? Because INPUT_PULLUP is used, when the button is not pressed, the pin is pulled up to high level. Initializing to HIGH is consistent with the physical state, avoiding false falling edge detection in the first loop() cycle after power-on.

5.2 setup() — GPIO Initialization

LED is set to push-pull output, button is set to pull-up input. INPUT_PULLUP uses one macro to complete both "input mode" and "enable pull-up" configurations.

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

When using INPUT (no pull-up/pull-down), the pin is floating, and digitalRead() reads random noise. This is the most common pitfall for beginners — remember button detection must include _PULLUP.

5.3 loop() — Main Loop and Button Detection (Core)

First read the button, then check for falling edge — if current is low and previous is high, the button has just been pressed. After confirmation, toggle the LED and delay 20ms for debouncing, finally save this reading for the next cycle comparison.

xxxxxxxxxx
void loop() {
  int keyState = digitalRead(KEY_PIN);

  // Falling edge: currently pressed(0) and previously released(1)
  if (keyState == LOW && lastKeyState == HIGH) {
    ledState = !ledState;             // Toggle
    digitalWrite(LED_PIN, ledState);
    delay(20);                        // Skip bounce period
  }

  lastKeyState = keyState;            // Save for next comparison
}

Execution flow analysis (for a complete button press):

xxxxxxxxxx
Timeline         GPIO0 Level       loop() Behavior
─────────────────────────────────────────────────
0ms            1 (released)        Read=1, condition not met → lastKeyState=1
...continuous polling...
100ms          0 (just pressed)    Read=0, lastKeyState=1 → Falling edge!
                                Toggle LED → delay(20) → lastKeyState=0
100~300ms      0 (held)             Read=0, lastKeyState=0 → Condition not met
300ms          1 (released)        Read=1, lastKeyState=0 → Rising edge, no action

Why must lastKeyState = keyState be outside the if? If it were only inside the if, when a falling edge is captured (short press, long press, or holding), lastKeyState would always be LOW, and every cycle would detect "falling edge". After that, whether holding or repeatedly pressing/releasing the button, the edge detection condition would never be met again, and the button function would completely fail.


6. Operation Flow

6.1 Build and Flash

Arduino flash process: See Arduino → 1. Before Development → 2. Build and Flash.

6.2 Normal Operation

  • After power-on, the LED is initially on (ledState initial value is LOW, common anode = on)

  • Each press of the BOOT button → LED toggles once (on→off or off→on)

  • Holding without releasing: Toggles only once, next toggle occurs on next press after release

    Before pressing button

    After pressing button

6.3 Boundary Testing

Test ItemOperationExpected Result
Short pressQuickly click BOOT button and release immediatelyLED toggles once
Long pressHold BOOT button for 5 secondsLED toggles once (no repeated toggling while holding)
Rapid consecutive pressesContinuously click 10 times quicklyEach valid press toggles once
Power-on defaultPower on without pressing buttonLED lights up (ledState initial LOW)

7. Common Issues

PhenomenonCauseSolution
One press toggles multiple timesInsufficient debounce timeIncrease delay(20) to 30~50ms
Button response sluggishDebounce delay too largeReduce delay(), recommended no less than 10ms
Button completely unresponsiveGPIO0 configuration error / no pull-upConfirm pinMode(KEY_PIN, INPUT_PULLUP)
Toggles on its own without pressingGPIO0 floating + no pull-up/pull-down → random levelUse INPUT_PULLUP, do not use INPUT
LED on/off logic reversedledState initial value not as expectedChange int ledState = LOW to = HIGH
LED Control
Peripheral Interrupts

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文