esp32 硬件看门狗 idf代码
时间: 2023-09-01 09:10:38 浏览: 110
ESP32 硬件看门狗的 IDF 代码可以参考如下示例:
```c
#include "esp_system.h"
#include "esp_event.h"
#include "esp_log.h"
#include "driver/timer.h"
static const char *TAG = "watchdog_example";
// 定义看门狗定时器
#define WATCHDOG_TIMER_GROUP TIMER_GROUP_0
#define WATCHDOG_TIMER_IDX TIMER_0
#define WATCHDOG_TIMER_DIVIDER 16
#define WATCHDOG_TIMER_INTERVAL_SEC 10
// 声明看门狗定时器句柄
static timer_group_t watchdog_timer_group;
static timer_idx_t watchdog_timer_idx;
// 看门狗定时器回调函数
static void IRAM_ATTR watchdog_timer_callback(void *arg)
{
esp_restart(); // 超时重启
}
void app_main()
{
ESP_LOGI(TAG, "Starting watchdog example...");
// 配置看门狗定时器
const timer_config_t watchdog_timer_config = {
.divider = WATCHDOG_TIMER_DIVIDER,
.counter_dir = TIMER_COUNT_UP,
.counter_en = TIMER_PAUSE,
.alarm_en = TIMER_ALARM_EN,
.auto_reload = TIMER_AUTORELOAD_EN,
.alarm_val = WATCHDOG_TIMER_INTERVAL_SEC * TIMER_BASE_CLK / WATCHDOG_TIMER_DIVIDER,
};
timer_init(WATCHDOG_TIMER_GROUP, WATCHDOG_TIMER_IDX, &watchdog_timer_config);
timer_set_counter_value(WATCHDOG_TIMER_GROUP, WATCHDOG_TIMER_IDX, 0);
timer_enable_intr(WATCHDOG_TIMER_GROUP, WATCHDOG_TIMER_IDX);
timer_isr_register(WATCHDOG_TIMER_GROUP, WATCHDOG_TIMER_IDX, watchdog_timer_callback, NULL, ESP_INTR_FLAG_IRAM, NULL);
timer_start(WATCHDOG_TIMER_GROUP, WATCHDOG_TIMER_IDX);
while (true)
{
// 每秒输出一次日志
ESP_LOGI(TAG, "Hello world!");
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
```
以上代码中,我们首先定义了看门狗定时器的一些参数,包括定时器所在的定时器组、定时器编号、分频系数、定时器超时时间等。然后在 `app_main` 函数中进行了看门狗定时器的配置和启动,并在死循环中每秒输出一次日志。当看门狗定时器超时时,会触发回调函数 `watchdog_timer_callback`,在该函数中调用 `esp_restart` 函数进行系统重启。
阅读全文