In this tutorial, we’ll discuss the STM32 PWM output generation using the STM32 timer modules in PWM mode. You’ll learn how the PWM signal is generated in hardware, how to set its frequency and duty cycle with the exact formulas (with real numbers), what the difference is between PWM mode 1 and PWM mode 2, and which STM32 Blue Pill pins can output PWM.
Then, we’ll configure the timer in STM32CubeMX and write two STM32 PWM example codes with HAL: an LED dimmer on TIM2 CH1, and a 4-channel PWM output that shows PWM mode 1 vs mode 2 on my oscilloscope. At the end, you’ll find a troubleshooting section for the usual “my STM32 PWM output is not working” problems. This is the first part of our STM32 PWM tutorial series. Without further ado, let’s get right into it!
STM32 PWM Example: HAL_TIM_PWM_Start & Duty Cycle
To output PWM on an STM32, set a timer channel to PWM Generation CHx in CubeMX, choose the Prescaler (PSC) and the Counter Period (ARR) for the frequency you need, generate the code, then start the channel and write the duty cycle to its CCR register. Here are the CubeMX values for a 1kHz PWM on the Blue Pill’s TIM2 CH1 (PA0) at 72MHz:
| CubeMX Setting (TIM2) | Value | Why |
|---|---|---|
| Clock Source | Internal Clock | TIM2 runs at 72MHz on the Blue Pill |
| Channel1 | PWM Generation CH1 | PA0 becomes the PWM output pin |
| Prescaler (PSC) | 72-1 | 72MHz / 72 = 1MHz timer tick (1µs) |
| Counter Period (ARR) | 1000-1 | 1MHz / 1000 = 1kHz PWM, 1000 duty cycle steps |
| auto-reload preload | Enable | New ARR values apply at the next period (no glitches) |
| Mode / Pulse (CCR1) | PWM mode 1 / 250 | 250 / 1000 = 25% duty cycle |
|
1 2 |
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); // Start the PWM output on PA0 __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 500); // Change the duty cycle to 50% (CCR1 = 500) |
Tip: PWM Frequency = FTIM / ((PSC + 1) × (ARR + 1)) and Duty Cycle = CCR / (ARR + 1). With PSC = 71 and ARR = 999 at 72MHz: 72,000,000 / (72 × 1000) = 1,000Hz, and CCR = 250 gives 250 / 1000 = 25%. You can get these numbers for any frequency with our STM32 PWM Calculator.
Note: All examples in this tutorial are tested with: STM32 Blue Pill (STM32F103C8T6). In STM32CubeIDE 2.x, note that the CubeMX configuration tool is no longer built into the IDE, so you’ll configure the project in the standalone STM32CubeMX and import it into the IDE. The steps are in the CubeMX configuration section.
STM32 PWM Introduction
Pulse Width Modulation (PWM) is a technique for generating a continuous HIGH/LOW alternating digital signal and programmatically controlling its pulse width and frequency. Certain loads like LEDs and motors respond to the average voltage of the signal, which gets higher as the PWM signal’s pulse width is increased. This technique is widely used in embedded systems to control the brightness of LEDs, the speed of motors, and many other applications.
PWM Frequency
The first feature of a PWM signal is the frequency, which is basically a measure of how fast the PWM signal keeps alternating between HIGH and LOW. The frequency is measured in Hz, and it’s the inverse of the full period time interval: FPWM = 1 / T. A 1kHz PWM signal repeats every 1ms.
PWM Duty Cycle
The PWM duty cycle is the feature that we’re always most interested in. It’s a measure of how long the PWM signal stays ON relative to the full PWM cycle period: Duty Cycle = TON / T × 100%. It directly sets the average voltage of the PWM signal that most loads respond to. On a 3.3v STM32 pin, a 25% duty cycle averages about 0.83v and 50% averages 1.65v. That’s why we change the duty cycle to control things like the LED brightness or the DC motor speed.
PWM Resolution
The PWM resolution is expressed in bits. It’s the number of discrete duty cycle levels between 0% and 100%. A PWM resolution of only 3 bits means there are only 8 discrete levels for the duty cycle. On the other hand, a PWM with a resolution of 8 bits will have 256 discrete levels over the same range. You can use the interactive tool below to test this yourself.
Average voltage:
PWM Duty Cycle:
50%
PWM Frequency:
x Hz
PWM Duty Cycle Resolution:
Set the PWM resolution to 3-bit and sweep across the entire range of the duty cycle. Then change the resolution up to 8 bits or even 16 bits to see the huge difference in the degree of control you'll have over the duty cycle value. It becomes incredibly smooth as the resolution increases. You can use the keyboard arrow keys for fine adjustment of the duty cycle while testing high resolutions.
Note: A higher PWM resolution is always a desirable thing to have. However, it's always in inverse proportion to the PWM frequency. The higher the PWM frequency you choose, the lower the PWM resolution becomes. There is no way to go around this fact, and you'll see exactly why in the formulas section below.
STM32 PWM Mode in Timer Explained
As we've discussed in the STM32 Timers Tutorial, the STM32 timer modules can operate in a variety of modes, one of which is the PWM mode. In PWM mode, the timer gets clocked from an internal source and its counter (CNT) counts up from 0 to the auto-reload register value (ARR), then it rolls over back to 0 and starts again. At the same time, the counter value is continuously compared with the channel's capture/compare register (CCRx).
In PWM mode 1 (up-counting), the channel output is HIGH while CNT < CCRx and LOW while CNT ≥ CCRx. So the ARR register sets the period (frequency) of the PWM signal, and the CCRx register sets its duty cycle. The animation below shows exactly this with ARR = 999 and 4 different CCR values. Note what happens when CCR goes above ARR: the compare never matches, and the output stays HIGH (100% duty cycle).

