翻滚安全计时器(勾选)比较

Jef*_*ffV 8 c c++ embedded rollover timer

我有一个硬件计数器,我可以观察时间考虑因素.它计算毫秒数并存储在16位无符号值中.如何安全地检查计时器值是否已经过一定时间并安全地处理不可避免的翻转:

//this is a bit contrived, but it illustrates what I'm trying to do
const uint16_t print_interval = 5000; // milliseconds
static uint16_t last_print_time;   

if(ms_timer() - last_print_time > print_interval)
{
    printf("Fault!\n");
    last_print_time = ms_timer();
}
Run Code Online (Sandbox Code Playgroud)

当ms_timer溢出为0时,此代码将失败.

smh*_*smh 9

你实际上不需要在这里做任何事情.假设ms_timer()返回uint16_t类型的值,问题中列出的原始代码将正常工作.

(还假设计时器在检查之间不会溢出两次......)

要说服自己就是这种情况,请尝试以下测试:

uint16_t t1 = 0xFFF0;
uint16_t t2 = 0x0010;
uint16_t dt = t2 - t1;
Run Code Online (Sandbox Code Playgroud)

dt会平等的0x20.

  • 考虑到原始行为和替换解决方案,我最后的暗杀是你的x变量/ ms_timer()函数是/返回大于16位的int,这会在计算时差时导致意外的类型提升. (4认同)

Jas*_*yon 1

只需检查 ms_timer < last_print_time 是否,如果是,则添加 2^16 否?

编辑:如果可以的话,您还需要达到 uint32。