Electronic – How to set PWM frequency with high granuality

microcontrollerpwmstm32timer

I want to create a PWM at 100kHz that can have 1000 steps. e.g. when I set CCR1 to 0%, the PWM is off an when I set CCR1 to 499 it should be 50% and obviously at CCR1 = 999, it should be full duty cycle of 100%.

The CPU_CLK is 80MHz…but I can not achieve this. here is my code so far:

  htim1.Instance = TIM1;
  htim1.Init.Prescaler = 0;
  htim1.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED2;
  htim1.Init.Period = 1000-1;
  htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim1.Init.RepetitionCounter = 0;
  htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;

This gives me a PWM with frequency of 40kHz….far below 100kHz…the Prescalare is already at minimum …is this impossible to achive?

The chip is STM32L476.

Best Answer

The short answer is, it's not trivial with a clock of 80 MHz unless you pull off some dithering techniques (see below).

$$\mathcal{f_{clk}}=PWM_{frequqncy}\times2^{steps} $$

In your case, steps required is 10 bits...therefore you need at least a main clock of 100MHz.

The document I linked in my comment, shows some complex ways to achieve this with lower clock rates by dithering and combining more timers(it is quite complex). Here is the document by STM itself.

Obviously, Another solution would be using another MCU from the same family with higher clock speeds if your application/budget allows it.