This is called the edge-aligned, up-counting PWM mode, and it's the most common one. Here is the timing diagram from my original tutorial that shows how the ARR value sets the PWM period and how the CCRx value sets the duty cycle:

STM32 Timers PWM Output Channels
Each STM32 timer channel has an output stage with a comparator and an output control block. The output stage generates an intermediate waveform called OCxREF (active high), and the channel polarity bit acts at the end of the chain, just before the pin. Here is the output stage that drives the OCx pins:

A single STM32 timer usually has multiple channels (4 on the general-purpose timers). Therefore, using a single timer, you can generate multiple PWM signals with different duty cycles. They all share the same timer counter, so they have the same frequency and they're all in sync. We'll do exactly this in Example 2. Here is the general-purpose timer (TIM2) block diagram that shows the 4 output compare channels and their output drivers:

STM32 Timers In PWM Mode
The PWM mode can be selected independently on each channel (one PWM per OCx output) by writing 110 (PWM mode 1) or 111 (PWM mode 2) in the OCxM bits in the TIMx_CCMRx register. You should also enable the CCRx preload register by setting the OCxPE bit, and optionally the auto-reload preload by setting the ARPE bit in TIMx_CR1. With the preload enabled, a new CCR (or ARR) value you write takes effect at the next update event, so you'll never get a broken or glitched PWM period. The HAL function HAL_TIM_PWM_ConfigChannel() sets OCxPE for you.
The OCx polarity is programmable using the CCxP bit in the TIMx_CCER register (active high or active low). The timer can generate PWM in edge-aligned mode or center-aligned mode depending on the CMS bits in the TIMx_CR1 register. All of these details are in the RM0008 reference manual (section 15.3.9 for TIM2 to TIM5).
STM32 PWM Frequency, Duty Cycle & Resolution Formulas
Here are the 3 formulas you'll need to set up any STM32 PWM output. They're for the edge-aligned, up-counting PWM mode 1, which is the CubeMX default. FTIM is the clock that drives the timer, PSC is the Prescaler register value, and ARR is the Counter Period value you set in CubeMX.
STM32 PWM Frequency
Tip: FPWM = FTIM / ((PSC + 1) × (ARR + 1))
The +1 is there because the prescaler divides by PSC + 1, and the counter counts from 0 up to ARR, which is ARR + 1 steps. That's why you'll see values like 72-1 and 1000-1 in CubeMX: you type the division you want and subtract 1. To get a target frequency, pick the PSC that gives you a convenient timer tick, then solve for ARR: ARR = FTIM / ((PSC + 1) × FPWM) - 1.
STM32 PWM Duty Cycle
Tip: Duty Cycle = CCRx / (ARR + 1) → CCRx = Duty × (ARR + 1)
CCRx = 0 gives you 0% (the output is always LOW), and any CCRx value greater than ARR gives you 100% (always HIGH). So with ARR = 999, you get exactly 1000 duty cycle steps from 0 to 1000. A common mistake (that was even in an older version of this article) is to use CCR / ARR. For a 25% duty cycle with ARR = 65535, the right value is 0.25 × 65536 = 16384, not 16383.
STM32 PWM Resolution
Tip: Resolution = log2(ARR + 1) bits and the max resolution at a given frequency is log2(FTIM / FPWM) with PSC = 0
To get the highest resolution for a PWM frequency, set PSC = 0 and use the largest ARR that gives you that frequency. On the 16-bit timers of the STM32F103, the ARR can't go above 65535, so the max resolution is 16 bits. Here are some real numbers for the Blue Pill (FTIM = 72MHz, PSC = 0):
| PWM Frequency | ARR (PSC = 0) | Duty Cycle Steps | Resolution |
|---|---|---|---|
| 1.0986kHz | 65535 | 65536 | 16-bit (Example 1) |
| 10kHz | 7199 | 7200 | 12.8-bit |
| 20kHz (motors, silent) | 3599 | 3600 | 11.8-bit |
| 50kHz | 1439 | 1440 | 10.5-bit |
| 100kHz | 719 | 720 | 9.5-bit |
| 281.25kHz | 255 | 256 | 8-bit |
| 1MHz | 71 | 72 | 6.2-bit |
Notice how the resolution drops as the frequency goes up, exactly as the note in the introduction said. If you need to configure the PWM frequency and resolution at run time, or for a different timer clock, check out the STM32 PWM Frequency & Resolution tutorial, the 2nd part of this series. And for a quick answer, use the STM32 PWM Calculator.
Note: Timer clock on the Blue Pill: with SYSCLK = 72MHz, the APB1 bus runs at 36MHz, but its timers (TIM2, TIM3, TIM4) get 2 × 36 = 72MHz. The STM32 doubles the timer clock whenever the APB prescaler isn't 1. TIM1 is on APB2, which is at 72MHz. So all 4 timers run at 72MHz. If your PWM frequency is exactly half or double of what you expected, this is usually the reason.
STM32 PWM Mode 1 vs PWM Mode 2
The STM32 timers have 2 PWM modes that you can choose for each channel in CubeMX (the Mode field under PWM Generation Channel x). PWM mode 2 is simply the inverse of PWM mode 1 for the same CCR value:
| PWM Mode 1 | PWM Mode 2 | |
|---|---|---|
| Up-counting output (OCxREF) | HIGH while CNT < CCRx, then LOW | LOW while CNT < CCRx, then HIGH |
| Duty cycle (active high) | CCRx / (ARR + 1) | 1 - CCRx / (ARR + 1) |
| CCRx = 250, ARR = 999 | 25% | 75% |
| CCRx = 0 | 0% (always LOW) | 100% (always HIGH) |
| CCRx > ARR | 100% (always HIGH) | 0% (always LOW) |
| OCxM bits (TIMx_CCMRx) | 110 | 111 |
| HAL setting | TIM_OCMODE_PWM1 | TIM_OCMODE_PWM2 |
PWM mode 2 with an active-high polarity gives the same pin signal as PWM mode 1 with an active-low polarity (the CCxP bit inverts the output after the mode). So which one should you use? Use mode 1 for normal PWM where a bigger CCR means a longer HIGH pulse. Mode 2 is useful when your load is active low (like an LED connected between 3.3v and the pin), or when you need 2 channels that are inverted copies of each other with the same CCR value. Note that this is not the same as complementary PWM with dead-time, which needs TIM1 and its CHxN outputs. That's covered in the STM32 Complementary PWM & Dead-Time tutorial.
In the center-aligned mode, PWM mode 1 is active while the counter is below CCRx in both directions (counting up and down). In Example 2, you'll see mode 1 and mode 2 side by side on my oscilloscope with the same CCR value.
STM32 Edge-Aligned vs Center-Aligned PWM
The STM32 timers can generate PWM signals in 2 alignment modes, and you select them with the Counter Mode setting in CubeMX.
Edge-Aligned PWM Mode
In the edge-aligned mode, the counter counts up (or down), so all channels of the timer switch at the start of each period (on the same edge). In the example below, we consider PWM mode 1 with ARR = 8. The reference signal OCxREF is HIGH as long as TIMx_CNT < TIMx_CCRx, else it becomes LOW. If the compare value in TIMx_CCRx is greater than the auto-reload value (in TIMx_ARR), then OCxREF is held at 1. If the compare value is 0, then OCxREF is held at 0.

