Skip to content

Commit 9ec73ae

Browse files
committed
stm32/timer: Fix Timer.freq() calc so mult doesn't overflow uint32_t.
Fixes issue micropython#5280.
1 parent 4e1b03d commit 9ec73ae

File tree

3 files changed

+21
-7
lines changed

3 files changed

+21
-7
lines changed

ports/stm32/timer.c

+13-7
Original file line numberDiff line numberDiff line change
@@ -1269,15 +1269,21 @@ STATIC mp_obj_t pyb_timer_freq(size_t n_args, const mp_obj_t *args) {
12691269
uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
12701270
uint32_t period = __HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self);
12711271
uint32_t source_freq = timer_get_source_freq(self->tim_id);
1272-
uint32_t divide = ((prescaler + 1) * (period + 1));
1272+
uint32_t divide_a = prescaler + 1;
1273+
uint32_t divide_b = period + 1;
12731274
#if MICROPY_PY_BUILTINS_FLOAT
1274-
if (source_freq % divide != 0) {
1275-
return mp_obj_new_float((float)source_freq / (float)divide);
1276-
} else
1277-
#endif
1278-
{
1279-
return mp_obj_new_int(source_freq / divide);
1275+
if (source_freq % divide_a != 0) {
1276+
return mp_obj_new_float((mp_float_t)source_freq / (mp_float_t)divide_a / (mp_float_t)divide_b);
12801277
}
1278+
source_freq /= divide_a;
1279+
if (source_freq % divide_b != 0) {
1280+
return mp_obj_new_float((mp_float_t)source_freq / (mp_float_t)divide_b);
1281+
} else {
1282+
return mp_obj_new_int(source_freq / divide_b);
1283+
}
1284+
#else
1285+
return mp_obj_new_int(source_freq / divide_a / divide_b);
1286+
#endif
12811287
} else {
12821288
// set
12831289
uint32_t period;

tests/pyb/timer.py

+6
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,9 @@
1111
print(tim.prescaler())
1212
tim.period(400)
1313
print(tim.period())
14+
15+
# Setting and printing frequency
16+
tim = Timer(2, freq=100)
17+
print(tim.freq())
18+
tim.freq(0.001)
19+
print(tim.freq())

tests/pyb/timer.py.exp

+2
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@
22
200
33
300
44
400
5+
100
6+
0.001

0 commit comments

Comments
 (0)