Changing the timer frequency dynamically

Solution 1:

I didn't find anything in the reference manual but finally got to test the behaviour on actual hardware:

  • Setting the ARR to a value lower than the current counter value doesn't create an interrupt/update event/etc, the timer keeps counting up
  • Manually creating an update event automatically restarts the counter
  • Setting the ARR to the current counter value creates an update event

I don't want to restart the counter when setting the ARR value to something higher than the counter value. The solution is to create a manual update event when the ARR value is lower than the counter value. There shouldn't be a problem with the counter reaching ARR while setting it because that automatically creates an update event.

This seems to work as expected:

void update_arr (TIM_HandleTypeDef* htim, uint16_t arr) {
    __HAL_TIM_SET_AUTORELOAD(htim, arr);
    if (__HAL_TIM_GET_COUNTER(htim) >= __HAL_TIM_GET_AUTORELOAD(htim)) {
        htim->Instance->EGR  |= TIM_EGR_UG;
    }
}