
STM32 PWM Principle and Application
Global electronic component supplier AMPHEO PTY LTD: Rich inventory for one-stop shopping. Inquire easily, and receive fast, customized solutions and quotes.
PWM (Pulse Width Modulation) is a fundamental technique used in STM32 and other microcontrollers for controlling analog-like behavior using digital signals. It is widely used in applications such as motor control, LED brightness, audio signal generation, and more.
🔧 STM32 PWM Principle
✅ What is PWM?
PWM is a digital signal with a fixed frequency but variable duty cycle.
-
Frequency: How often the signal repeats (e.g. 1 kHz = 1000 times per second)
-
Duty Cycle: The percentage of time the signal is HIGH in one period.
Example:
-
0% Duty Cycle → Always LOW
-
50% Duty Cycle → Half HIGH, half LOW
-
100% Duty Cycle → Always HIGH
✅ How STM32 Generates PWM
STM32 uses Timers in PWM mode to generate signals:
-
Timer counts up to a value (ARR - Auto Reload Register).
-
When counter reaches a compare value (CCR - Capture Compare Register), the output pin toggles.
-
The compare value defines the duty cycle.
📐 PWM Formula
For a timer in up-counting mode:
-
PWM Frequency =
Timer Clock / ((PSC + 1) * (ARR + 1))
-
Duty Cycle (%) =
(CCR / ARR) * 100
Where:
-
PSC
= Prescaler -
ARR
= Auto Reload Register -
CCR
= Capture Compare Register
🛠️ Application Example: LED Brightness Control
🧱 Hardware
-
STM32F4 board
-
LED connected to a PWM-capable pin (e.g., TIM3_CH1)
⚙️ Setup in STM32CubeMX
-
Select Timer (e.g., TIM3)
-
Enable a PWM Channel (e.g., CH1) on a pin (e.g., PB4)
-
Set the timer prescaler and period (ARR) to define frequency.
-
Enable GPIO as alternate function.
-
In the generated code, use
__HAL_TIM_SET_COMPARE()
to control duty cycle.
📄 Example Code
🎯 Common Applications
Application | Description |
---|---|
LED Dimming | Change brightness by varying duty cycle |
Motor Control | Control speed or direction (via H-bridge) |
Servo Control | Generate 1–2 ms pulse at 50 Hz for position |
Audio | Generate tones by varying frequency |
Power Supplies | Use PWM in SMPS for voltage regulation |
📚 Conclusion
PWM in STM32 is implemented using timers, offering high precision and flexibility. It's simple to configure with CubeMX and powerful enough for real-time control tasks like dimming, speed regulation, and signal generation.
Related Articles
- ·How to use STM32 as a logic analyzer?
- ·How to Create a PCB for STM32?
- ·The difference between HEX and BIN files in microcontrollers
- ·How to Make a STM32 CNC 4 Axis?
- ·UART Serial Communication Experiment Based on Raspberry Pi 4B and STM32
- ·How to choose STM32 clock?
- ·Which is better for beginners: ESP32 or STM32? A robot example
- ·The Application of Embedded Electronics in the Field of Consumer Electronics
- ·Comparison of FPGA, ARM, STM32, and DSP Platforms