Introduction

In this course we’ll look at how to control a servomotor with the Raspberry Pi.
A servomotor is a very precise motor where you can control its direction and angle to the nearest degree. It can be used if you have a project requiring very precise motor positions. Some servomotors can make turns of up to 180 degrees. If you need a precise motor turning 360 degrees, we recommend a stepper motor.
Here’s the diagram for connecting the servomotor to the Raspberry Pi:

Programming

Here’s the program to operate the servomotor. It uses PWM to vary the motor position:

import RPi.GPIO as GPIO
import time

# Pin configuration
servo_pin = 17

# Initial GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setup(servo_pin, GPIO.OUT)

# Set PWM signal frequency (50 Hz is generally used for servomotors)
pwm_frequency = 50
pwm = GPIO.PWM(servo_pin, pwm_frequency)

# Function to set servomotor angle
def set_servo_angle(angle):
    duty_cycle = (angle / 18) + 2
    GPIO.output(servo_pin, True)
    pwm.ChangeDutyCycle(duty_cycle)
    time.sleep(1) # Wait 1 second for servomotor to reach position
    GPIO.output(servo_pin, False)
    pwm.ChangeDutyCycle(0)

try:
    # Start PWM with an initial angle of 90 degrees
    pwm.start(7.5)

    # Rotate servomotor from 0 to 180 degrees in 30-degree steps
    for angle in range(0, 180, 30):
        set_servo_angle(angle)
        time.sleep(1)

    # Return to initial position (90 degrees)
    set_servo_angle(90)

except KeyboardInterrupt:
    pass

finally:
    # Clean GPIO resources
    pwm.stop()
    GPIO.cleanup()