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_CH1PWM 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:

c

HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1); // Start PWM on TIM4_CH1 // Set duty cycle to 50% __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, 500);

To change duty cycle dynamically:

c

uint16_t duty = 750; // 75% of 1000 __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, duty);

 Example PWM Frequency & Duty Cycle Calculation

PrescalerPeriod (ARR)Timer FreqPWM Freq
839991 MHz1 kHz
83991 MHz10 kHz

Duty cycle (%) = (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:

c

for (int i = 0; i < 1000; i++) { __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, i); HAL_Delay(1); }

 Optional: Use Other Channels or Pins

TimerChannelPin
TIM4CH2PD13
TIM4CH3PD14
TIM4CH4PD15
TIM3CH1PA6
TIM2CH1PA0

评论

此博客中的热门博文

How To Connect Stm32 To PC?

What are the common HDL languages used in FPGA design?

How do you set up ADC (Analog-to-Digital Converter) in STM32?