STM32 Servo Control Demo

Servo 1 0°→90°→180°

My approach is as follows: first, consider which specific timer and which channel to use, then perform clock enabling operations for the corresponding GPIO and timer. Next, initialize the timer part to ensure a 50Hz output period, as we are outputting PWM with high and low levels. Therefore, the pin must be set to alternate push-pull output. After all initializations are complete, we need to configure the PWM output mode using the function ocinit, which is the output compare function. Select PWM1 mode, which is in mode 1, where the counter is less than our ccr to output a high level. Note that the main channel configuration is essential; the channel does not need to be configured, just remember to set the initial ccr to 0. Subsequently, the value of ccr can be configured using the TIM_SetCompare1 function. Finally, after configuring the PWM, remember to enable the corresponding channel. For advanced timers, you must add TIM_CtrlPWMOutputs(TIM8,ENABLE).

The problem I encountered in the middle was that I was not familiar with the process at first and forgot to enable the corresponding PWM channel preload function, which eliminates the PWM wave’s glitch phenomenon. Also, I initially did not know to use TIM_CtrlPWMOutputs(TIM8,ENABLE). The third issue was that when configuring the PWM, due to the master-slave channel setup, I initially configured the values incorrectly, especially easy to copy wrong, so be careful.

The following image shows part of the source code. Of course, we can also use a general-purpose timer to achieve this.

STM32 Servo Control Demo

The above image shows the implementation using an advanced timer, while the image below shows the implementation using a general-purpose timer; the effect is the same.

STM32 Servo Control Demo

For simple servo control, either option works. However, for motors that require safety considerations, it is recommended to use an advanced timer, which can provide hardware braking and stop PWM output for protection. Additionally, it has a repeat counting function, which triggers an update event after accumulating several overflows, making it faster and more convenient than blocking delays.

Leave a Comment