AnsweredAssumed Answered

STM32 PWM with variable Frequency

Question asked by Paul STM32_ on Mar 19, 2018
Latest reply on Mar 20, 2018 by Jan Waclawek

Hi at all,

I am working since some days with STM32 ( + HAL, CubeMX), because I need a Source for a PMW with variable Frequency, where f = 20..200kHz and Duty Cycle 0..100%.

To realize this I started with a regular PWM with a fixed Period. That worked fine.


int main(void) {




MX_TIM2_Init(200); // where 200 is  htim2.Init.Period
__HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_1, 100);



void MX_TIM2_Init(int period) {




however when I change the period, then I have to follow the steps:

 HAL_TIM_PWM_Stop(&htim2,TIM_CHANNEL_1);  // Stop PWM

 MX_TIM2_Init(40);  // re-initialize the Timer2

 HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1); // Start PWM again

 __HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_1, 20); // Set Duty Cuyle


it worked too, but it is slow and needed ca. 1000us. I need a method to switch faster (~100us). There are a lot of tricky ways to use the Timer in STM32, but I am not experienced enough to find the right way.

Can you give me a hint, what could be the most promising way to generate a PWM with a varibale Frequency and a fast way to switch (<100us)  the Frequency?


thanks in advance