上一篇博客讲解了GPIO的基本使用,差不多就是电灯成功了;接下来讲解NodeMCU上硬件定时器的使用:
使用硬件定时器必须包括的一个头文件:
#include "driver/hw_timer.h"
头文件提供了以下几个接口方便调用:
esp_err_t hw_timer_set_clkdiv(hw_timer_clkdiv_t clkdiv); //设置硬件定时器的分频系数
uint32_t hw_timer_get_clkdiv(); //获取硬件定时器的分频系数
esp_err_t hw_timer_set_intr_type(hw_timer_intr_type_t intr_type);//设置硬件定时器的中断类型
uint32_t hw_timer_get_intr_type(); //获取硬件定时器的中断类型
esp_err_t hw_timer_set_reload(bool reload); //启用硬件计时器重新加载
bool hw_timer_get_reload(); //获取硬件定时器重载状态
esp_err_t hw_timer_enable(bool en); //使能硬件定时器
bool hw_timer_get_enable(); //获取硬件定时器使能状态
esp_err_t hw_timer_set_load_data(uint32_t load_data); //设置硬件计时器加载值
uint32_t hw_timer_get_load_data(); //获取硬件定时器加载值
uint32_t hw_timer_get_count_data(); //获取硬件定时器计数值
esp_err_t hw_timer_deinit(void); //删除硬件计时器
esp_err_t hw_timer_init(hw_timer_callback_t callback, void *arg);//初始化硬件计时器
esp_err_t hw_timer_alarm_us(uint32_t value, bool reload); //设置触发计时器us延迟来启用此计时器
esp_err_t hw_timer_disarm(void); //禁用这个计时器
关键函数讲解
硬件定时器初始化
//参数:初始化的回调函数,传给回调函数的参数
esp_err_t hw_timer_init(hw_timer_callback_t callback, void *arg);
设置触发计时器us延迟来启用此计时器
//参数:延迟多少us,bool型的是否重载
esp_err_t hw_timer_alarm_us(uint32_t value, bool reload);
取消硬件定时器
esp_err_t hw_timer_deinit(void);
用例
使用硬件定时器实现输出一个频率为500Hz的脉冲
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/hw_timer.h"
static const char *TAG = "hw_timer_example";
#define TEST_ONE_SHOT false
#define TEST_RELOAD true
#define GPIO_OUTPUT_IO_0 12
#define GPIO_OUTPUT_PIN_SEL (1ULL << GPIO_OUTPUT_IO_0)
void hw_timer_test(void *arg)
{
static int state = 0;
gpio_set_level(GPIO_OUTPUT_IO_0, (state ++) % 2);
}
void app_main(void)
{
//GPIO初始化
gpio_config_t io_conf;
io_conf.intr_type = GPIO_INTR_DISABLE;
io_conf.mode = GPIO_MODE_OUTPUT;
io_conf.pin_bit_mask = GPIO_OUTPUT_PIN_SEL;
io_conf.pull_down_en = 0;
io_conf.pull_up_en = 0;
gpio_config(&io_conf);
//初始化硬件定时器
hw_timer_init(hw_timer_test, NULL);
//设置输出频率为500Hz
hw_timer_alarm_us(1000, TEST_RELOAD);
while(1)
{
vTaskDelay(1000 / portTICK_RATE_MS);
ESP_LOGI(TAG, "Testting");
}
}
输出结果如下图:
扫描二维码关注公众号,回复:
10370213 查看本文章