HardwareTimer(uint8 timerNum)
构造函数
参数
timerNum 定时器编号(零知-标准板为1-4)
返回值
void attachInterrupt(int channel, voidFuncPtr handler)
设置中断函数
参数
channel 定时器的通道 1-4
handler 中断函数
返回值
无
void detachInterrupt(int channel)
移除中断函数
参数
channel 设置中断时使用的通道编号,1-4
返回值
无
uint16 getCompare(int channel)
获取定时器比较值
参数
channel 通道编号
返回值
比较值
uint16 getCount(void)
获取当前定时器的计数值
参数
返回值
计数值
uint16 getOverflow()
获取溢出值
参数
无
返回值
溢出值
uint32 getPrescaleFactor()
获取定时器的预分频因子
参数
无
返回值
预分频因子
void pause(void)
暂停定时器
参数
返回值
void refresh(void)
重置计数器
参数
返回值
void resume(void)
恢复停止的计数器
参数
返回值
void setCompare(int channel, uint16 compare)
设置定时器比较值
参数
channel 通道编号
compare 比较值
返回值
无
void setCount(uint16 val)
设置定时器的计数值
参数
计数值
返回值
无
void setMode(int channel, timer_mode mode)
设置定时器的模式
参数
channel 通道编号 1 - 4
mode 定时器的工作模式有3种:TIMER_DISABLED(关闭)、TIMER_PWM(PWM,初始化后的默认模式)、TIMER_OUTPUT_COMPARE(由定时器触发中断)。
返回值
无
void setOverflow(uint16 val)
设置定时器溢出值
参数
val 设置的溢出值
返回值
无
uint16 setPeriod(uint32 microseconds)
设置定时器的周期,单位为微秒
参数
microseconds 周期
返回值
新的溢出值
void setPrescaleFactor(uint32 factor)
设置定时器的预分频因子
参数
factor 分频因子, 1 - 65536
返回值
无
使用示例1
#define LED_RATE 500000
HardwareTimer timer(2);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
timer.pause();
timer.setPeriod(LED_RATE);
timer.setChannel1Mode(TIMER_OUTPUT_COMPARE);
timer.setCompare(TIMER_CH1, 1);
timer.attachCompare1Interrupt(handler_led);
timer.refresh();
timer.resume();
}
void loop() {
}
void handler_led(void) {
toggleLED();
}
使用示例2
int count3 = 0;
int count4 = 0;
HardwareTimer timer3(3);
HardwareTimer timer4(4);
int button_pin = 2;
void setup() {
pinMode(button_pin, INPUT_PULLUP);
timer3.setMode(TIMER_CH1, TIMER_OUTPUT_COMPARE);
timer4.setMode(TIMER_CH1, TIMER_OUTPUT_COMPARE);
timer3.pause();
timer4.pause();
timer3.setCount(0);
timer4.setCount(0);
timer3.setOverflow(30000);
timer4.setOverflow(30000);
timer3.setCompare(TIMER_CH1, 1000);
timer4.setCompare(TIMER_CH1, 1000);
timer3.attachCompare1Interrupt(handler3);
timer4.attachCompare1Interrupt(handler4);
timer3.refresh();
timer4.refresh();
timer3.resume();
timer4.resume();
}
void loop() {
Serial.print("Count 3: ");
Serial.print(count3);
Serial.print("\t\tCount 4: ");
Serial.println(count4);
for (int i = 0; i < 1000; i++) {
if (digitalRead(button_pin)) {
timer4.pause();
} else {
timer4.resume();
}
delay(1);
}
}
void handler3(void) {
count3++;
}
void handler4(void) {
count4++;
}