กลับไปหน้ารวมไฟล์
esp-32-elapsed-timer-alerting-framework-0e4593-en.md

title: "Mastering ESP32 Timer Interrupts: Smart Time Management System (ETA Framework)" description: "A deep dive into using ESP32 Hardware Timers to create a highly accurate parallel Task management system via Elapsed Timer Alerts (ETA)."

Introduction: Overcoming delay() Limitations with Hardware Timers

When programming on ESP32, a common issue encountered by embedded system engineers is managing multiple events that need to occur at different times (Multi-tasking). If we use the delay() function, the program will halt and be unable to respond to other events promptly.

This article will introduce the ETA Framework (Elapsed Timer Alerts), a programming structure that directly utilizes ESP32 Timer Interrupts. It allows you to create multiple concurrent "timers," whether for one-off or recurring tasks, without disrupting the main program execution.

Concept of the ETA Framework

The core of this Framework is defining the conditions for alerts when time elapses, which we call an Elapsed Timer Alert (ETA). Each ETA consists of:

  1. Type: Type of Timer (one-off or recurring)
  2. Alert ID: A unique identification code (ID 0-65535) used to distinguish which Task has completed.
  3. Countdown (ms): The countdown duration in milliseconds.

Engineering Deep Dive: ESP32 Hardware Timers (Example 1)

The ESP32 has a total of 4 Hardware Timers (Timer 0 to 3), which are high-precision 64-bit counters. In the first example (Example 1), we will configure Timer 0 to operate at a frequency of 1,000Hz, or every 1 millisecond.

In-depth Working Principle:

  • Prescaler: The ESP32's clock signal is 80MHz. We use a Prescaler of 80 to divide the frequency down to 1MHz (1 million times per second).
  • Alarm: When the Counter reaches 1,000 counts, it will generate an Interrupt signal once (equal to exactly 1ms).
  • ISR (Interrupt Service Routine): When an Interrupt occurs, the program jumps to execute a special function stored in IRAM_ATTR for speed. Its role in this Framework is to increment the time-counting variable (Interrupt Count).

Main Structure of the ETA Framework (Example 2)

This Framework is designed to operate Asynchronously, meaning the Interrupt solely handles time counting, while heavy decision-making or Logic is moved to the main loop() to prevent the system from freezing (WDT Reset).

Working Steps (Pseudo Code):

 main loop {  
   Check pending Interrupt count;  
   while (there are unhandled Interrupts) { 
     update_ETAs(); // Decrement the countdown of all Timers by 1ms 
     while (there is an ETA due) {  
       switch (ETA Alert ID) {  
         case heart_beat:  
           Flash LED;  
         case sensor_read_id:  
           Read sensor data;  
         ...  
       }  
     }  
   }  
   Perform other tasks (e.g., connect Wi-Fi or process data);  
 }  

Defining the Number of Timers

You can define the maximum number of Timers the system will manage via the Macro #define max_ETAs to allow the system to allocate memory efficiently.


Key Function Usage in the Framework

1. Creating a Timer (create_ETA)

This function is used to create time-based tasks and has 3 parameters:

  • ETA_type: one_off_ETA (execute once then delete) or recurring_ETA (repeat continuously)
  • ETA_alert_id: Task ID (0 - 65535)
  • ETA_interval: Desired time (ms)

Creation Example:

if(create_ETA(recurring_ETA, 102, 500) == ETA_inserted) {
    // Successfully created a Timer to send data every 500ms!
}

2. Deleting a Timer (delete_ETA)

We can immediately cancel a scheduled task using delete_ETA(type, id), which is very useful when needing to stop certain Tasks based on specified conditions.

3. Displaying Status (print_ETAs)

For Debugging, this function will print a table of all Timers to the Serial Monitor (115200 baud) to check if the Countdown and Interval values for each ID are still functioning correctly.


Case Study: Smart Environment Control System (Example 3)

To illustrate real-world usage, Example 3 simulates a Greenhouse Control system that must manage Tasks with completely different frequencies:

  • Heartbeat (500ms): Flashes an LED to indicate the system is not frozen.
  • Sensor Sampling (2 seconds): Reads temperature and humidity values.
  • Soil Moisture Check (30 seconds): Checks soil moisture (which doesn't need to be checked as frequently as temperature).
  • Stats Report (1 minute): Summarizes operation results via Serial Port.

With the ETA Framework, we can easily define these in an Array format:

unsigned int my_ETA_data[max_ETAs][3] = {
    {recurring_ETA, heart_beat_id, 500},
    {recurring_ETA, sensor_read_id, 2000},
    {recurring_ETA, soil_moisture_id, 30000},
    {recurring_ETA, stats_report_id, 60000}
};

Time Support Data (Time Macros)

The Framework provides constants to make the Code easier to read (Self-documenting code):

  • one_day : 86,400,000 ms
  • one_hour : 3,600,000 ms
  • one_minute : 60,000 ms
  • one_second : 1,000 ms

You can use these values directly, for example create_ETA(one_off_ETA, 5, 2 * one_hour); to set a timer for 2 hours from now.


Conclusion from an Engineer's Perspective

Utilizing ESP32 Timer Interrupts via the ETA Framework fully transforms programming from a "waiting" (Blocking) style to an "event-responsive" (Event-Driven) style.

This system offers high flexibility (Scalability) and minimizes the computational load in the ISR, making your ESP32 operate stably, without glitches, and capable of professionally handling complex IoT projects.

If you wish to use it with Arduino family boards (AVR), you only need to change the Timer Register configuration to match that architecture (e.g., using the AVR Timer Interrupts Calculator), but the logical structure of the ETA Framework remains immediately compatible.

ข้อมูล Frontmatter ดั้งเดิม

title: "ESP 32 Elapsed Timer Alerting Framework"
description: "A totally flexible and general timer interrupt framework for designing solutions needing one or many individual elapsing and separate timers"
author: "ronbentley1"
category: ""
tags:
  - "etas"
  - "esp 32"
  - "alerting"
  - "timers"
  - "interrupts"
views: 1452
likes: 0
price: 2450
difficulty: "Intermediate"
components:
  - "1x ESP32S"
tools: []
apps:
  - "1x Arduino IDE"
downloadableFiles:
  - "https://projects.arduinocontent.cc/1ed87cdf-35cb-4167-933a-7f1745167f87.ino"
  - "https://projects.arduinocontent.cc/c23cbc08-47fb-4f98-b288-751799d75ea3.ino"
  - "https://projects.arduinocontent.cc/1ed87cdf-35cb-4167-933a-7f1745167f87.ino"
documentationLinks: []
passwordHash: "87328bc21168104cabebc8079173f7f6ff20911fa0fc0928495665e57d182d05"
encryptedPayload: "U2FsdGVkX1+owfScJPPlvxV1KJE4ucksEVYf7lojdAhIVoPiv/qW9k7xgso/55NFhID7i+fUw54cqn9BPepewC/BL5oJpuAABfjKzEFcZ5A="
seoDescription: "A flexible ESP 32 Timer interrupt framework for managing multiple separate elapsing timers in Arduino projects."
videoLinks: []
heroImage: "https://cdn.jsdelivr.net/gh/bigboxthailand/arduino-assets@main/images/projects/esp-32-elapsed-timer-alerting-framework-0e4593_cover.jpg"
lang: "en"