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

3. Peripheral Interrupts

Peripheral Interrupts


Peripheral Interrupts1. Peripheral Interrupt Overview2. Core Concepts2.1 External Interrupt Principle2.2 ISR Hard Constraints2.3 volatile Keyword2.4 Debounce Strategy3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Details5.1 Macro Definitions and Global Variables5.2 setup() — Initialization and Interrupt Registration5.3 loop() — Debounce and LED Toggle5.4 keyISR() — Interrupt Service Routine6. Operation Flow6.1 Build and Flash6.2 Normal Operation6.3 Boundary Testing7. Common Issues


1. Peripheral Interrupt Overview

External Interrupt (External Interrupt / EXTI) is a hardware mechanism by which the MCU responds to external asynchronous events. When a GPIO pin detects a specified edge (rising edge/falling edge/either edge), the hardware automatically pauses the current program execution, jumps to a preset Interrupt Service Routine (ISR) to handle the event, and returns to the original program to continue execution after handling is complete.

This experiment uses the BOOT button (GPIO0) to trigger an external interrupt. The ISR only records a timestamp, while debouncing and LED toggling are handled in loop(). This "ISR marks flag + main loop does the work" pattern is the universal paradigm for all interrupt applications.

Typical Application Scenarios:

Application TypeExample
Edge triggerEmergency stop button, speed sensor, PIR motion detection
Level triggerPower loss detection, overcurrent protection signal
ISR + main loopTouch IC status pin, encoder Z-phase home signal

2. Core Concepts

2.1 External Interrupt Principle

attachInterrupt(digitalPinToInterrupt(pin), ISR, mode) maps GPIO edge events to the CPU interrupt vector table. When the pin level changes by the specified amount, the CPU pauses the current task, jumps to the ISR function for execution, and returns to the original task to continue running after execution is complete.

mode parameterTrigger condition
CHANGETriggers on both rising and falling edges
RISINGRising edge only (LOW to HIGH)
FALLINGFalling edge only (HIGH to LOW)

This experiment uses FALLING edge triggering because it needs to capture the press event to determine bounce.

2.2 ISR Hard Constraints

The following operations are NOT allowed in ISR, otherwise they will cause deadlock, watchdog reset, or data corruption:

Prohibited operationReason
Serial.print()Internally relies on UART interrupt, will cause deadlock in ISR
delay() / long operationsHigher priority interrupts are masked during ISR, delaying all timing/communication
malloc() / free()May trigger kernel scheduling, not allowed in ISR context
Modifying non-volatile global variablesCompiler may cache in registers, loop() cannot see updates

Correct approach: ISR only does the simplest operations (sets flag, records timestamp), leaving heavy work to loop().

2.3 volatile Keyword

volatile unsigned long lastEdgeTime = 0;  // Written by ISR, read by loop()

The compiler optimizer caches "seemingly unchanged" variables in CPU registers. volatile forces each reload from RAM, ensuring that values written by ISR can be immediately seen by loop(). The typical symptom of not adding volatile is: ISR clearly updates the variable, but loop() always reads the old value.

2.4 Debounce Strategy

This experiment uses a separated strategy of ISR records timestamp + loop() debounces:

  • In ISR, only millis() records the latest edge time (< 1μs)

  • In loop(), judge "more than 30ms since last edge" as stable, then read the level

There are two benefits to placing debouncing in loop() instead of ISR: ISR remains very short; debounce logic can be debugged with Serial.print.


3. Hardware Dependencies

PinPeripheralConfigurationDescription
GPIO44LEDOUTPUTCommon anode connection, low level lights up
GPIO0BOOT buttonINPUT_PULLUPPress = low level, falling edge interrupt

4. Project Architecture and Flow

​x
setup()
  ├─ pinMode(LED, OUTPUT)             // LED push-pull output
  ├─ pinMode(KEY, INPUT_PULLUP)       // Button pull-up input
  ├─ digitalWrite(LED, OFF)           // Initial off
  └─ attachInterrupt(KEY, keyISR, FALLING)  // Register falling edge interrupt

