ESP-Timer入门(基于ESP-IDF-5.4)

主要参考资料:

ESP 定时器(高分辨率定时器): https://docs.espressif.com/projects/esp-idf/zh_CN/stable/esp32s3/api-reference/system/esp_timer.html

目录

ESP-Timer与FreeRTOS Timer

ESP-Timer 是 ESP-IDF 中提供的高精度定时器组件,专为精确时间控制和低功耗设计优化。它取代了传统的 FreeRTOS 定时器,在 ESP32 系统中提供更精确、更灵活的时间管理能力。

与FreeRTOS定时器比较:

API 使用

1.创建定时器

cpp 复制代码
#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.启动定时器

c 复制代码
// 单次定时器 (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.管理定时器

c 复制代码
// 停止定时器
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.时间管理

c 复制代码
// 获取精确时间戳 (微秒)
int64_t now = esp_timer_get_time();
ESP_LOGI("TIME", "Current time: %lld us", now);

// 延迟执行 (非阻塞)
esp_rom_delay_us(500); // 精确500μs延迟
相关推荐
风指引着方向7 小时前
图编译优化全链路:CANN graph-engine 仓库技术拆解
c语言
C++ 老炮儿的技术栈7 小时前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
Once_day7 小时前
C++之《Effective C++》读书总结(4)
c语言·c++·effective c++
晓13138 小时前
第七章 【C语言篇:文件】 文件全面解析
linux·c语言·开发语言
梵刹古音8 小时前
【C语言】 指针基础与定义
c语言·开发语言·算法
杜子不疼.8 小时前
Ascend_C自定义算子开发
c语言·开发语言
小乔的编程内容分享站8 小时前
C语言笔记之函数
c语言·笔记
杜子不疼.9 小时前
基于ATVC模板库的Ascend C Vector算子快速开发指南
c语言·开发语言·mfc
C++ 老炮儿的技术栈9 小时前
Qt Creator中不写代如何设置 QLabel的颜色
c语言·开发语言·c++·qt·算法
艾莉丝努力练剑9 小时前
【Linux:文件】基础IO
linux·运维·c语言·c++·人工智能·io·文件