HardwareTimer


HardwareTimer(uint8 timerNum)

构造函数

void attachInterrupt(int channel, voidFuncPtr handler)

设置中断函数

void detachInterrupt(int channel)

移除中断函数

uint16 getCompare(int channel)

获取定时器比较值

uint16 getCount(void)

获取当前定时器的计数值

uint16 getOverflow()

获取溢出值

uint32 getPrescaleFactor()

获取定时器的预分频因子

void pause(void)

暂停定时器

void refresh(void)

重置计数器

void resume(void)

恢复停止的计数器

void setCompare(int channel, uint16 compare)

设置定时器比较值

void setCount(uint16 val)

设置定时器的计数值

void setMode(int channel, timer_mode mode)

设置定时器的模式

void setOverflow(uint16 val)

设置定时器溢出值

uint16 setPeriod(uint32 microseconds)

设置定时器的周期,单位为微秒

void setPrescaleFactor(uint32 factor)

设置定时器的预分频因子

使用示例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++;
}