November 2, 2024

Generate PWM signals in STM32 microcontrollers

Figure shown below illustrates a Pulse Width Modulation (PWM) signal.

Figure 1: Illustration of the PWM signal.

The PWM signal is defined by the following variables

  • s – length of the pulse
  • T_{\text{PWM}} – period of the PWM signal.
  • V_{\text{max}} – maximal (voltage) value of the PWM signal.

The frequency of the PWM signal is

(1)   \begin{align*}f_{\text{PWM}}=\frac{1}{T_{\text{PWM}}}\end{align*}

The duty cycle is defined by

(2)   \begin{align*}D=\frac{s}{T_{\text{PWM}}} \end{align*}

In the STM32 development environment, we select the frequency of the PWM signal by using the three parameters f_{\text{TC}}, k_{\text{PS}}, and k_{\text{P}}, and the following equation

(3)   \begin{align*}f_{\text{PWM}}=\frac{f_{\text{TC}}}{(k_{\text{PS}}+1)(k_{\text{P}}+1)} \end{align*}

where

  • f_{\text{TC}} is the frequency of a timer clock of an STM32 microcontroller.
  • k_{\text{PS}} is the prescaler value.
  • k_{\text{P}} is the period value.

The frequency the time clock f_{\text{TC}} of the clock is measured in MHz. Usually, every STM32 microcontroller has a maximal value. The prescaler value k_{\text{PS}} is used to downscale the frequency of the time clock. The period value k_{\text{P}} is the final parameter that determines the frequency of the PWM signal.

In the STM32CubeIDE development environment:

  • The period k_{\text{P}} is called “Auto Reload Register” which is abbreviated by ARR. That is, ARR=k_{\text{P}}.

In the STM32CubeIDE environment, the duty cycle is determined by

(4)   \begin{align*}D=\frac{CCR}{ARR+1} \end{align*}

where CCR is the Capture/Compare Register (CCR). We select the value of CCR in the interval 0,1,\ldots, ARR+1.

Let us illustrate this with an example. Let us suppose that we want to generate a PWM signal with the frequency of 10,000 \text{Hz}. Let us suppose that the time clock frequency is 84 MHz. Then, by selecting the prescaler value of k_{\text{PS}}=83 and the period of ARR=k_{\text{P}}=99, we obtain the desired frequency

(5)   \begin{align*}f_{\text{PWM}}=\frac{f_{\text{TC}}}{(k_{\text{PS}}+1)(k_{\text{P}}+1)}=\frac{84}{(83+1)(99+1)} \end{align*}