From 63426eb2c3d465e0099bf425e7552457abfb867b Mon Sep 17 00:00:00 2001 From: "R. Steve McKown" Date: Sat, 31 Dec 2011 19:11:32 -0700 Subject: [PATCH] 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. --- tmr.c | 3 ++- tmr.h | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) 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. */ -- 2.39.2