stm32/timer: Fix Timer.freq() calc so mult doesn't overflow uint32_t.

Fixes issue #5280.
pull/1/head
Damien George 2019-10-31 12:49:18 +11:00
parent 4e1b03d45c
commit 9ec73aedb4
3 changed files with 21 additions and 7 deletions

View File

@ -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;

View File

@ -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())

View File

@ -2,3 +2,5 @@
200
300
400
100
0.001