timer: fix a build warning and add a comment
authorarighi <arighi@38d2e660-2303-0410-9eaa-f027e97ec537>
Fri, 4 Feb 2011 10:15:57 +0000 (10:15 +0000)
committerarighi <arighi@38d2e660-2303-0410-9eaa-f027e97ec537>
Fri, 4 Feb 2011 10:15:57 +0000 (10:15 +0000)
Fix the following build warning:
 bertos/drv/timer.c:292: warning: signed and unsigned type in conditional expression

And comment the formula used to evaluate the timer delta.

git-svn-id: https://src.develer.com/svnoss/bertos/trunk@4681 38d2e660-2303-0410-9eaa-f027e97ec537

bertos/drv/timer.c

index 4d1309466da6b37fb870ad244aa4f802df57f74a..d75f15abcf85324e525444bd3ad060404f196c56 100644 (file)
@@ -289,7 +289,27 @@ void timer_busyWait(hptime_t delay)
        for (;;)
        {
                now = timer_hw_hpread();
-               delta = (now < prev) ? (TIMER_HW_CNT - prev + now) : (now - prev);
+               /*
+                * The timer counter may wrap here and "prev" can become
+                * greater than "now". So, be sure to always evaluate a
+                * coherent timer difference:
+                *
+                * 0     prev            now   TIMER_HW_CNT
+                * |_____|_______________|_____|
+                *        ^^^^^^^^^^^^^^^
+                * delta = now - prev
+                *
+                * 0     now             prev  TIMER_HW_CNT
+                * |_____|_______________|_____|
+                *  ^^^^^                 ^^^^^
+                * delta = (TIMER_HW_CNT - prev) + now
+                *
+                * NOTE: TIMER_HW_CNT can be any value, not necessarily a power
+                * of 2. For this reason the "%" operator is not suitable for
+                * the generic case.
+                */
+               delta = (now < prev) ? ((hptime_t)TIMER_HW_CNT - prev + now) :
+                                               (now - prev);
                if (delta >= delay)
                        break;
                delay -= delta;