概述
早期的Arduino提供的库使用timerBegin(0, 80, true)形式,现在新版的Arduino库已经发生了变化。库的位置:hardware\esp32\3.0.0\cores\esp32\esp32-hal-timer.h. 库函数的头文件如下
头文件
#pragma once
#include "soc/soc_caps.h"
#if SOC_GPTIMER_SUPPORTED
#include "esp32-hal.h"
#include "driver/gptimer_types.h"
#ifdef __cplusplus
extern "C" {
#endif
struct timer_struct_t;
typedef struct timer_struct_t hw_timer_t;
hw_timer_t *timerBegin(uint32_t frequency);
void timerEnd(hw_timer_t *timer);
void timerStart(hw_timer_t *timer);
void timerStop(hw_timer_t *timer);
void timerRestart(hw_timer_t *timer);
void timerWrite(hw_timer_t *timer, uint64_t val);
uint64_t timerRead(hw_timer_t *timer);
uint64_t timerReadMicros(hw_timer_t *timer);
uint64_t timerReadMilis(hw_timer_t *timer);
double timerReadSeconds(hw_timer_t *timer);
uint32_t timerGetFrequency(hw_timer_t *timer);
void timerAttachInterrupt(hw_timer_t *timer, void (*userFunc)(void));
void timerAttachInterruptArg(hw_timer_t *timer, void (*userFunc)(void *), void *arg);
void timerDetachInterrupt(hw_timer_t *timer);
void timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count);
#ifdef __cplusplus
}
#endif
#endif /* SOC_GPTIMER_SUPPORTED */
从名称上就可以看出如何使用。
使用实例
void setup()
{
// Create semaphore to inform us when the timer has fired
timerSemaphore = xSemaphoreCreateBinary();
tim1 = timerBegin(1000000); // 1MHz
timerAttachInterrupt(tim1, &onTimer);
// 设置alarm调用onTimer,每10us调用一次。
//Set alarm to call onTimer function every second (value in microseconds).
// 重复调用,第四个参数是 = 0
timerAlarm(tim1, 10, true, 0); // 10 us 执行一次
}
void ARDUINO_ISR_ATTR onTimer()
{
// Increment the counter and set the time of ISR
portENTER_CRITICAL_ISR(&timerMux);
if ( tm_Enable) tm_ms++;
portEXIT_CRITICAL_ISR(&timerMux);
// Give a semaphore that we can check in the loop
xSemaphoreGiveFromISR(timerSemaphore, NULL);
// It is safe to use digitalRead/Write here if you want to toggle an output
}
这个程序在使能了tm_Enable时对tm_ms进行累加。
心得
设置1MHz或者是10MHz,1us无法使用。10us可以正常使用。并且这个新的库没法确定定时器号。2MHz的定时器运行时loop无法访问串口了。用Serial.avialble()函数没法访问串口了。有知道怎么解决的吗?