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延迟
相关推荐
望酹江月17 小时前
HNU-RFID与传感器原理实验
c语言·单片机
计算机安禾19 小时前
【C语言程序设计】第39篇:预处理器与宏定义
c语言·开发语言·c++·vscode·算法·visual studio code·visual studio
本喵是FW19 小时前
C语言手记3
c语言·开发语言
HABuo20 小时前
【linux线程(一)】线程概念、线程控制详细剖析
linux·运维·服务器·c语言·c++·ubuntu·centos
C羊驼21 小时前
C语言学习笔记(十一):数据在内存中的存储
c语言·经验分享·笔记·学习
承渊政道1 天前
【优选算法】(实战体验滑动窗口的奇妙之旅)
c语言·c++·笔记·学习·算法·leetcode·visual studio
C羊驼1 天前
C语言学习笔记(十):操作符
c语言·开发语言·经验分享·笔记·学习
自信150413057591 天前
选择排序算法
c语言·数据结构·算法·排序算法
hongtianzai1 天前
Laravel7.x十大核心特性解析
java·c语言·开发语言·golang·php
weixin_649555671 天前
C语言程序设计第四版(何钦铭、颜晖)第十章函数与程序结构之统计完全平方数
c语言·数据结构·算法