STM32 Timer Settings Changing

I'm using STM32F407VG. I created a 28 khz square wave by using Timer PWM Generation. When i look at the oscilloscope, i can see it clearly. I'm having a trouble to change frequency of PWM without stopping it.

I found two functions which are __HAL_TIM_SET_PRESCALER() and __HAL_TIM_SET_AUTORELOAD().

HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
__HAL_TIM_SET_AUTORELOAD(&htim2,99);
__HAL_TIM_SET_PRESCALER(&htim2,29);


I set prescaler and autoreload in cubemx. Prescaler is 2 and ARR is 999 but i want change prescaler to 29 and arr to 99. I can see square wave with HAL_TIM_PWM_Start() but when i added other 2 functions.It goes away. I commented those prescaler and arr functions and i saw that PWM was working.

I dont not know how to change prescaler and arr values without stopping the PWM.

• Is ARR buffer/preload enabled? TIM->CR1:ARPE bit controls this. – Tagli Apr 16 at 12:55

2 Answers

Let's say you update ARR as 90 when your CNT register is 95, when do you think the next update/reload happens?

Options:

when you set ARR check CNT if it's higher than next ARR value.(poor)

set CNT to 0 when you are updating ARR.(OK)

Enable relevant timer interrupt, update ARR only in timer overflow ISR.(Best in my opinion)

I solved my problem today. I was changing ARR and Prescaler together. But i have seen a guy's comment which was about missing part of changing.

So i decided to change all of them at the same time.

__HAL_TIM_SET_AUTORELOAD();
__HAL_TIM_SET_PRESCALER();
__HAL_TIM_SET_COMPARE();


When i had done like this. It worked. I hope it will be helpful for anyone who faces the same struggle.