In this project, we will learn how to control servo motors using an STM32F103C6 microcontroller by utilizing Pulse Width Modulation (PWM) to achieve precise positioning. Servo motors are crucial components in robotics and automation due to their accurate control over angular movement. They are widely used in applications ranging from hobby projects to complex industrial systems. Through this project, you’ll understand how to configure PWM on the STM32 to control a servo motor’s position efficiently.
What is a Servo Motor?
Servo motors are designed for precise control of position, speed, and acceleration. Unlike standard DC motors, which rotate continuously, servo motors respond to PWM control signals to move to a specific angle and hold that position. This is achieved through a feedback mechanism that ensures the motor maintains the correct position based on the input signal.
How Servo Motors Work
- Servo motors function through a closed-loop control system, utilizing feedback to adjust their movement.
- Control Signal: The STM32 sends a PWM signal to the servo. The pulse duration determines the target position.
- Position Sensing: A potentiometer inside the servo continuously monitors the shaft position.
- Error Correction: The control circuit compares the actual position (feedback) with the target position (input signal).
- Feedback Loop: The motor adjusts until it reaches the desired position.
PWM and Servo Motor Control
PWM (Pulse Width Modulation) is a method used to create analog-like control from digital signals by adjusting the duration of pulses. For servo motors, PWM is essential since the pulse width determines the shaft angle.
- Typical PWM period for hobby servos: 20 ms (50 Hz).
- Pulse Width → Servo Position:
-1 ms pulse → ~0° (minimum position)
-1.5 ms pulse → ~90° (neutral position)
-2 ms pulse → ~180° (maximum position)
By varying the pulse width between 1–2 ms, smooth and accurate angular control is achieved.
STM32CubeMX Setup- MCU Selection: STM32F103C6 (72 MHz clock)
- TIM2 Configuration:
-Channel 1 (PA0): PWM Generation
-Prescaler: 15
-Counter Period: 19999
- GPIO Configuration:
-
PB0.. PB1 →
Input Pull_down
- Generate initialization code in STM32CubeIDE.
- Servo Initialization
-Servo_Init()
→ Starts PWM signal for the servo.
- Set Servo Angle
-Servo_SetAngle(angle)
→ Moves the servo to the desired angle (0°–180°).
- Button Control
Components:
- STM32F103C6
- Servo Motor
- Virtual Terminal (UART optional)
Connections:
- PA8 → Servo Signal Input
- 5V / GND → Servo Power
Steps:
- Load the.hex file generated from CubeIDE.
- Run simulation in Proteus.
- Observe servo movement sequence: 0° → 90° → 180°.
If you have any questions or suggestions don't hesitate to leave a comment below
Comments