How to use PWM on the STM32F407 microcontroller?
Here's a complete guide to using PWM on the STM32F407 microcontroller using TIM4 and GPIO pin PD12 (which maps to TIM4_CH1) — commonly used on STM32F4 Discovery boards.
Goal
Generate PWM signal on PD12 (TIM4 Channel 1) using STM32F407 and HAL drivers via STM32CubeMX + STM32CubeIDE.
Required Tools
-
STM32F407 MCU or Discovery board
-
STM32CubeMX
-
STM32CubeIDE
-
USB cable, LED, or oscilloscope (to observe PWM)
Step-by-Step Instructions
1. STM32CubeMX Configuration
a. Select Device
-
Open CubeMX and choose
STM32F407VGTx
(or your variant).
b. Configure Pin
-
Click on pin PD12, set as
TIM4_CH1
→ PWM Generation CH1.
c. Configure Timer 4
-
Go to Timers → TIM4 → Mode → PWM Generation Channel 1.
-
Set:
-
Prescaler: 83 → 84 MHz / (83+1) = 1 MHz timer frequency
-
Counter Period (ARR): 999 → PWM frequency = 1 MHz / 1000 = 1 kHz
-
Pulse: 500 → 50% duty cycle
-
d. Clock Configuration
-
Ensure the system clock is at 84 MHz (from HSE or HSI with PLL).
e. Project Settings
-
Name the project (e.g.,
PWM_TIM4
), set the toolchain to STM32CubeIDE. -
Click Generate Code.
2. STM32CubeIDE Code (main.c)
Add this to your main.c
inside int main(void)
after HAL initialization:
To change duty cycle dynamically:
Example PWM Frequency & Duty Cycle Calculation
Prescaler | Period (ARR) | Timer Freq | PWM Freq |
---|---|---|---|
83 | 999 | 1 MHz | 1 kHz |
83 | 99 | 1 MHz | 10 kHz |
(CCR1 / ARR) * 100
Debugging & Testing
-
Connect an LED with resistor to PD12 or measure with an oscilloscope.
-
You should see PWM square wave output.
-
Try varying
CCR1
in a loop to change brightness:
Optional: Use Other Channels or Pins
Timer | Channel | Pin |
---|---|---|
TIM4 | CH2 | PD13 |
TIM4 | CH3 | PD14 |
TIM4 | CH4 | PD15 |
TIM3 | CH1 | PA6 |
TIM2 | CH1 | PA0 |
评论
发表评论