loop()                                // Main loop
  ├─ if (now - lastEdgeTime >= 30ms)  // Debounce: more than 30ms since last edge?
  │    ├─ reading = digitalRead(KEY)  // Read stable level
  │    └─ if (reading != lastStableState)  // Different from last stable value?
  │         ├─ Update lastStableState
  │         └─ if (reading == LOW)    // Falling edge → valid press
  │              └─ Toggle LED

keyISR()                              // Interrupt Service Routine
  └─ lastEdgeTime = millis()          // Only record timestamp, nothing else

5. Source Code Details

Full source code: Source Code → Arduino → 1.Basic Peripherals → 3.NVIC_KEY → 3.NVIC_KEY.ino

5.1 Macro Definitions and Global Variables

First define pin numbers and debounce time. Two global variables use volatile and regular type to distinguish ISR access permissions.

xxxxxxxxxx
#define LED_PIN     44
#define KEY_PIN     0
#define DEBOUNCE_MS 30

volatile unsigned long lastEdgeTime = 0;  // Written by ISR, read by loop(), must be volatile
bool ledState = false;                    // Only accessed by loop(), no volatile needed
bool lastStableState = HIGH;              // Last stable level after debounce

lastStableState initial value HIGH: In pull-up state, unpressed is HIGH, consistent with physical state.

5.2 setup() — Initialization and Interrupt Registration

Configure GPIO and register interrupt. attachInterrupt internally completes pin to interrupt number mapping and vector table writing.

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

  attachInterrupt(digitalPinToInterrupt(KEY_PIN), keyISR, FALLING);
}

digitalPinToInterrupt() converts Arduino pin number to internal interrupt number. Not all GPIO support interrupts — ESP32-S3 all GPIO are usable, but AVR boards like Uno have only a few.

5.3 loop() — Debounce and LED Toggle

Debounce judgment is done in loop(), not blocking ISR. Only when more than 30ms has passed since last edge is the signal considered stable.

xxxxxxxxxx
void loop() {
  unsigned long now = millis();

  if (now - lastEdgeTime >= DEBOUNCE_MS) {     // More than 30ms since last edge?
    bool reading = digitalRead(KEY_PIN);        // Read stable level

    if (reading != lastStableState) {           // Different from last confirmed value?
      lastStableState = reading;
      if (reading == LOW) {                     // Falling edge → valid press
        ledState = !ledState;
        digitalWrite(LED_PIN, ledState);
      }
    }
  }
}

The debounce logic is essentially the same as the delay(20) in the button experiment, but here it does not block — loop() continues running, just skips readings during the bounce period. lastStableState prevents secondary toggles caused by release bounce.

5.4 keyISR() — Interrupt Service Routine

ISR only does one thing: records the timestamp. This is the best practice for ISR — very short, non-blocking, no peripheral operations.

xxxxxxxxxx
void keyISR() {
  lastEdgeTime = millis();  // Only record timestamp, fastest operation
}

Is millis() safe in ISR? Safe — it only reads a hardware counter register, does not depend on interrupts, and does not block.


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, LED is initially off (ledState = false)

  • Each press of BOOT button → LED toggles once

Initial State

State After Interrupt Triggered

6.3 Boundary Testing

Test ItemOperationExpected Result
Short pressQuick tap BOOT buttonLED toggles once
Long pressHold BOOT buttonLED toggles once (debounce judges only one falling edge)
Fast continuous pressContinuous quick tapsEach valid press toggles once

7. Common Issues

PhenomenonCauseSolution
Adding Serial.print in ISR causes hangSerial port forbidden in ISRMove print to loop()
LED does not togglevolatile missingCheck if lastEdgeTime is declared as volatile
One press toggles multiple timesDebounce time insufficientIncrease DEBOUNCE_MS to 50ms
Interrupt does not triggerGPIO0 mode errorConfirm pinMode(KEY_PIN, INPUT_PULLUP)
Button Detection
ESP_TIMER

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/中文