esp32-----定时器

一、周期性定时任务

#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);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

被大佬糊弄的只会点灯的小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值