Center-Aligned PWM Mode
In the center-aligned mode, the counter counts up from 0 to ARR and then down to 0, so the pulses of all channels are centered in the middle of the period. A full PWM period takes 2 × ARR counts, so the frequency formula becomes FPWM = FTIM / (2 × (PSC + 1) × ARR). The compare flag is set when the counter counts up, when it counts down, or both, depending on the CMS bits (center-aligned mode 1, 2, or 3). The diagram below shows some center-aligned PWM waveforms with ARR = 8 in PWM mode 1.

The center-aligned PWM generates fewer harmonics and it's the go-to choice for 3-phase motor control. You can learn more about both modes in the STM32 3-Phase PWM (Center-Aligned) and the STM32 Edge-Aligned PWM (3-Phase) tutorials.
STM32 Blue Pill PWM Pins
The STM32F103C8T6 on the Blue Pill board has 4 timers with PWM outputs, 4 channels each. That's 16 PWM pins in the default pin mapping. Each timer can run at its own frequency, and the 4 channels of each timer share that frequency with independent duty cycles.
| Timer | CH1 | CH2 | CH3 | CH4 | Notes |
|---|---|---|---|---|---|
| TIM1 (advanced) | PA8 | PA9 | PA10 | PA11 | Complementary outputs CH1N - CH3N on PB13, PB14, PB15. PA9/PA10 are also USART1, PA11 is USB D- |
| TIM2 | PA0 | PA1 | PA2 | PA3 | Used in both examples of this tutorial |
| TIM3 | PA6 | PA7 | PB0 | PB1 | |
| TIM4 | PB6 | PB7 | PB8 | PB9 | PB6/PB7 are also I2C1 |
Some of these pins can be moved to other pins with the timer remap options in CubeMX (for example, TIM2 CH1 to PA15 or TIM3 to PB4, PB5). The onboard LED on PC13 has no timer channel, so you can't dim it with hardware PWM. That's why we use an external LED on PA0 in Example 1. For the full pin map, check out the STM32 Blue Pill Pinout guide.
Note: TIM2 on the STM32F103 is a 16-bit timer (ARR up to 65535). On the STM32F2, F4, G4, L4, and many other families, TIM2 (and TIM5) are 32-bit timers, so the ARR can go up to 4,294,967,295. The code in this tutorial works on those too, but the resolution numbers above are for the Blue Pill.
STM32 PWM HAL Functions
These are the STM32 HAL functions and macros you'll need for PWM output. The timer and channel configuration itself is generated by CubeMX in the MX_TIMx_Init() function, so you only call these in your application code.
| HAL Function / Macro | What It Does |
|---|---|
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1) | Enables the PWM output of the channel and starts the timer counter. On TIM1 (and other advanced timers) it also sets the MOE bit to enable the outputs |
HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1) | Disables the channel output (and stops the counter if no other channel is enabled) |
HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1) | Starts the complementary output CHxN of an advanced timer (TIM1) |
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, ccr) | Sets the duty cycle (writes CCR1). Same as TIM2->CCR1 = ccr; |
__HAL_TIM_GET_COMPARE(&htim2, TIM_CHANNEL_1) | Reads the current CCR1 value |
__HAL_TIM_SET_AUTORELOAD(&htim2, arr) | Changes the ARR (PWM period / frequency) at run time |
__HAL_TIM_SET_PRESCALER(&htim2, psc) | Changes the prescaler at run time (applies at the next update event) |
HAL_TIM_PWM_Start_DMA() / HAL_TIM_PWM_Start_IT() | Start PWM with DMA (duty cycle values from a buffer) or with interrupts |
Both HAL_TIM_PWM_Start() and HAL_TIM_PWM_Stop() take 2 parameters only: the timer handle and the PWM channel. Here is how to set a 25% duty cycle on TIM2 CH1 when ARR = 65535 (as in Example 1). From the duty cycle formula, CCR1 = 0.25 × (65535 + 1) = 16384:
|
1 2 3 4 |
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); // Start TIM2 CH1 PWM output __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 16384); // 25% duty cycle (16384 / 65536) // Or write the register directly: TIM2->CCR1 = 16384; |
You can change TIMx->CCRy to match the hardware timer (x) and the PWM output channel (y) you're using, and you're good to go. All of these functions are documented in ST's UM1850 HAL user manual.
Required Parts For STM32 PWM Examples
All the examples in this tutorial are done using the parts below. The oscilloscope is optional: you can see the LED dimming without it, but it's the only way to check the exact PWM frequency and duty cycle.
| QTY. | Component Name | Amazon.com | AliExpress |
| 1 | STM32 Blue Pill Board (STM32F103C8T6) | Amazon | AliExpress |
| 1 | ST-Link V2 Debugger | Amazon | AliExpress |
| 1 | Breadboard | Amazon | AliExpress |
| 1 | LEDs Kit | Amazon | AliExpress |
| 1 | Resistors Kit (330Ω) | Amazon | AliExpress |
| 1 | Jumper Wires Pack | Amazon | AliExpress |
| 1 | Micro USB Cable | Amazon | AliExpress |
★ Check The Links Below For The Full Course Kit List & LAB Test Equipment Required For Debugging ★
STM32 PWM Output Example: LED Dimmer
In this STM32 PWM example, we'll set up Timer2 to operate in PWM mode with the internal clock and enable CH1 (PA0) as the PWM output channel. The ARR value is set to the maximum 65535, which gives us the full 16-bit resolution, and a PWM frequency of 72,000,000 / (1 × 65536) = 1098.6Hz. Then, in the main loop, we'll sweep the duty cycle from 0% up to 100% and back down by writing to the CCR1 register, so the LED brightness follows the same pattern.
STM32 PWM LED Dimmer Wiring

