From 9ec73aedb4fedafce93a018c26cfbc79686be34b Mon Sep 17 00:00:00 2001 From: Damien George Date: Thu, 31 Oct 2019 12:49:18 +1100 Subject: [PATCH] stm32/timer: Fix Timer.freq() calc so mult doesn't overflow uint32_t. Fixes issue #5280. --- ports/stm32/timer.c | 20 +++++++++++++------- tests/pyb/timer.py | 6 ++++++ tests/pyb/timer.py.exp | 2 ++ 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/ports/stm32/timer.c b/ports/stm32/timer.c index 3b9f1dc40..834ebd9c8 100644 --- a/ports/stm32/timer.c +++ b/ports/stm32/timer.c @@ -1269,15 +1269,21 @@ STATIC mp_obj_t pyb_timer_freq(size_t n_args, const mp_obj_t *args) { uint32_t prescaler = self->tim.Instance->PSC & 0xffff; uint32_t period = __HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self); uint32_t source_freq = timer_get_source_freq(self->tim_id); - uint32_t divide = ((prescaler + 1) * (period + 1)); + uint32_t divide_a = prescaler + 1; + uint32_t divide_b = period + 1; #if MICROPY_PY_BUILTINS_FLOAT - if (source_freq % divide != 0) { - return mp_obj_new_float((float)source_freq / (float)divide); - } else - #endif - { - return mp_obj_new_int(source_freq / divide); + if (source_freq % divide_a != 0) { + return mp_obj_new_float((mp_float_t)source_freq / (mp_float_t)divide_a / (mp_float_t)divide_b); } + source_freq /= divide_a; + if (source_freq % divide_b != 0) { + return mp_obj_new_float((mp_float_t)source_freq / (mp_float_t)divide_b); + } else { + return mp_obj_new_int(source_freq / divide_b); + } + #else + return mp_obj_new_int(source_freq / divide_a / divide_b); + #endif } else { // set uint32_t period; diff --git a/tests/pyb/timer.py b/tests/pyb/timer.py index 61320690a..e83550abd 100644 --- a/tests/pyb/timer.py +++ b/tests/pyb/timer.py @@ -11,3 +11,9 @@ tim.prescaler(300) print(tim.prescaler()) tim.period(400) print(tim.period()) + +# Setting and printing frequency +tim = Timer(2, freq=100) +print(tim.freq()) +tim.freq(0.001) +print(tim.freq()) diff --git a/tests/pyb/timer.py.exp b/tests/pyb/timer.py.exp index 5c4623030..7602bbd70 100644 --- a/tests/pyb/timer.py.exp +++ b/tests/pyb/timer.py.exp @@ -2,3 +2,5 @@ 200 300 400 +100 +0.001