STM32 PWM Mode Explained

In the previous article, STM32 Timer Interrupts Explained, we used the update event of TIM3 to call a function at a fixed interval. A timer can also drive a pin directly, without any help from the CPU, and the most common use of this feature is pulse width modulation, or PWM. A PWM output produces a square wave whose frequency and duty cycle are set by timer registers, so the program can change the signal at any time with a single write.

In this article, we will first look at what PWM is and how the period, the frequency, and the duty cycle describe a waveform. Then we will follow the counter, the auto-reload register, and the compare register to see how PWM mode 1 creates the output. After that, we will calculate the frequency and the duty cycle, configure TIM2 in STM32CubeMX, start the output with the HAL library, and finish with an example that fades an LED.

The examples in this article use the NUCLEO-F446RE board, with the same clock setup as in the previous two articles. The green user LED LD2 on this board is connected to pin PA5, which can also act as the output of TIM2 channel 1, so the example needs no external parts. The same approach applies to other STM32 families, but timer names, pin assignments, and counter widths can differ, so anything that is not the same everywhere is marked as device-dependent. This article is part of the STM32 timer tutorial series.

What Is PWM

Pulse width modulation is a method for controlling how much power a load receives by switching a digital signal on and off at a fixed rate. Instead of producing a steady voltage between 0 V and 3.3 V, the pin alternates between the two levels, and the share of time that it spends at the high level sets the average value that the load sees. This approach is efficient, because the output transistor of the pin is either fully on or fully off, and it needs only a digital output instead of a digital-to-analog converter.

Three terms describe a PWM signal. The period T is the time of one complete cycle, and the frequency is its inverse, which is f = 1 / T. Inside each period, the signal stays high for the time t_on and low for the remaining time t_off, so the period is the sum of the two. The duty cycle is the share of the period in which the signal is high, which is written as t_on / T and usually given as a percentage. A duty cycle of 25% means that the signal is high for a quarter of every period, and a duty cycle of 100% means that it is high all the time. The diagram below shows these quantities for a signal with a duty cycle of 40%.

PWM waveform showing the period, high time, and low time for a 40% duty cycle

For a logic level of 3.3 V, the average voltage equals the duty cycle multiplied by 3.3 V, so a duty cycle of 25% gives about 0.8 V and a duty cycle of 50% gives about 1.65 V. A load follows this average only when it reacts slowly compared with the PWM period. An LED, a motor winding, or a simple RC filter smooths the fast switching, whereas a fast logic input would still see every single pulse. The frequency must therefore be chosen to suit the load.

Common Uses of PWM

The most familiar use of PWM is LED brightness. The human eye cannot resolve flicker above a few hundred hertz, so a signal of 1 kHz looks steady, and the duty cycle then sets how bright the LED appears. Motor speed control works in a similar way, but the PWM signal goes to a driver stage such as a transistor or an H-bridge instead of directly to the motor, because a GPIO pin can only supply a small current. Motor drivers often use frequencies of around 20 kHz so that the switching is above the audible range.

Servo motors use PWM in a different way. The signal has a fixed frequency of 50 Hz, and the pulse width between 1 ms and 2 ms carries the position command, so the pulse width itself is the important value rather than the percentage. Buzzers, power converters, and simple digital-to-analog conversion with a filter are further uses that rely on the same mechanism.

PWM signals at 25%, 50%, and 75% duty cycle with the same frequency

How STM32 Timer PWM Works

In STM32 Timer Prescaler, Counter and ARR Explained, we saw that the counter CNT counts from 0 up to the auto-reload value ARR at a rate that the prescaler sets. PWM adds one more register for each output channel, the capture/compare register (CCR), which is named CCR1 to CCR4 for channels 1 to 4 on timers that have four channels. Next to each CCR sits a comparator that checks the counter against the register on every counter clock tick. The result goes to the output mode logic, which creates a reference signal, and the polarity and enable bits then decide whether the pin follows this signal directly or inverted.

The signal reaches the pin through the alternate-function multiplexer of the GPIO block. This is the reason why the channel pin must be configured for the timer, as described in GPIO Alternate Functions Pins. The roles of the three timer values are easy to separate. The prescaler and ARR set the length of the period, and the CCR sets the point inside the period at which the output changes. All channels of one timer share the same counter, prescaler, and ARR, but each channel has its own CCR, so one timer can produce several PWM signals with the same frequency and different duty cycles.

STM32 timer counter compared with ARR and CCR, with the PWM mode 1 output going high and low

PWM Mode 1

