diff --git a/ports/stm32/timer.c b/ports/stm32/timer.c index 3b9f1dc400..834ebd9c85 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 61320690a6..e83550abd8 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 5c46230303..7602bbd70d 100644 --- a/tests/pyb/timer.py.exp +++ b/tests/pyb/timer.py.exp @@ -2,3 +2,5 @@ 200 300 400 +100 +0.001