STM32F4 PWM tutorial with TIMERs

In this tutorial, I will show you, how to implement PWM outputs on STM32F4xx devices. This is for a lot of people pretty hard work, but believe me, it’s quite quick and easy. I will go step by step on how to make a PWM output on specific timer.

Update: I made a library for PWM, available here.



STM32F4 timers

They have up to 14 timers inside. Table below shows their description. You have to know, that let’s say F401 doesn’t have so many timers like F407 or F429. You have to always check manual for it’s chip if it has available timer.

Timer Type Resolution Prescaler Channels MAX INTERFACE CLOCK MAX TIMER CLOCK* APB
TIM1, TIM8 Advanced 16bit 16bit 4 SysClk/2 SysClk 2
TIM2, TIM5 General purpose 32bit 16bit 4 SysClk/4 SysClk, SysClk/2 1
TIM3, TIM4 General purpose 16bit 16bit 4 SysClk/4 SysClk, SysClk/2 1
TIM9 General purpose 16bit 16bit 2 SysClk/2 SysClk 2
TIM10, TIM11 General purpose 16bit 16bit 1 SysClk/2 SysClk 2
TIM12 General purpose 16bit 16bit 2 SysClk/4 SysClk, SysClk/2 1
TIM13, TIM14 General purpose 16bit 16bit 1 SysClk/4 SysClk, SysClk/2 1
TIM6, TIM7 Basic 16bit 16bit 0 SysClk/4 SysClk, SysClk/2 1

* Clock speed depends on which STM32F4xx device is used

Timer initialization

Before we can use PWM, we have to initialize timer. Because STM32F429 Discovery board does not have leds on PWM pins, I will use STM32F4 Discovery with 168MHz core clock for this example. Leds are connected to pins PD12 to PD15, what give us timer TIM4 with Output channels 1 to 4.

Initialize TIM4

Here we will initialize timer, for our PWM frequency. We have to set prescaler and period for how fast will it count and how much it will count for specific PWM frequency.

Initialize PWM 4 channels

Set PWM output channels to PWM.

Initialize outputs

Initialize and connect pins for specific TIM. Notice, that GPIOs have AF (Alternating Function) mode, because timer has full control on them.

Example

That’s it. You have not set your timer to work in PWM mode.

Hope it helps.

tilz0R

Owner of this site. Application engineer, currently employed by STMicroelectronics. Exploring latest technologies and owner of different libraries posted on Github.

You may also like...