In PWM mode 1 with an up-counting timer, the channel is active as long as the counter value is lower than the CCR value, and it becomes inactive as soon as the counter reaches the CCR value. With active-high polarity, the pin therefore goes high when the counter returns to 0 at the update event, and it goes low at the compare match, which is the moment when CNT equals CCR. The high time is set by the CCR, and the period is set by ARR and the prescaler. Two special cases are useful to know. When CCR is 0, the output stays inactive for the whole period, and when CCR is larger than ARR, the output stays active for the whole period.


PWM Mode 2

PWM mode 2 works in the opposite way. The channel is inactive while the counter is lower than the CCR value and active after that. With the same CCR value, the output therefore stays low first and goes high only after the counter reaches the CCR value, so the high pulse sits at the end of the period instead of at the beginning. The duty cycle is 100% minus the duty cycle of mode 1. For example, with ARR = 999 and CCR = 250, mode 1 gives a duty cycle of 25%, while mode 2 gives 75%. Mode 2 is rarely needed in simple examples, but it is useful when a specific relation between two channels is required. In this article, we use mode 1 for all examples.


Compare Register Preload

Each CCR has an optional preload function. When the preload is enabled, a new value written to the CCR is held in a buffer and is copied to the active register only at the next update event. This prevents a change from taking effect in the middle of a period, which would create one pulse of an unexpected length. When HAL configures a PWM channel, it turns on the compare preload automatically, so you do not need to enable it yourself. As a result, every new duty-cycle value in the examples below starts at the beginning of the next period.


PWM Frequency and Duty Cycle

The equations in this section use four assumptions, so that every number can be checked against the code. The timer counts up in edge-aligned mode, the channel uses PWM mode 1 with active-high polarity, the repetition counter is 0, and the timer clock is 90 MHz, which is the APB1 timer clock of the NUCLEO-F446RE with the setup from the previous articles. If you need a reminder of how this clock is created, the article STM32 Clock System Explained covers it.

Calculate PWM Frequency

In edge-aligned mode, the PWM frequency is the same as the update frequency that we calculated in the previous article, because one PWM period is one counter period.

f_PWM = f_timer / ((PSC + 1) ร— (ARR + 1))

The prescaler divides the timer clock to produce the counter clock, and ARR sets how many counter ticks one period contains. With a timer clock of 90 MHz and PSC = 89, the counter clock is 1 MHz, so each tick lasts 1 ยตs. Adding ARR = 999 gives a period of 1000 ticks, which is 1 ms, and therefore a PWM frequency of 1 kHz. This is the same pair of values that we used for a period of 1 ms in the previous article.

If the timer is set to a center-aligned mode, the counter counts up and then down, so one PWM period lasts about twice as long, and the frequency becomes f_PWM = f_timer / (2 ร— (PSC + 1) ร— ARR). The exact reload behavior of this mode is described in the reference manual of your device, and it is not used in the rest of this article.

The choice of PSC and ARR also affects the resolution, which is the number of different duty-cycle steps. The counter has ARR + 1 positions per period, so ARR = 999 gives 1000 steps of 0.1% each. When a high frequency is needed, ARR becomes small and the resolution drops. For example, a frequency of 20 kHz with PSC = 0 requires ARR = 4499, which still gives 4500 steps, but a frequency of 1 MHz would leave only 90 steps. A good rule is to use the smallest prescaler that reaches the target frequency, because this leaves the largest possible value for ARR.


Calculate Duty Cycle

The duty cycle depends on the compare value and on the length of the period.

Duty cycle = CCR / (ARR + 1) ร— 100%

The divisor is ARR + 1 because the counter takes ARR + 1 different values during one period, and the output is high for CCR of them. To find the compare value for a wanted duty cycle, the equation is rearranged to CCR = duty cycle ร— (ARR + 1). With ARR = 999, the compare value in ticks is simply ten times the percentage, which makes the numbers easy to check. Because one tick lasts 1 ยตs in this setup, the high time in microseconds is equal to the CCR value.

CCRDuty cycleHigh time at 1 kHz
00%0 ยตs
25025%250 ยตs
50050%500 ยตs
75075%750 ยตs
1000100%1000 ยตs

The last row shows that a CCR value of 1000 is needed for a duty cycle of 100%, which is one more than ARR. Since the counter never reaches 1000 when ARR is 999, the compare match never happens, and the output stays active for the whole period. The same equations also cover the servo example from the first section. With PSC = 89 and ARR = 19999, the counter clock is 1 MHz and the period is 20 ms, which is 50 Hz, and a CCR value of 1500 creates a pulse of 1.5 ms.


Configure PWM in CubeMX