Connect an LED with a 330Ω resistor in series to the PA0 pin of the Blue Pill, and the LED's cathode (short leg) to GND. Power the Blue Pill from its micro-USB port. The ST-Link V2 connects to the 4-pin SWD header at the end of the board with 3 wires only: SWDIO, SWCLK, and GND. Leave the ST-Link's 3.3V pin unconnected, because the board is powered from USB.
PA0 TIM2 CH1 PWM output → 330Ω resistor → LED anode (long leg)
GND LED cathode (short leg) → Blue Pill G pin, and ST-Link GND
SWCLK Blue Pill CLK (SWD header) → ST-Link SWCLK
SWDIO Blue Pill DIO (SWD header) → ST-Link SWDIO
STM32 PWM CubeMX Configuration Steps
If you're new to the STM32 development tools, check out the STM32 Getting Started Tutorial first. Here are the configuration steps in STM32CubeMX:
#1
Open STM32CubeMX, click Access to MCU Selector, search for STM32F103C8T6, and double-click its name to create a new project.
#2
Go to System Core > SYS and set Debug to Serial Wire.
Note: Don't skip step #2. If Debug is left at No Debug, the generated code disables the SWD pins at startup, and the ST-Link can't connect to the Blue Pill after the first flash (the troubleshooting section shows how to recover it).
#3
Go to Timers > TIM2, set the Clock Source to Internal Clock, and set Channel1 to PWM Generation CH1. In the Parameter Settings, set the Prescaler to 0, the Counter Period (ARR) to 65535, and the auto-reload preload to Enable.

