Raspberry Pi - Servo Motor

This tutorial instructs you how to use Raspberry Pi to control servo motor. In detail, we will learn:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Servo Motor
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Overview of Servo Motor

A servo motor is a component capable of rotating its shaft within a specific range of motion, typically between 0 and 180 degrees. It is commonly used to control the angular position of an object.

The Servo Motor Pinout

The servo motor has three pins:

  • VCC pin (usually red) which needs to be connected to VCC (5V)
  • GND pin (typically black or brown) which needs to be connected to GND (0V)
  • Signal pin (normally yellow or orange) which receives the PWM control signal from a Raspberry Pi's pin.
servo motor pinout

Raspberry Pi - Servo Motor

Some of the pins on a Raspberry Pi can be programmed to produce a PWM signal. We can control a servo motor by connecting its signal pin to one of the Raspberry Pi's pins and programming it to generate a PWM on that pin.

Thanks to the Raspberry Pi Servo library, controlling a servo motor is made easy. We don't need to understand the workings of the servo motor or how to generate a PWM signal. All we need to do is learn how to use the library.

Wiring Diagram

The wiring diagram between Raspberry Pi and Servo Motor

This image is created using Fritzing. Click to enlarge image

For the purpose of keeping things simple, the wiring diagram above is used for testing and learning, and is suitable for a servo motor with low torque. We strongly suggest that an external power supply be used for the servo motor. The wiring diagram below shows how to connect the servo motor to an external power source.

The wiring diagram between Raspberry Pi and servo motor external power supply

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file servo_motor.py and add the following code:
# This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-servo-motor import RPi.GPIO as GPIO import time # Set the GPIO mode (BCM or BOARD) GPIO.setmode(GPIO.BCM) # Define the GPIO pin connected to the servo motor SERVO_PIN = 18 # Set the servo pin as an output pin GPIO.setup(SERVO_PIN, GPIO.OUT) # Set up PWM pwm_frequency = 50 # Set PWM frequency to 50Hz (standard for most servos) pwm = GPIO.PWM(SERVO_PIN, pwm_frequency) pwm.start(0) def set_servo_angle(angle): duty_cycle = (angle / 18) + 2.5 pwm.ChangeDutyCycle(duty_cycle) time.sleep(0.3) # Give the servo time to reach the desired angle try: while True: # Rotate the servo from 0 to 180 degrees for angle in range(0, 181, 10): set_servo_angle(angle) # Rotate the servo back from 180 to 0 degrees for angle in range(180, -1, -10): set_servo_angle(angle) except KeyboardInterrupt: # If the user presses Ctrl+C, clean up the GPIO configuration pwm.stop() GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 servo_motor.py

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

  • Check out the outcome: The servo motor rotates at a slow speed in both the clockwise and counter-clockwise directions, up to 180°.

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

How to Control Speed of Servo Motor

# This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-servo-motor import RPi.GPIO as GPIO import time # Set the GPIO mode (BCM or BOARD) GPIO.setmode(GPIO.BCM) # Define the GPIO pin connected to the servo motor SERVO_PIN = 18 # Set the servo pin as an output pin GPIO.setup(SERVO_PIN, GPIO.OUT) # Set up PWM pwm_frequency = 50 # Set PWM frequency to 50Hz (standard for most servos) pwm = GPIO.PWM(SERVO_PIN, pwm_frequency) pwm.start(0) MOVING_TIME = 3000 # moving time is 3 seconds angle_start = 30 # 30° angle_stop= 90 # 90° move_start_ms = int(round(time.time() * 1000)) # start moving in milliseconds try: while True: # Get the elapsed time since the movement started progress = int(round(time.time() * 1000)) - move_start_ms if progress <= MOVING_TIME: # Calculate the current angle based on the progress angle = angle_start + (angle_stop- angle_start) * progress / MOVING_TIME pwm.ChangeDutyCycle(2.5 + (angle / 18)) # Convert angle to duty cycle time.sleep(0.05) # Adjust this delay to control the speed/smoothness of movement except KeyboardInterrupt: # If the user presses Ctrl+C, clean up the GPIO configuration pwm.stop() GPIO.cleanup()

Video Tutorial