Skip to content

Commit e429daa

Browse files
committed
extmod/utime_mphal: Fix implementation of new semantics of ticks_diff().
Now the function properly uses ring arithmetic to return signed value in range (inclusive): [-MICROPY_PY_UTIME_TICKS_PERIOD/2, MICROPY_PY_UTIME_TICKS_PERIOD/2-1]. That means that function can properly process 2 time values away from each other within MICROPY_PY_UTIME_TICKS_PERIOD/2 ticks, but away in both directions. For example, if tick value 'a' predates tick value 'b', ticks_diff(a, b) will return negative value, and positive value otherwise. But at positive value of MICROPY_PY_UTIME_TICKS_PERIOD/2-1, the result of the function will wrap around to negative -MICROPY_PY_UTIME_TICKS_PERIOD/2, in other words, if a follows b in more than MICROPY_PY_UTIME_TICKS_PERIOD/2 - 1 ticks, the function will "consider" a to actually predate b.
1 parent 76146b3 commit e429daa

1 file changed

Lines changed: 7 additions & 1 deletion

File tree

extmod/utime_mphal.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,13 @@ STATIC mp_obj_t time_ticks_diff(mp_obj_t end_in, mp_obj_t start_in) {
8989
// we assume that the arguments come from ticks_xx so are small ints
9090
uint32_t start = MP_OBJ_SMALL_INT_VALUE(start_in);
9191
uint32_t end = MP_OBJ_SMALL_INT_VALUE(end_in);
92-
return MP_OBJ_NEW_SMALL_INT((int32_t)(end - start));
92+
int32_t diff = end - start;
93+
if (diff < (signed)-(MICROPY_PY_UTIME_TICKS_PERIOD / 2)) {
94+
diff += MICROPY_PY_UTIME_TICKS_PERIOD;
95+
} else if (diff >= (signed)(MICROPY_PY_UTIME_TICKS_PERIOD / 2)) {
96+
diff -= MICROPY_PY_UTIME_TICKS_PERIOD;
97+
}
98+
return MP_OBJ_NEW_SMALL_INT(diff);
9399
}
94100
MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj, time_ticks_diff);
95101

0 commit comments

Comments
 (0)