极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 13530|回复: 2

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

[复制链接]
发表于 2017-6-24 22:47:26 | 显示全部楼层 |阅读模式
本帖最后由 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 机制如下:

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册

x
回复

使用道具 举报

发表于 2017-6-25 22:17:48 | 显示全部楼层
好帖。。。但是没有看懂
回复 支持 反对

使用道具 举报

发表于 2017-6-28 10:31:48 | 显示全部楼层
好贴,慢慢读,细细体会。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-3-29 16:15 , Processed in 0.043838 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表