c++ - Rollover safe timer (tick) comparisons -


i have counter in hardware can observe timing considerations. counts miliseconds , stored in 16 bit unsigned value. how safely check if timer value has passed time , safely handle inevitable rollover:

//this bit contrived, illustrates i'm trying 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(); } 

this code fail when ms_timer overflows 0.

you don't need here. original code listed in question work fine, assuming ms_timer() returns value of type uint16_t.

(also assuming timer doesn't overflow twice between checks...)

to convince case, try following test:

uint16_t t1 = 0xfff0; uint16_t t2 = 0x0010; uint16_t dt = t2 - t1; 

dt equal 0x20.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -