在上一篇ESP32的编程环境搭建完毕后,即可进行定时器操作,定时器用起来,裸机程序的前后台模式就可以跑起来啦。总体来说和STM32的定时器用起来差不多,都是配置一下然后开始就可以使用了。
下面附上定时器验证用的demo程序:
#include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_log.h"
#include "driver/timer.h"
#define TIMER_DIVIDER 16
#define TIMER_SCALE (TIMER_BASE_CLK / TIMER_DIVIDER/ 1000)
#define TIMER_INTERVAL0_SEC (1)
#define TEST_WITH_RELOAD 1
unsigned int timer_counter = 0;
void IRAM_ATTR timer_group0_isr(void *para)
{
timer_spinlock_take(TIMER_GROUP_0);
int timer_idx = (int) para;
// /* Prepare basic event data
// that will be then sent back to the main program task */
timer_counter++;
timer_group_clr_intr_status_in_isr(TIMER_GROUP_0, TIMER_0);
/* After the alarm has been triggered
we need enable it again, so it is triggered the next time */
timer_group_enable_alarm_in_isr(TIMER_GROUP_0, timer_idx);
/* Now just send the event data back to the main program task */
timer_spinlock_give(TIMER_GROUP_0);
}
static void example_tg0_timer_init(int timer_idx,
bool auto_reload, double timer_interval_sec)
{
/* Select and initialize basic parameters of the timer */
timer_config_t config = {
.divider = TIMER_DIVIDER,
.counter_dir = TIMER_COUNT_UP,
.counter_en = TIMER_PAUSE,
.alarm_en = TIMER_ALARM_EN,
.auto_reload = auto_reload,
}; // default clock source is APB
timer_init(TIMER_GROUP_0, timer_idx, &config);
/* Timer's counter will initially start from value below.
Also, if auto_reload is set, this value will be automatically reload on alarm */
timer_set_counter_value(TIMER_GROUP_0, timer_idx, 0x00000000ULL);
/* Configure the alarm value and the interrupt on alarm. */
timer_set_alarm_value(TIMER_GROUP_0, timer_idx, timer_interval_sec * TIMER_SCALE);
timer_enable_intr(TIMER_GROUP_0, timer_idx);
timer_isr_register(TIMER_GROUP_0, timer_idx, timer_group0_isr,
(void *) timer_idx, ESP_INTR_FLAG_IRAM, NULL);
timer_start(TIMER_GROUP_0, timer_idx);
}
void ds_timer_init(void)
{
example_tg0_timer_init(TIMER_0, TEST_WITH_RELOAD, TIMER_INTERVAL0_SEC);
}
void app_main(void)
{
ds_timer_init();
while(1){
printf("system run ...\n");
vTaskDelay(1000 / portTICK_PERIOD_MS);
if(timer_counter >= 1000)
{
timer_counter = 0;
printf("ESP32 Demo Timer Task run ...\n");
}
}
}
运行结果:
ESP32 Demo Timer Task任务也以1000ms为周期运行。