In this section, we will configure TIM2 in STM32CubeMX to generate a PWM signal. The signal will have the frequency of 1 kHz and an initial duty cycle of 50% on the LD2 pin of the NUCLEO-F446RE. Create a new project for this board and accept the default peripheral initialization. If you are not yet familiar with the tool, the article STM32CubeMX Explained describes the main views.

Select the Timer Channel and Pin

Open Pinout & Configuration, select Timers, and click TIM2. Set Clock Source to Internal Clock, and then set Channel1 to PWM Generation CH1. TIM2 is a 32-bit timer on the STM32F446, while TIM3 has a 16-bit counter, but both work for this example because the values are small.

CubeMX assigns the channel to a default pin when the mode is selected, and this pin may not be the one that we want. On the NUCLEO-F446RE board, PA5 is configured as the GPIO output LD2 by default, so we have to change it. In the Pinout view, click pin PA5 and choose TIM2_CH1 from the list, which gives the pin the alternate function AF1. The user label LD2 disappears at this point, and the macros LD2_Pin and LD2_GPIO_Port are no longer generated, so any code that uses them must be removed.

STM32CubeMX pinout view with pin PA5 set to TIM2_CH1 on the NUCLEO-F446RE

Set Prescaler, Period, and Pulse

Next, open the Parameter Settings of TIM2. First confirm in the Clock Configuration tab that HCLK is 180 MHz and that the APB1 timer clocks are 90 MHz. Then enter the values from the table below, which follow the calculation from the previous section.

ParameterValueReason
Prescaler (PSC โ€“ 16 bits value)89Divides 90 MHz by 90 to give a 1 MHz counter clock
Counter ModeUpThe counter runs from 0 to ARR
Counter Period (AutoReload Register โ€“ 32 bits value)999A period of 1000 ticks, which is 1 ms and 1 kHz
auto-reload preloadEnableARR changes take effect at the next update event
ModePWM mode 1The output is active while CNT is lower than CCR
Pulse (32 bits value)500An initial duty cycle of 500 / 1000 = 50%
Fast ModeDisableKeeps the normal output timing
CH PolarityHighAn active channel drives the pin high

The Pulse field is the initial value of the CCR, and it is the number that we will change at run time. The CH Polarity setting decides which level counts as active. When it is set to Low, the pin is inverted, so a duty cycle of 25% would keep the pin low for a quarter of the period instead of high.

TIM2 parameter settings in CubeMX with prescaler 89, period 999, PWM mode 1, and pulse 500

Review the Generated Code

After the code is generated, the function MX_TIM2_Init() in main.c contains the timer settings, followed by a channel configuration structure that holds the PWM settings.

The last call, HAL_TIM_MspPostInit(), configures the GPIO pin for the timer output. As in the previous article, the generated code prepares everything but does not start the counter, so the output stays idle until we add the start call ourselves.


Generate PWM with HAL

The generated configuration is complete, so the program only has to start the channel and later change the compare value. Both tasks need only a few lines of code.

Start the PWM Output

The function HAL_TIM_PWM_Start() enables the output of the selected channel and starts the counter. It takes the timer handle and the channel as arguments, and it belongs in the user code section of main(), after the initialization functions.

No interrupt is needed for this mode, because the hardware creates the whole waveform. The function HAL_TIM_PWM_Stop() stops the channel again. On advanced-control timers such as TIM1, the same start function also sets the main output enable bit, which these timers need before any pin can switch.


Change the Duty Cycle While Running

To change the duty cycle, we write a new value to the CCR. The macro __HAL_TIM_SET_COMPARE() does this for the chosen channel, and the macro __HAL_TIM_GET_COMPARE() reads the current value back. Since the compare preload is active, the new value takes effect at the start of the next period, so the output never produces a pulse that is cut off in the middle.

The function below reads ARR from the timer, so it stays correct when the period is changed.

The frequency can be changed in the same way with __HAL_TIM_SET_AUTORELOAD() or __HAL_TIM_SET_PRESCALER(). When ARR changes, the CCR no longer corresponds to the same percentage, so the compare value must be calculated again for the new period.


Alternate Function Pin Setup

A timer channel can only drive a pin that is configured for the matching alternate function. The generated function HAL_TIM_MspPostInit() does this configuration, and for our example it contains the following settings.

The mode GPIO_MODE_AF_PP is the push-pull type that we described in GPIO Push-Pull vs Open-Drain, now controlled by the timer instead of the output data register. The alternate function number AF1 selects TIM2 for this pin, and it is device-dependent, so the datasheet of your device has to be checked when you use another pin or MCU. If you write the code without CubeMX, the same setting is made through the MODER and AFR registers, which are covered in GPIO Registers Explained.


