Skip to content
systemcoding.dev
Embedded

Centre-align STM32 PWM with the TIM CMS bits

Centre-align STM32 PWM with the CMS bits in TIMx_CR1, which counts up and down and halves the PWM frequency for the same reload value.

2 min read
Summarize in AI

In edge-aligned mode, the counter counts up and the output goes high at the start of every period. In centre-aligned mode, it counts up and then down, so the pulse is symmetrical around the middle of the period. That is what a motor driver or a class-D stage wants, because the switching edges spread out and the average current ripple is smaller.

c
// STM32F4 timer 1, stopped, with PSC and ARR already set
TIM1->CR1 = (TIM1->CR1 & ~TIM_CR1_CMS) | TIM_CR1_CMS_0;   // centre-aligned mode 1
TIM1->CCR1 = TIM1->ARR / 4;
TIM1->CCMR1 |= (6U << TIM_CCMR1_OC1M_Pos);                // PWM mode 1
TIM1->CCER  |= TIM_CCER_CC1E;
TIM1->BDTR  |= TIM_BDTR_MOE;
TIM1->CR1   |= TIM_CR1_CEN;

CMS has three settings: 01, 10 and 11 differ only in when the compare interrupt flag is set (counting down, up or both). The PWM waveform is the same for all three, so mode 1 is usually enough.

Two things catch people. The reference manual forbids switching from edge-aligned to centre-aligned while the counter is running, so configure CMS with CEN clear, as above. And the period doubles: the counter travels up to ARR and back, so the frequency is f_timer / (2 × ARR × (PSC + 1)), half of the edge-aligned value for the same registers.

With the HAL, set htim.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED1 before HAL_TIM_PWM_Init. The register description is in RM0090.

Taggedcstm32
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.