From: R. Steve McKown Date: Sun, 1 Jan 2012 02:11:32 +0000 (-0700) Subject: Better cross-platform handling of time calcs X-Git-Url: https://oss.titaniummirror.com/gitweb?p=rgblamp.git;a=commitdiff_plain;h=63426eb2c3d465e0099bf425e7552457abfb867b Better cross-platform handling of time calcs Thanks to integral promotion, a C compiler might treat the intermediate value (t1 - t0) as a larger signed value when t1 and t0 are unsigned values. Cast the intermediate result to unsigned in these cases, as this is necessary to get the correct result in the case of timer value roll-over. --- diff --git a/tmr.c b/tmr.c index 09e6c2d..f07b4b3 100644 --- a/tmr.c +++ b/tmr.c @@ -108,7 +108,8 @@ void tmr_isr() TMR0IF = 0; _tmr_ticks++; for (tmr_bitno_t t = 0; t < TMR_COUNT; t++) { - if (bit_get(_tmr_on, t) && _tmr_ticks - _tmr_t0[t] >= _tmr_elapsed[t]) { + if (bit_get(_tmr_on, t) && + (tmr_time_t)(_tmr_ticks - _tmr_t0[t]) >= _tmr_elapsed[t]) { bit_set(_tmr_flag, t); if (bit_get(_tmr_periodic, t)) _tmr_t0[t] += _tmr_elapsed[t]; diff --git a/tmr.h b/tmr.h index a204ab0..e985e1c 100644 --- a/tmr.h +++ b/tmr.h @@ -98,8 +98,8 @@ void tmr_isr(); /* Wait for c clocks, 0 <= c < 128. */ #define tmr_cwait(c) \ do { \ - unsigned t0 = TMR0; \ - while (TMR0 - t0 <= c); \ + unsigned char t0 = TMR0; \ + while ((unsigned char)(TMR0 - t0) <= c); \ } while (0) /* Wait for a number of us. This is pretty accurate. */