STM32 PWM - EPFL-MICRO-315/TPs-Wiki GitHub Wiki
⚠ wiki page used in TP2
PWM Introduction
- A PWM signal can be used to for instance
- drive a servo motor
- modulate a LED intensity
- ...
- To configure a PWM, one must :
- configure a Timer with an Output Compare channel
- connect the desire output GPIO to this channel
Figure 1
PWM signal generated using a Timer and Output Compare in PWM mode 2. https://visualgdb.com/tutorials/arm/stm32/pwm/
Note : The figure shows a PWM mode 2. PWM mode 1 does the same except the output signal is inverted
1 - Configuration of the GPIO
- Only specific GPIO can be driven in output using a PWM signal
- The table 7 STM32F40xxx pin and ball definitions in the datasheet of STM32F40xxx shows all the possible alternate functions for each pin of the microcontroller
- In this example, we will select the Pin 14 of the Port D: PD14 that is connected to the channel 3 of the timer 4: TIM4_CH3 as shown in the table 7 STM32F40xxx pin and ball definitions
- This GPIO is connected to the Front Led of the e-puck2 → it is perfect to test the effect of a PWM signal on the intensity of a LED!
Figure 2
STM32F40xxx pin and ball definitions, from the datasheet
- 💡 In the Lab 1, the PD14 GPIO used to drive the LED was set to output, as we just wanted to drive the LED with two states (high and low)
- 💡 Here, we will have to use the pin in its Alternate Function (AF) mode (see alternate function configuration)
Figure 3
Configuration of the GPIO in alternate function mode, see Sec. 8 of the Reference Manual
2 - Timer configuration
- Timer must be configured to obtain the desired PWM
- In this example, Timer4 and Channel 3 will be configured
- ⚠ to generate a PWM signal, there is no need for timer interrupt: see the code block below.
- Prescaler and Counter maximum of Timer 4 must be correctly set to get the right frequency
Code block 1
Timer 4 configuration
// enable TIM4 clock RCC->APB1ENR |= RCC_APB1ENR_TIM4EN; // configure TIM4 TIM4->PSC = PRESCALER_TIM4 - 1; // Note: final timer clock = timer clock / (prescaler + 1) TIM4->ARR = COUNTER_MAX_TIM4 - 1; // Note: timer reload takes 1 cycle, thus -1 // enable TIM4 TIM4->CR1 |= TIM_CR1_CEN; - Final step: configure the channel for Output Compare
- In this example, Channel 3 of Timer4 will be configuredd
- The schema-bloc of the Output Compare architecture can be seen in figure 4 or in the reference Manual
Figure 4
Output stage of capture/compare channel (channel 1), with the registers involved. The same scheme can be applied to channel 3, see Chap. 8 of the Reference Manual
- The registers of TIMER4 to be modified have been highlighted