ESP32_定时器Timer&PWM
一、主程序代码
#include <Arduino.h>
#include "../lib/Motor/Motor.h"
#define PMW_EN 1
int interruptCounter = 0;
hw_timer_t *timer = NULL;
// 函数名称:onTimer()
// 函数功能:中断服务的功能,它必须是一个返回void(空)且没有输入参数的函数
// 为使编译器将代码分配到IRAM内,中断处理程序应该具有 IRAM_ATTR 属性
// https://docs.espressif.com/projects/esp-idf/zh_CN/release-v4.3/esp32/api-reference/storage/spi_flash_concurrency.html
void IRAM_ATTR TimerEvent()
{
Serial.println(interruptCounter++);
if (interruptCounter > 5)
{
interruptCounter = 1;
}
}
void setup()
{
Serial.begin(115200);
#if PMW_EN
Motor_Init();
#endif
// 函数名称:timerBegin()
// 函数功能:Timer初始化,分别有三个参数
// 函数输入:1. 定时器编号(0到3,对应全部4个硬件定时器)
// 2. 预分频器数值(ESP32计数器基频为80M,80分频单位是1us)
// 3. 计数器向上(true)或向下(false)计数的标志
// 函数返回:一个指向 hw_timer_t 结构类型的指针
timer = timerBegin(0, 80, true);