Skip to content

Commit

Permalink
stm32/timer: Fix Timer.freq() calc so mult doesn't overflow uint32_t.
Browse files Browse the repository at this point in the history
Fixes issue #5280.
  • Loading branch information
dpgeorge committed Oct 31, 2019
1 parent 4e1b03d commit 9ec73ae
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
20 changes: 13 additions & 7 deletions ports/stm32/timer.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions tests/pyb/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,9 @@
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())
2 changes: 2 additions & 0 deletions tests/pyb/timer.py.exp
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
200
300
400
100
0.001

0 comments on commit 9ec73ae

Please sign in to comment.