How to Control Servo Motors Using Raspberry Pi and the pigpio Library for Precision Robotics
Micro servo motors are the unsung heroes of modern robotics. From robotic arms that pick up delicate objects to pan-tilt camera mounts that track moving targets, these tiny, torque-packed devices turn electrical signals into precise mechanical motion. If you have ever tried to drive a micro servo from a Raspberry Pi using a naive software PWM loop, you already know the pain: jittery movement, random twitching, and a servo that buzzes angrily at you when the CPU gets busy.
This guide walks you through doing it properly with the pigpio library, which offloads pulse generation to the Raspberry Pi's hardware and gives you microsecond-level control over your servo's position. We will cover wiring, the theory behind servo signals, practical Python code, multi-servo coordination, and the tuning tricks that separate a wobbly hobby project from a genuinely precise robotic system.
Why Micro Servo Motors Deserve Your Attention
Before diving into code, it is worth understanding why micro servos (typically the SG90, MG90S, or similar 9-gram class motors) have become the default actuator for small robotics projects.
The Three Wires That Do Everything
A micro servo has exactly three connections: power (usually 4.8V–6V), ground, and a signal line. Inside the plastic housing you get a DC motor, a gear train, a potentiometer for position feedback, and a small control board. You send it a PWM pulse, and the internal feedback loop handles the rest. No encoder wiring, no motor driver H-bridge, no PID tuning on your end. For a roboticist building a prototype, that is an enormous simplification.
The Trade-offs You Should Know About
Micro servos are not magic. They draw significant current spikes (a stalled SG90 can pull over 700mA), they have limited torque (around 1.8 kg·cm for an SG90 at 4.8V), and their plastic gears wear out. But their size-to-torque ratio and sub-20-millisecond response time make them ideal for grippers, animatronics, camera gimbals, and small walking robots. The key to unlocking their precision is a stable, accurate pulse train — which is exactly where pigpio shines.
Understanding the Servo Control Signal
A standard hobby servo expects a pulse every 20 milliseconds (50 Hz). The pulse width encodes the angle:
- ~500 µs → one extreme (often 0°)
- ~1500 µs → center (90°)
- ~2500 µs → the other extreme (180°)
The critical insight: the servo does not care about the exact frame rate as much as it cares about pulse width consistency. A jitter of even 10 µs translates to visible twitching. Software PWM in Python (RPi.GPIO) is notoriously bad at this because the Linux scheduler can preempt your timing loop at any moment. pigpio solves this by generating pulses in a dedicated daemon with DMA-backed timing, achieving accuracy in the low microseconds even under load.
Why 50 Hz Is Not a Law
Many digital micro servos accept 100–333 Hz update rates, which makes motion smoother and reduces latency. Check your servo's datasheet. If it supports higher rates, pigpio lets you change the PWM frequency easily — just remember that higher frame rates usually narrow the acceptable pulse range slightly.
Wiring Your Micro Servo to the Raspberry Pi
Keep these rules in mind before you plug anything in:
- Never power a servo from the Pi's 5V pin if you are driving more than one, or any servo under load. The voltage sag will reset your Pi. Use a separate 5V supply (a UBEC or a 4xAA battery pack works well) and tie the grounds together.
- Signal wire goes to a GPIO pin — GPIO 18 (physical pin 12) is a safe default because it supports hardware PWM, though pigpio can use any GPIO.
- Add a 100–470 µF electrolytic capacitor across the servo's power and ground leads near the servo. This absorbs current spikes and dramatically reduces twitching.
- Use a common ground between the Pi and the external servo supply. Forgetting this is the number one cause of "my servo does nothing" forum posts.
A typical bench setup: external 5V 2A supply → servo power; supply ground → servo ground AND Pi ground; GPIO 18 → servo signal.
Installing and Configuring pigpio
On Raspberry Pi OS, install the daemon and the Python bindings:
bash sudo apt update sudo apt install pigpio python3-pigpio sudo systemctl enable pigpiod sudo systemctl start pigpiod
The pigpiod daemon must be running for your scripts to work. If you prefer running your script with sudo and the daemon disabled, pigpio can also run locally, but the daemon approach is cleaner and lets non-root users control GPIOs.
Verify it is alive:
bash pigs t
This should list the GPIO states. If you get a connection error, the daemon is not running.
Your First Precision Servo Script
Here is a minimal but production-quality example using the pigpio Python module:
python import pigpio import time
SERVOPIN = 18 MINPW = 500 # microseconds at 0 degrees MAX_PW = 2500 # microseconds at 180 degrees FREQ = 50 # Hz
pi = pigpio.pi() if not pi.connected: raise RuntimeError("pigpiod is not running")
pi.setmode(SERVOPIN, pigpio.OUTPUT)
def angletopulse(angle): angle = max(0, min(180, angle)) return int(MINPW + (MAXPW - MIN_PW) * angle / 180.0)
def moveto(angle, settle=0.3): pw = angletopulse(angle) pi.setservopulsewidth(SERVOPIN, pw) time.sleep(settle)
try: for a in range(0, 181, 10): moveto(a, 0.15) for a in range(180, -1, -10): moveto(a, 0.15) finally: pi.setservopulsewidth(SERVO_PIN, 0) # stop pulses pi.stop()
The set_servo_pulsewidth call is the heart of it. pigpio handles the 50 Hz timing in its daemon, so your Python process can do other work — or sleep — without affecting pulse accuracy. Setting the pulse width to 0 disables pulses entirely, which lets the servo go limp and saves power; this is also the correct way to stop a servo from buzzing at a holding position.
Calibrating Your Specific Servo
Cheap micro servos vary wildly. An SG90 might reach its mechanical limit at 480 µs on one end and 2520 µs on the other. Pushing beyond the limit makes the servo grind against its internal stop, draw stall current, and overheat. Calibrate like this:
- Start at 1500 µs and confirm the servo centers.
- Slowly decrease the pulse width in 10 µs steps until the horn stops moving — that is your true minimum. Back off 50 µs.
- Repeat upward for the maximum.
- Update
MIN_PWandMAX_PWin your code.
This five-minute calibration is the difference between a servo that lasts years and one that dies in a week.
Driving Multiple Micro Servos Smoothly
Robotic arms and hexapods need coordinated motion. pigpio handles this elegantly because each servo's pulse train runs independently in the daemon — you just set pulse widths, and they all hold. A simple coordinated sweep for a two-axis pan-tilt mount:
python import pigpio, time, math
pi = pigpio.pi() PAN, TILT = 18, 19 for p in (PAN, TILT): pi.set_mode(p, pigpio.OUTPUT)
def pw(angle): return int(500 + 2000 * max(0, min(180, angle)) / 180)
try: for t in range(0, 360, 2): panangle = 90 + 60 * math.sin(math.radians(t)) tiltangle = 90 + 30 * math.sin(math.radians(t * 2)) pi.setservopulsewidth(PAN, pw(panangle)) pi.setservopulsewidth(TILT, pw(tiltangle)) time.sleep(0.02) finally: pi.setservopulsewidth(PAN, 0) pi.setservopulsewidth(TILT, 0) pi.stop()
Notice there is no per-servo blocking wait. Both pulse trains update within microseconds of each other, producing genuinely synchronized motion. For smoother trajectories, interpolate angles with easing functions rather than linear steps — micro servos respond well to S-curve profiles because abrupt commanded jumps cause overshoot and gear slop.
Power Budgeting for Multi-Servo Builds
Each micro servo can spike to 700 mA under load. Four servos moving simultaneously can demand nearly 3A. Size your supply at 1A per servo plus headroom, use thick short power wires, and consider adding a per-servo decoupling capacitor. If your Pi reboots when the arm moves, it is a power problem, not a code problem.
Advanced Techniques for Real Precision
Once the basics work, these refinements push your system from "moves" to "moves precisely."
Dead Band Compensation
Micro servos have a dead band of roughly 5–10 µs where small pulse changes produce no motion. If you command tiny increments, the servo may sit still, then jump. For fine positioning, command changes larger than the dead band, or accept that sub-degree positioning is beyond analog micro servos — consider digital servos with tighter dead bands for that.
Speed Control via Pulse Ramping
Servos move at their own speed; you cannot command velocity directly. But you can ramp the pulse width over time to approximate a speed limit:
python def ramp(pi, pin, start_angle, end_angle, duration, steps=50): dt = duration / steps for i in range(steps + 1): a = start_angle + (end_angle - start_angle) * i / steps pi.set_servo_pulsewidth(pin, pw(a)) time.sleep(dt)
This protects plastic gears from shock loads and makes robotic motion look deliberate rather than jerky.
Feedback and Closed-Loop Upgrades
Open-loop micro servos assume the horn reaches the commanded angle. Under load, it may not. If your application needs verified position, add an external sensor — a magnetic encoder on the output shaft or a potentiometer coupled to the joint — and close the loop in software. pigpio's callback functions let you read GPIOs with microsecond timestamps, which is enough for simple encoder counting.
Troubleshooting Common Failure Modes
- Servo twitches constantly: power supply sag or missing capacitor. Fix power first.
- Servo moves to one end and buzzes: pulse width out of range or signal wire on the wrong pin.
- Erratic behavior when Wi-Fi is active: pigpio's DMA timing is robust, but extreme system load can still interfere. Raise the daemon's priority or reduce competing processes.
- Servo jitters only when the Pi is headless via SSH: this is usually a grounding issue between supplies, not a software problem.
pigpio.error: 'can not open pipe to pigpiod': the daemon is not running or you are in a container without device access.
Putting It All Together
The combination of Raspberry Pi and pigpio gives micro servo motors something they rarely get in hobby projects: a stable, precise, multi-channel pulse source that does not care what your Python script is doing. Calibrate each servo's pulse range, power them from a supply that can survive current spikes, ramp your pulse widths for smooth motion, and disable pulses when holding is not needed. Do those four things and your micro servo robot will move with a consistency that surprises anyone who has only used software PWM. The little 9-gram motors are capable of far more precision than most people give them credit for — you just have to feed them a clean signal.
Copyright Statement:
Author: Micro Servo Motor
Source: Micro Servo Motor
The copyright of this article belongs to the author. Reproduction is not allowed without permission.
Recommended Blog
- How to Connect a Servo Motor to Raspberry Pi Without a Breadboard
- Using Raspberry Pi to Control Servo Motors in Automated Inspection Systems
- Building a Servo-Driven Automated Plant Watering System with Raspberry Pi
- How to Power Servo Motors with Raspberry Pi Safely
- Creating a Servo-Controlled Automated Sorting Conveyor with Raspberry Pi
- Using Raspberry Pi to Control Servo Motors in Automated Inspection and Sorting Systems
- How to Control Servo Motors Using Raspberry Pi and the pigpio Library for High Precision
- Implementing Servo Motors in Raspberry Pi-Based Automated Sorting and Packaging Lines
- Implementing Servo Motors in Raspberry Pi-Based Drones
- Building a Servo-Powered Automated Sorting Robot with Raspberry Pi and AI
About Us
- Lucas Bennett
- Welcome to my blog!
Hot Blog
- Troubleshooting and Fixing RC Car Receiver Power Issues
- A Breakdown of the Control Circuit Inside Micro Servo Motors
- How to Power Servo Motors with Raspberry Pi Safely
- Micro Servo Motors for Pan-Tilt Camera Gimbals on Robots
- How to Build a Remote-Controlled Car with Autonomous Driving Capabilities
- Building a Micro Servo Robotic Arm with Open-Source Software
- Smart Pet Door Controlled by Micro Servo Motors
- Diagnosing and Fixing RC Car Motor Vibration Issues
- Micro Servo Motors for VTOL Drone Control Surfaces
- Building a Micro Servo Robotic Arm with a Servo Motor Controller
Latest Blog
- The Use of PWM in Signal Demodulation
- How to Control Servo Motors Using Raspberry Pi and the pigpio Library for Precision Robotics
- Using a Pressure Sensor to Control Your Micro Servo Robotic Arm
- PWM in Audio Amplifiers: Applications and Benefits
- The Role of Micro Servo Motors in Smart Scientific Systems
- How to Use Thermal Imaging for Motor Diagnostics
- Troubleshooting and Fixing RC Car Steering Sensitivity Problems
- Best Micro Servo Motors for DIY Electronics Projects
- How to Build a Remote-Controlled Car with Independent Suspension
- Using Arduino to Control the Angle of a Micro Servo Motor
- Micro Servos for Low Voltage Drones (3.7V or less)
- Micro Servo Motors in Automated Assembly Lines
- The Basics of PWM Signal Generation
- Micro Servo Motors in Industrial Automation: Innovations and Trends
- How to Connect a Servo Motor to Raspberry Pi Without a Breadboard
- Understanding the Mechanics of a Micro Servo-Powered Robotic Arm
- How to Troubleshoot Power Failures in Your RC Car
- Using Micro Servos for Smart Vent Covers for Climate Control
- Building a Servo-Controlled Automated Curtain System with Arduino
- Micro Servo vs Standard Servo: Whichever Serves Better for Torque to Weight Ratio