YAWAR

#2 Generating PWM with STM32

Microcontrollers handle tasks from sensor sampling to motor control. PWM generation is one example where the timer configuration matters as much as the application code.

For projects needing more timer channels, interfaces, or processing headroom, a 32-bit STM32 can be a useful choice. This example uses the STM32F103x8 family, which has a 72 MHz Cortex-M3 core, timers, and 12-bit ADCs; peripheral availability varies by STM32 model. See the STM32F103x8 data sheet for device limits.

View the related STM32CubeMX/HAL PWM project on GitHub

The Development Ecosystem

For an STM32F103x8 PWM project, a typical toolchain includes:

  • Software: STM32CubeMX can configure clocks and pins and generate initialization code. Keil uVision is one option for building and debugging C/C++ firmware.
  • Hardware: An ST-Link v2 can flash the device and support Serial-Wire Debugging (SWD).
  • Libraries: ST’s Hardware Abstraction Layer (HAL) can simplify setup. The timer reference manual is useful when checking update timing or debugging a configuration.

The Physical Layer of PWM

For edge-aligned PWM, the timer counts to an Auto-Reload Register (ARR) value, while a Capture/Compare Register (CCR) sets the compare point. The linked project uses STM32CubeMX and HAL; the following separate register-level illustration assumes TIM2 has a 72 MHz timer input clock and that the peripheral clock and output pin are already configured.

// Example Bare-Metal Timer Configuration
TIM2->PSC = 71;        // 72 MHz timer clock / 72 = 1 MHz tick
TIM2->ARR = 999;       // Auto-reload value (Period = 1ms -> 1kHz frequency)
TIM2->CCR1 = 500;      // Duty cycle = 50% in PWM mode 1
TIM2->CCMR1 |= TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2; // PWM Mode 1
TIM2->CCER |= TIM_CCER_CC1E; // Enable Output
TIM2->CR1 |= TIM_CR1_CEN;    // Start Timer

Why It Matters in Power Electronics

Timer clock, prescaler, and register update behavior set the available PWM resolution and timing. In a power converter, also check when preload values take effect and configure dead time and protection where the switching topology requires them.