ESP8266學習歷程(2)——hw_timer硬件定時器

上一篇博客講解了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");
    }
    
}

輸出結果如下圖:

在這裏插入圖片描述
在這裏插入圖片描述


我的GITHUB

我的個人博客

CSDN

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章