Skip to content

Commit d29b709

Browse files
committed
stm32/timer: Enable ARPE so that timer freq can be changed smoothly.
The timer prescaler is buffered by default, and this patch enables ARPE which buffers the auto-reload register. With both of these registers buffered it's now possible to smoothly change the timer's frequency and have a smoothly varying PWM output.
1 parent 4a314a6 commit d29b709

1 file changed

Lines changed: 6 additions & 8 deletions

File tree

ports/stm32/timer.c

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,12 @@ STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, size_t n_args, cons
620620
#endif
621621
config_deadtime(self, args[6].u_int);
622622
}
623+
624+
// Enable ARPE so that the auto-reload register is buffered.
625+
// This allows to smoothly change the frequency of the timer.
626+
self->tim.Instance->CR1 |= TIM_CR1_ARPE;
627+
628+
// Start the timer running
623629
if (args[5].u_obj == mp_const_none) {
624630
HAL_TIM_Base_Start(&self->tim);
625631
} else {
@@ -1121,10 +1127,6 @@ STATIC mp_obj_t pyb_timer_freq(size_t n_args, const mp_obj_t *args) {
11211127
uint32_t prescaler = compute_prescaler_period_from_freq(self, args[1], &period);
11221128
self->tim.Instance->PSC = prescaler;
11231129
__HAL_TIM_SetAutoreload(&self->tim, period);
1124-
// Reset the counter to zero. Otherwise, if counter >= period it will
1125-
// continue counting until it wraps (at either 16 or 32 bits depending
1126-
// on the timer).
1127-
__HAL_TIM_SetCounter(&self->tim, 0);
11281130
return mp_const_none;
11291131
}
11301132
}
@@ -1155,10 +1157,6 @@ STATIC mp_obj_t pyb_timer_period(size_t n_args, const mp_obj_t *args) {
11551157
} else {
11561158
// set
11571159
__HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
1158-
// Reset the counter to zero. Otherwise, if counter >= period it will
1159-
// continue counting until it wraps (at either 16 or 32 bits depending
1160-
// on the timer).
1161-
__HAL_TIM_SetCounter(&self->tim, 0);
11621160
return mp_const_none;
11631161
}
11641162
}

0 commit comments

Comments
 (0)