主要參考資料:
ESP 定時器(高分辨率定時器): https://docs.espressif.com/projects/esp-idf/zh_CN/stable/esp32s3/api-reference/system/esp_timer.html
目錄
- ESP-Timer與FreeRTOS Timer
- API 使用
- 1.創建定時器
- 2.啟動定時器
- 3.管理定時器
- 4.時間管理
ESP-Timer與FreeRTOS Timer
ESP-Timer 是 ESP-IDF 中提供的高精度定時器組件,專為精確時間控制和低功耗設計優化。它取代了傳統的 FreeRTOS 定時器,在 ESP32 系統中提供更精確、更靈活的時間管理能力。
與FreeRTOS定時器比較:
API 使用
1.創建定時器
#include "esp_timer.h"// 定義回調函數
void timer_callback(void* arg) {int* counter = (int*)arg;(*counter)++;ESP_LOGI("TIMER", "Callback called %d times", *counter);
}// 創建定時器配置
esp_timer_create_args_t timer_args = {.callback = &timer_callback,.arg = &counter,.name = "my_timer",.dispatch_method = ESP_TIMER_TASK // 或 ESP_TIMER_ISR
};esp_timer_handle_t timer_handle;
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &timer_handle));
2.啟動定時器
// 單次定時器 (50ms后觸發)
ESP_ERROR_CHECK(esp_timer_start_once(timer_handle, 50 * 1000));// 周期定時器 (每100ms觸發)
ESP_ERROR_CHECK(esp_timer_start_periodic(timer_handle, 100 * 1000));
3.管理定時器
// 停止定時器
ESP_ERROR_CHECK(esp_timer_stop(timer_handle));// 刪除定時器
ESP_ERROR_CHECK(esp_timer_delete(timer_handle));// 獲取剩余時間
int64_t remaining = esp_timer_get_next_alarm();
ESP_LOGI("TIMER", "Next alarm in %lld us", remaining);
4.時間管理
// 獲取精確時間戳 (微秒)
int64_t now = esp_timer_get_time();
ESP_LOGI("TIME", "Current time: %lld us", now);// 延遲執行 (非阻塞)
esp_rom_delay_us(500); // 精確500μs延遲