Leave the PWM channel settings at PWM mode 1, Pulse 0, and CH Polarity High. PA0 turns green as TIM2_CH1.
#4
Go to System Core > RCC and set the High Speed Clock (HSE) to Crystal/Ceramic Resonator (the Blue Pill has an 8MHz crystal).

#5
In the Clock Configuration tab, select HSE as the PLL source, PLLMul ×9, and PLLCLK as the System Clock source, then type 72 in the HCLK box and press Enter.

The APB1 timer clocks and APB2 timer clocks should both show 72MHz.
#6
In the Project Manager tab, name the project, set the Toolchain / IDE to STM32CubeIDE, and click GENERATE CODE.
In STM32CubeIDE 2.x, use File > Import > Existing Projects into Workspace and select the generated folder (or double-click the generated .project file). Every time you change the configuration and generate the code again in CubeMX, press F5 on the project in the IDE to refresh it. Your own code is kept as long as it's written between the USER CODE BEGIN and USER CODE END comments.
STM32 PWM Example Code (LED Dimmer)
Here is the full code for the main() function of this LAB. The SystemClock_Config(), MX_GPIO_Init(), and MX_TIM2_Init() functions are generated by CubeMX from the configuration steps above, so you don't need to write them (they're in the download files below).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/* * LAB Name: STM32 PWM Output Example (LED Dimmer) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com * * TIM2 CH1 (PA0) PWM output: 72MHz / (0+1) / (65535+1) = 1098.6Hz, 16-bit resolution * The duty cycle sweeps 0% -> 100% -> 0% (about 0.94s each way) */ #include "main.h" TIM_HandleTypeDef htim2; void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_TIM2_Init(void); int main(void) { int32_t CH1_DC = 0; HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_TIM2_Init(); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); while (1) { // Ramp Up: 0 -> 65535 (CCR1 never exceeds the 16-bit ARR) for (CH1_DC = 0; CH1_DC <= 65535; CH1_DC += 70) { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, CH1_DC); HAL_Delay(1); } // Ramp Down: 65535 -> 0 (CCR1 never goes below 0) for (CH1_DC = 65535; CH1_DC >= 0; CH1_DC -= 70) { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, CH1_DC); HAL_Delay(1); } } } |
And here is the CubeMX-generated MX_TIM2_Init() function, so you can check your own settings against it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
static void MX_TIM2_Init(void); int main(void) { int32_t CH1_DC = 0; HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_TIM2_Init(); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); while (1) { // Ramp Up: 0 -> 65535 (CCR1 never exceeds the 16-bit ARR) for (CH1_DC = 0; CH1_DC <= 65535; CH1_DC += 70) { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, CH1_DC); HAL_Delay(1); } // Ramp Down: 65535 -> 0 (CCR1 never goes below 0) for (CH1_DC = 65535; CH1_DC >= 0; CH1_DC -= 70) { __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, CH1_DC); HAL_Delay(1); } } } |
STM32 PWM Code Explanation
After the CubeMX-generated initialization, HAL_TIM_PWM_Start() enables the TIM2 CH1 output and starts the counter. From that point, the timer hardware generates the 1098.6Hz PWM signal on PA0 on its own, and the CPU only has to change the duty cycle.
The first for loop ramps the CCR1 value up from 0 to 65535 in steps of 70, with a 1ms delay per step. That's 937 steps, so the LED goes from OFF to full brightness in about 0.94 seconds. The second loop does the opposite. Note that the loop limits keep CCR1 inside the 0 to 65535 range. In an older version of this code, the value went past 65535 (TIM2 on the F103 is 16-bit, so 65590 became 54) and below 0, which made the LED flash at both ends of the sweep.
STM32 PWM LED Dimmer Testing Results
Here are my oscilloscope captures of the PWM output on PA0.
CH1 (yellow) is the TIM2 CH1 output on PA0, which drives the LED through the 330Ω resistor.
The frequency counter reads 1.0987kHz, which matches the 1098.6Hz calculated from the formula. In this capture, the duty cycle sweep is frozen at 46.71%: the output is HIGH for 425.5µs of each 910.2µs period.
At a low duty cycle of 17.94%, the output is HIGH for only 163.3µs of each period, and the LED is dim:
At 89.00%, the HIGH time grows to 810.0µs at the same 1.0987kHz frequency, and the LED is almost at full brightness:
And here are the demo videos of this LAB, the PWM signal on the oscilloscope and the resulting LED dimmer:
STM32 PWM Example 2: 4-Channel PWM Output (Mode 1 vs Mode 2)
In this example, we'll use all 4 channels of Timer2 to generate 4 PWM signals at the same time, with the same frequency and different duty cycles. We'll also set channel 2 to PWM mode 2 with the same CCR value as channel 1, so you can see the difference between the 2 PWM modes on the oscilloscope. Here are the settings:
| Channel (Pin) | PWM Mode | Pulse (CCRx) | Expected Duty Cycle |
|---|---|---|---|
| CH1 (PA0) | PWM mode 1 | 250 | 250 / 1000 = 25% |
| CH2 (PA1) | PWM mode 2 | 250 | 1 - 250 / 1000 = 75% |
| CH3 (PA2) | PWM mode 1 | 500 | 50% |
| CH4 (PA3) | PWM mode 1 | 1000 | 100% (CCR > ARR) |
The timer clock is 72MHz, the Prescaler is 72-1 (1MHz timer tick), and the Counter Period (ARR) is 1000-1. So the PWM frequency of all 4 channels is 72,000,000 / (72 × 1000) = 1kHz, with 1000 duty cycle steps (about 10-bit resolution).
STM32 4-Channel PWM Wiring

Connect 4 LEDs, each with a 330Ω resistor in series, to PA0, PA1, PA2, and PA3, and the 4 cathodes to GND. The Blue Pill is powered from its micro-USB port, and the ST-Link stays on the SWD header as in Example 1. To check the signals on an oscilloscope, connect the probes to the same pins (I used 2 probes at a time: PA0 with PA1, then PA2 with PA3) and the probe ground clips to the Blue Pill GND.
PA0 TIM2 CH1: PWM mode 1, 25%
PA1 TIM2 CH2: PWM mode 2, 75%
PA2 TIM2 CH3: PWM mode 1, 50%
PA3 TIM2 CH4: PWM mode 1, 100%
GND LED cathodes (and the oscilloscope probes ground)
STM32 4-Channel PWM CubeMX Configuration
#1
Start from the same project setup as Example 1: SWD debug, HSE, and the 72MHz clock.
#2
Go to Timers > TIM2, set the Clock Source to Internal Clock, and set Channel1 to Channel4 to PWM Generation CHx.
#3
In the Parameter Settings, set the Prescaler to 72-1 and the Counter Period to 1000-1 (CubeMX accepts these expressions).
#4
Set each channel's Mode and Pulse as in the table above: PWM mode 1 / 250 for CH1, PWM mode 2 / 250 for CH2, PWM mode 1 / 500 for CH3, and PWM mode 1 / 1000 for CH4.
#5
Generate the code, then press F5 on the project in STM32CubeIDE to refresh it.
STM32 4-Channel PWM Example Code
This time, the duty cycles are set by CubeMX in MX_TIM2_Init(), so the main() function only has to start the 4 channels. The timer hardware does the rest, and the CPU is free.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
/* * LAB Name: STM32 PWM 4-Channel Output (PWM Mode 1 vs Mode 2) * Author: Khaled Magdy * For More Info Visit: www.DeepBlueMbedded.com * * TIM2: 72MHz / (71+1) / (999+1) = 1kHz on all 4 channels (same frequency, in sync) * CH1 (PA0): PWM mode 1, CCR1 = 250 -> 25% duty * CH2 (PA1): PWM mode 2, CCR2 = 250 -> 75% duty (inverted CH1) * CH3 (PA2): PWM mode 1, CCR3 = 500 -> 50% duty * CH4 (PA3): PWM mode 1, CCR4 = 1000 -> 100% duty (CCR > ARR) */ #include "main.h" TIM_HandleTypeDef htim2; void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_TIM2_Init(void); int main(void) { HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_TIM2_Init(); // Start PWM Output On All 4 Channels HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4); while (1) { // Nothing To Do Here, The Timer Hardware Generates All 4 PWM Signals } } |
Here is the CubeMX-generated MX_TIM2_Init() function with the 4 PWM channels configuration:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
static void MX_TIM2_Init(void); int main(void) { HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_TIM2_Init(); // Start PWM Output On All 4 Channels HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4); while (1) { // Nothing To Do Here, The Timer Hardware Generates All 4 PWM Signals } } |
STM32 4-Channel PWM Testing Results
Here are my oscilloscope captures of the 4 channels, 2 at a time.
CH1 (yellow) is PA0 (TIM2 CH1, PWM mode 1), and CH3 (cyan) is PA1 (TIM2 CH2, PWM mode 2). Both channels have the same CCR value of 250.
Both run at 1.000kHz and stay in sync, because they share the same TIM2 counter. PA0 in PWM mode 1 is HIGH for 25.00% of the period, and PA1 in PWM mode 2 is the exact inverse at 75.00%:
Then I moved the 2 probes: CH1 (yellow) to PA2 (TIM2 CH3) and CH3 (cyan) to PA3 (TIM2 CH4).
PA2 is a clean 50.00% duty cycle at 1.000kHz. PA3 has no edges at all: it stays HIGH, because its CCR value (1000) is greater than ARR (999), so the counter never reaches the compare value. That's the 100% duty cycle case from the formulas section (the scope shows **** for its frequency and duty cycle, because there's no period to measure on a DC level):
STM32 PWM Not Working? Troubleshooting
No PWM Output on the Pin
Check that you call HAL_TIM_PWM_Start(&htimx, TIM_CHANNEL_x) for every channel you use. CubeMX only configures the timer, it doesn't start it. Then check that the channel is set to PWM Generation CHx (not Output Compare), and that you're measuring the pin CubeMX assigned (it turns green in the Pinout view).
TIM1 PWM Doesn't Work (or Only CHxN Doesn't Work)
TIM1 is an advanced timer, and its outputs only work when the MOE (Main Output Enable) bit is set. HAL_TIM_PWM_Start() sets it for you, but if you write the registers yourself, you need to set it with __HAL_TIM_MOE_ENABLE(&htim1). The complementary outputs (CH1N, CH2N, CH3N) need HAL_TIMEx_PWMN_Start(), not HAL_TIM_PWM_Start(). Also check the Break input settings: an active break input disables the outputs.
The PWM Frequency Is Wrong (Half or Double)
Check the timer clock in the CubeMX Clock Configuration tab (APB1 Timer clocks / APB2 Timer clocks), not the APB clock itself. On the Blue Pill, APB1 is 36MHz but TIM2-TIM4 run at 72MHz. Also check that the HSE is enabled and set to the right crystal (8MHz on the Blue Pill, 25MHz on many other boards), otherwise the system runs from the 8MHz HSI and everything is 9 times slower. And don't forget the +1 in (PSC + 1) and (ARR + 1).
The ST-Link Can't Connect After Flashing the PWM Project
The project was generated with SYS > Debug set to No Debug, so the code disables the SWD pins at startup. Set it to Serial Wire and generate the code again. To flash the board again, move the Blue Pill's BOOT0 jumper to 1 and press RESET: the chip then starts the built-in bootloader instead of your code, so SWD stays enabled and the ST-Link can connect. Flash the fixed code, put BOOT0 back to 0, and press RESET. (The Blue Pill's 4-pin SWD header has no NRST pin, so the "Connect Under Reset" option only works if you hold the RESET button while connecting.) This is exactly what happened to the Blue Pill I used for this tutorial, which still had an old No Debug project on it.
The Duty Cycle Is Stuck at 0% or 100%
A CCRx value of 0 gives a constant LOW output, and any value greater than ARR gives a constant HIGH output (in PWM mode 1, reversed in mode 2). Also check that you're not writing a value larger than 65535 to a 16-bit timer: the upper bits are lost, so 65590 becomes 54.
I Can't Get PWM on PC13 (the Blue Pill LED)
PC13 isn't connected to any timer channel on the STM32F103, so it can't output hardware PWM. Use one of the 16 PWM pins in the Blue Pill PWM pins table with an external LED, or toggle PC13 in a timer interrupt for a slow software PWM.
The Motor (or LED Strip) Doesn't Respond to the PWM
The STM32 pins output 3.3v and can only source a few milliamps, so they can't drive motors, LED strips, or 12v loads directly. Use a logic-level MOSFET or a motor driver between the PWM pin and the load. For DC motors, use a PWM frequency around 20kHz to get rid of the audible whine. Check the STM32 DC Motor Speed Control tutorial for a full example.
STM32 PWM Tutorial Series
This tutorial is the first part of our STM32 PWM tutorial series:
| Part | Tutorial | What You'll Build |
|---|---|---|
| 1 | STM32 PWM Output Example (this tutorial) | PWM with HAL and CubeMX: LED dimmer, 4-channel PWM, mode 1 vs mode 2 |
| 2 | STM32 PWM Frequency & Resolution | Set the PWM frequency and resolution at run time |
| 3 | STM32 PWM Input Mode | Measure a signal's frequency and duty cycle |
| 4 | STM32 Complementary PWM & Dead-Time | TIM1 complementary outputs with dead-time |
| 5 | STM32 3-Phase PWM (Center-Aligned) | 3-phase center-aligned PWM for motor drives |
| 6 | STM32 3-Phase PWM (Edge-Aligned) | 3-phase edge-aligned PWM |
| 7 | STM32 PWM Phase Shift (Timer-Synchronized) | Phase-shifted PWM with synchronized timers |
| 8 | STM32 PWM Shutdown (Break Input) | Stop the PWM outputs safely with the break input |
STM32 PWM Wrap-Up
To conclude this tutorial, we've seen how to generate STM32 PWM output signals using the hardware timers in PWM mode: how the counter, ARR, and CCR registers create the PWM signal, the exact frequency, duty cycle, and resolution formulas, PWM mode 1 vs mode 2, edge-aligned vs center-aligned PWM, and the Blue Pill PWM pins. Then, we've built an LED dimmer on TIM2 CH1 and a 4-channel PWM output with HAL and CubeMX, and checked both on the oscilloscope.
This tutorial is a fundamental part of our STM32 Series of Tutorials because we'll use PWM in so many tutorials and projects hereafter, like servo motor control and BLDC motor control with an ESC.
If you're just getting started with STM32, you need to check out the STM32 Getting Started Tutorial here. And follow this STM32 Series of Tutorials to learn more about STM32 Microcontrollers Programming. If you've got any questions, drop me a comment below and I'll be glad to help!
Download STM32 PWM Example Projects
Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you've seen in the demo videos & screenshots. Please consider supporting my work if it helped you.
STM32 PWM FAQ
The STM32F103C8T6 on the Blue Pill has 16 PWM channels: 4 on each of TIM1, TIM2, TIM3 and TIM4. TIM1 also has 3 complementary outputs (CH1N to CH3N). Each timer has its own frequency, and its 4 channels share it with independent duty cycles.
It depends on the load: 1kHz to 5kHz for LED dimming, about 20kHz for DC motors (above the audible range), 25kHz for 4-wire PC fans, and 50Hz for hobby servos. A higher frequency always means a lower resolution, so pick the lowest frequency that works for your load.
In theory, it's the timer clock divided by 2 (36MHz at 72MHz with ARR = 1), but that leaves only 1 bit of resolution. In practice, at 8-bit resolution (ARR = 255) the Blue Pill gives 281.25kHz, and at 10-bit (ARR = 1023) about 70.3kHz.
Yes. Writing the CCR register with __HAL_TIM_SET_COMPARE() is a single register write, and with the CCR preload enabled (the CubeMX default for PWM), the new value takes effect at the start of the next PWM period. So the PWM timing stays exact, wherever you write it from.
The STM32 PWM pins switch between 0v and 3.3v. Some pins are 5v tolerant as inputs, but they still output 3.3v. To drive 5v or 12v loads, use a logic-level MOSFET or a motor driver between the PWM pin and the load.
My project isnt recognising those 3 rows
SystemClock_Config();
MX_GPIO_Init();
MX_TIM2_Init();
Where are they and how are they generated?
Those functions are generated by CubeMX and you can find the definition of each function in the main.c file
can you give wiring this experiment?
thank you
Hi I want to to learn STM32CUBEIDE code for a 3 phase bldc motor to control speed with pot cw ccw start stop can you help coding min max speed