Fareed Mohmed← Project library

Engineering · Raspberry Pi · Project 8 of 47 · Motion · Beginner

Servo motor sweep

A hobby servo turns to an angle you choose. Step it through left, centre and right like a radar or a robot arm joint.

▶ Open in the simulator

Raspberry Pi simulator drawing of the circuit for Servo motor sweep: the board, its power supply and the parts wired to the 40-pin header

Parts in this circuit

PartType
Micro servoServo

Wiring, pin by pin

Red = 5 V, orange = 3.3 V, black = GND, other colours = signals. “Pin” is the position on the 40-pin header; the GPIO number is what the code uses. Power the Pi from a 5.1 V supply and wire with the power off.

#ColourFrom (part and leg)To (header pin)
1ColouredMicro servo - signalPin 11 (GPIO17)
2RedMicro servo - 5 VPin 2 (5V)
3BlackMicro servo - GNDPin 6 (GND)

Python code (gpiozero)

from gpiozero import AngularServo
from time import sleep

servo = AngularServo(17, min_angle=-90, max_angle=90)

while True:
    for angle in (-90, -45, 0, 45, 90, 45, 0, -45):
        servo.angle = angle
        print("Angle:", angle)
        sleep(0.8)

How the code works

You will learn

  • Servo control by pulse width
  • Looping over a list of values
  • Angles in a range

Try this

  • Sweep smoothly: step one degree at a time with a short sleep.
  • Return to 0 degrees at the end with servo.angle = 0.
  • Add a button that sends the servo to 0.

On a real Pi

  • Power the servo from a separate 5 V supply and join the grounds. A stalled servo can reset the Pi.
  • Jitter is common with software PWM. A pigpio or hardware PWM setup is steadier.

Parts to buy

The links open a search on each store, so you see what is in stock today. Check the model, voltage and price before you order.

#ItemQtyBuy / compare
1Raspberry Pi 4 Model B
about 4000 to 9000 INR
1Robu.in Amazon.in ThinkRobotics
2Official 15 W USB-C power supply (5.1 V, 3 A)
Do not use an old phone charger
1Robu.in Amazon.in ThinkRobotics
3microSD card 32 GB, class 10 / A1 (with Raspberry Pi OS)
And a card reader to write it
1Robu.in Amazon.in ThinkRobotics
4SG90 micro servo1Robu.in Amazon.in ThinkRobotics
5Dupont jumper wires, male-to-female, 20 cm (pack of 40)1Robu.in Amazon.in ThinkRobotics
6Breadboard 830 points
For resistors and shared GND / 5 V
1Robu.in Amazon.in ThinkRobotics
← 7. Dimmer and breathing LED (PWM)All projects9. DC motor with an H-bridge →

This is a learning tool. The simulator checks the program logic, not the electrical design. Never put more than 3.3 V on a GPIO pin.