一、周期性定时任务
#include <stdio.h>
#include "esp_types.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "soc/timer_group_struct.h"
#include "driver/periph_ctrl.h"
#include "driver/timer.h"
#define GPIO_LED 2
esp_timer_handle_t test_p_handle = 0;
void test_timer_periodic_cb(void *arg) {
printf("Hello\n");
}
void app_main()
{
//定义一个周期重复运行的定时器结构体
esp_timer_create_args_t test_periodic_arg = {
.callback =
&test_timer_periodic_cb, //设置回调函数
.arg = NULL, //不携带参数
.name = "TestPeriodicTimer" //定时器名字
};
esp_err_t err = esp_timer_create(&test_periodic_arg, &test_p_handle);
err = esp_timer_start_periodic(test_p_handle, 1000 * 1000);
}
二、只运行一次的定时任务
#include <stdio.h>
#include "esp_types.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "soc/timer_group_struct.h"
#include "driver/periph_ctrl.h"
#include "driver/timer.h"
#define GPIO_LED 2
esp_timer_handle_t test_p_handle = 0;
void test_timer_periodic_cb(void *arg) {
vTaskDelay(5000 / portTICK_PERIOD_MS);
printf("Hello\n");
}
void app_main()
{
//定义一个周期重复运行的定时器结构体
esp_timer_create_args_t test_periodic_arg = {
.callback =
&test_timer_periodic_cb, //设置回调函数
.arg = NULL, //不携带参数
.name = "TestPeriodicTimer" //定时器名字
};
esp_err_t err = esp_timer_create(&test_periodic_arg, &test_p_handle);
err = esp_timer_start_once(test_p_handle, 1000 * 1000);
}
三、周期性运行若干次的定时任务
#include <stdio.h>
#include "esp_types.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "soc/timer_group_struct.h"
#include "driver/periph_ctrl.h"
#include "driver/timer.h"
#define GPIO_LED 2
esp_timer_handle_t test_p_handle = 0;
int cnt=0;
void test_timer_periodic_cb(void *arg) {
vTaskDelay(5000 / portTICK_PERIOD_MS);
printf("Hello\n");
if(cnt>5){
esp_err_t err = esp_timer_stop(test_p_handle);
err=esp_timer_delete(test_p_handle);
}
cnt++;
}
void app_main()
{
//定义一个周期重复运行的定时器结构体
esp_timer_create_args_t test_periodic_arg = {
.callback =
&test_timer_periodic_cb, //设置回调函数
.arg = NULL, //不携带参数
.name = "TestPeriodicTimer" //定时器名字
};
esp_err_t err = esp_timer_create(&test_periodic_arg, &test_p_handle);
err = esp_timer_start_periodic(test_p_handle, 1000 * 1000);
while(1){
printf("Hi\n");
vTaskDelay(5000 / portTICK_PERIOD_MS);
}