hubery0922 发表于 2017-6-24 22:47:26

Arduino timer 机制(micros()与millis()的原理)

本帖最后由 hubery0922 于 2017-6-24 22:46 编辑

针对大多数arduino学习资料没有详细的timer原理/机制解释,在下总结各路大神们的文章,抽象为一张流程图,供大家参考和深入学习arduino时钟机制。

两个重要的函数原型如下:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG; // 狀態寄存器(包括是否允許 Interrupt)
    uint8_t t;// 臨時變量
    cli();    // 禁止 Interrupt
    m = timer0_overflow_count;// timer0 已經 overflow 幾次 ?
    t = TCNT0;// timer0 目前的值
    if ((TIFR0 & _BV(TOV0)) && (t & 255)) m++; // timer0 目前的TCNT0值不是 0且欠一次中斷
    SREG = oldSREG;// 恢復狀態寄存器(注意不一定恢復中斷喔 !)
    return ((m *256) + t) * 4;// 最大只能代表約 71.58分鐘
} // micros(

unsigned long millis() {
    unsigned long m;
    uint8_t oldSREG = SREG;//狀態寄存器(包括是否允許 Interrupt); 1clock
    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli( ); // 禁止中斷; 1 clock
    m = timer0_millis; // 讀取記憶體的全域變量 timer0_millis;8 clock
    SREG = oldSREG;// 恢復狀態寄存器(注意不一定恢復中斷喔 !);1 clock
    return m;// 6 clocks
} // millis(   //total 17 clock cycles

参考:
1.http://www.arduino.cn/thread-12468-1-1.html
2.http://gammon.com.au/interrupts

Arduino timer 机制如下:

maxims 发表于 2017-6-25 22:17:48

好帖。。。但是没有看懂

老胖熊 发表于 2017-6-28 10:31:48

好贴,慢慢读,细细体会。
页: [1]
查看完整版本: Arduino timer 机制(micros()与millis()的原理)