Fade an LED with PWM

We can now combine the steps in one complete example. The program changes the duty cycle of TIM2 channel 1 slowly from 0% to 100% and back, so that the green LED LD2 fades in and out. The signal stays at 1 kHz during the whole process, so the LED never appears to flicker.

Add the following code inside the user code sections.

The variable level counts from 0 to 100 and then back to 0, and the program waits 20 ms after each step. One full fade in and out therefore takes about 4 seconds. Because ARR is 999, multiplying level by 10 gives a compare value from 0 to 1000, which matches a duty cycle from 0% to 100%. The delay blocks the program, but this is fine here because the main loop has nothing else to do. The PWM signal keeps running on its own between the updates.


Common PWM Problems

Most PWM problems come from a small number of setup mistakes. The output depends on the timer clock, the compare register, the pin configuration, and the start call. Therefore a single wrong value is enough to produce a signal that looks very different from the expected one.

Wrong Alternate Function Pin

When the pin is not configured for the timer, the channel works inside the chip, but nothing appears on the pin. This happens when the pin is still set as a GPIO output, when a different alternate function is selected, or when the code uses a pin that does not offer the channel. On the NUCLEO-F446RE, PA5 is the LD2 output by default, and it is also the clock line of SPI1, so another peripheral can claim the same pin. The fix is to check the pin list in the datasheet and to confirm in CubeMX that the pin shows the label of the timer channel.


Incorrect Timer Clock Calculation

A PWM frequency that is off by a factor of two is almost always caused by the use of the APB peripheral clock instead of the timer clock. The timer clock of APB1 on the STM32F446 is 90 MHz, which is twice the 45 MHz peripheral clock, as we saw in the previous articles. Another typical mistake is to enter the division factors instead of the register values, such as 90 instead of 89 for the prescaler. The frequency equation from this article should be used to verify the numbers before the code is run.


Duty Cycle Always 0% or 100%

A duty cycle that never changes usually points to the compare value. When CCR is 0, the output stays inactive, and when CCR is larger than ARR, the output stays active. A common cause is writing a percentage directly into the CCR, for example writing 50 when ARR is 999, which gives a duty cycle of about 5%. Another cause is a change of ARR to a value below the current CCR, which turns the output fully active. A polarity setting of Low also swaps the meaning of the two levels, so that a duty cycle of 0% looks like a permanently high pin.


PWM Channel Not Started

If the program never calls HAL_TIM_PWM_Start() for the channel, the timer is configured but idle, and the pin stays at its idle level. This is the PWM equivalent of the missing start call in the previous article. It is also possible to start the wrong channel or the wrong timer handle, so the arguments should match the channel that was configured in CubeMX. In the debugger, a stopped timer is easy to recognize, because the CNT register does not change.


Timer and Channel Limitations

Not every timer can generate PWM. The basic timers TIM6 and TIM7 have no output channels at all, as described in STM32 Timer Types Explained. The number of channels, the counter width, and the available pins differ between timers and between devices, and some channels exist only as complementary outputs of advanced-control timers. All channels of one timer also share the same period, so two signals with different frequencies need two different timers. Finally, a pin may exist on one package of a device and not on another, so the datasheet of the exact part number is the final reference.


Conclusion

A timer creates a PWM signal by comparing its counter with a compare register. The prescaler and the auto-reload register set the period, so the frequency is f_timer / ((PSC + 1) ร— (ARR + 1)). The compare register CCR sets the point at which the output changes, so the duty cycle is CCR / (ARR + 1). In PWM mode 1, the channel is active while the counter is below the CCR, and the hardware keeps producing the waveform without any further work from the CPU.

The most important points are to start from the timer clock, to check the pin and its alternate function, and to remember that the HAL library does not start the channel until the program calls HAL_TIM_PWM_Start(). The same two steps, starting the channel and updating the compare value, are enough to build simple effects such as the LED fade. In the next articles of the timer series, we will use the same counter and compare logic for other timer tasks.


Download the Project Here

Download the CubeMX project files and HAL source code โ€” all tested on real hardware.

If you find this useful, you can support us with a Donation as well.

Article by Yashmiti

Yashmiti is a technical writer at STM32Guide, where she creates tutorials and guides that help embedded-systems learners and developers work confidently with STM32 microcontrollers. Her writing covers tools like STM32CubeIDE and STM32CubeMX, along with peripherals and communication protocols โ€” always with an emphasis on clear explanations and hands-on examples that take readers from concept to working project.

She's also part of the effort to build STM32Guide into an organized, easy-to-navigate resource for the STM32 community.

Leave a Comment