Using Raspberry Pi to Control Servo Motors in Automated Inspection and Sorting Systems

Micro Servo Motor with Raspberry Pi / Visits:7

The Micro Servo Motor Revolution: Why Small Motors Are the Big Brain of Smart Factory Lines

If you’ve ever watched a high-speed sorting line at an Amazon fulfillment center, you’ve seen the ballet of robotic arms, conveyor belts, and camera flashes. But beneath the industrial gloss, the unsung hero is often a tiny, cheap, and surprisingly precise component: the micro servo motor. When paired with a Raspberry Pi, these palm-sized actuators become the muscle fibers of automated inspection and sorting systems that can be built on a benchtop, tested in a dorm room, and scaled to a warehouse.

This article isn’t a dry datasheet. It’s a hands-on, opinionated, and slightly obsessive dive into why micro servo motors (especially the classic SG90 and MG90S) are the perfect fit for Raspberry Pi–based sorting rigs, how to wire them without letting the magic smoke out, and how to code them for real-world inspection tasks—complete with camera feedback, timing loops, and failure handling.

The Micro Servo Motor: Not Just a Toy Anymore

Let’s get one thing straight: the micro servo motor (typically 9g to 12g, 4.8V to 6V) is not a weakling. It’s a complete closed-loop system in a tiny plastic box: a DC motor, a gear train, a potentiometer for feedback, and a control board that listens to PWM (pulse-width modulation) signals. You command a position (say, 90°), and the servo fights to get there, holding that position against light loads.

For inspection and sorting, that’s gold. Here’s why:

  • Positional repeatability: A decent micro servo returns to the same angle within ±1°–2°. That’s enough to flip a lever, push a defective part, or rotate a camera turret.
  • Low power draw: A single SG90 stalls around 250mA, but typical operation is 50–80mA. A Raspberry Pi’s 5V rail can handle two or three servos if you’re careful (and use a separate BEC or capacitor).
  • Instant response: Servos update at 50Hz (20ms period), so a 180° sweep takes ~0.1–0.2s. For sorting at 2–3 items per second, that’s borderline, but with clever gating and pre-positioning, it works.
  • Cost: You can buy five SG90s for the price of a pizza. That means you can build a 4-way sorter for under $20 in actuators.

But here’s the catch: micro servos are not stepper motors. They don’t give you absolute encoder counts, and they don’t like being back-driven. If your sorting chute jams, the servo will buzz, draw current, and eventually burn out its transistor. So your Raspberry Pi code must handle stall detection (via current sensing or timeouts) and gracefully reset the system.

Wiring a Micro Servo to a Raspberry Pi: The Right Way, Not the Lazy Way

Let’s avoid the classic beginner mistake: powering a servo directly from the Pi’s 3.3V pin. That’s a one-way ticket to undervoltage warnings and random reboots. Here’s the bulletproof setup:

What You Need

  • Raspberry Pi (any model, but Pi 4B or Pi Zero 2 W for camera work)
  • Micro servo (SG90 for light loads, MG90S for metal gears and higher torque)
  • External 5V 2A power supply (or a 4.8V–6V battery pack)
  • 470µF electrolytic capacitor across the servo power pins (to absorb spikes)
  • A 1kΩ resistor in series with the signal line (optional but recommended)
  • Level shifter? No – the servo signal line is 3.3V tolerant on most SG90s, but to be safe, use a 3.3V-to-5V level shifter if your servo is old or cheap.

The Wiring Diagram (Text Version)

Raspberry Pi Micro Servo 5V (pin 2) --------> VCC (red) [DO NOT USE PI 5V FOR MORE THAN 1 SERVO] GND (pin 6) --------> GND (brown) GPIO 18 --------> Signal (orange/yellow) [via 1k resistor]

Power the servo from the external 5V supply separately. Connect the external supply’s ground to the Pi’s ground (common ground). This prevents brownouts.

Pro tip: If you’re running two or more servos, use a small servo driver board (PCA9685) over I2C. The Pi only needs two wires (SDA, SCL) to control 16 servos, and the board has its own power input. That’s the industrial approach.

Software: From PWM Jitter to Smooth, Deterministic Control

The Raspberry Pi is not a real-time controller. Linux can preempt your Python script for 10–100ms, which is an eternity for a servo expecting a 20ms pulse. So you have three options:

  1. Use the hardware PWM module (via pigpio or rpi-hardware-pwm). This offloads the waveform generation to the Pi’s dedicated PWM hardware, giving jitter-free signals.
  2. Use a dedicated servo driver board (PCA9685) which generates its own PWM independent of Linux.
  3. Use software PWM but with a real-time priority – risky but works for non-critical demos.

I’ll show you the pigpio approach because it’s the most direct and reliable for a single servo.

Setting Up pigpio

bash sudo apt install pigpio python3-pigpio sudo systemctl enable pigpiod sudo systemctl start pigpiod

Then in Python:

python import pigpio import time

SERVO_GPIO = 18 pi = pigpio.pi() # connect to local daemon

Set servo range (500µs to 2500µs maps to 0° to 180°)

pi.setservopulsewidth(SERVO_GPIO, 1500) # center time.sleep(1)

Sweep to 0°

pi.setservopulsewidth(SERVO_GPIO, 500) time.sleep(1)

Sweep to 180°

pi.setservopulsewidth(SERVO_GPIO, 2500) time.sleep(1)

Turn off pulse (servo releases)

pi.setservopulsewidth(SERVO_GPIO, 0) pi.stop()

Notice the set_servo_pulsewidth function. It expects microseconds, not duty cycle percentages. This is the key to smooth motion. You can also ramp the pulse width in small increments to create acceleration/deceleration profiles—critical for sorting arms that shouldn’t fling parts across the room.

Building a Camera-Guided Sorting System: The Full Project

Let’s design a concrete example: a Raspberry Pi–based inspection station that sorts small colored beads (red, green, blue) into three bins using a micro servo–actuated flipper.

The setup:

  • A conveyor belt (or a simple inclined track) carries beads one at a time.
  • A Raspberry Pi Camera Module v2 captures an image of each bead as it passes under a fixed frame.
  • OpenCV (or a simple color detection script) classifies the bead.
  • Based on the classification, the Pi sends a PWM command to a micro servo that rotates a flipper arm, diverting the bead into the correct bin.

The Mechanical Design (Simplified)

  • The servo is mounted sideways, with a 3D-printed arm (or a popsicle stick) attached to the spline.
  • At rest, the arm is horizontal, allowing beads to roll past into a default bin.
  • When a bead is detected as red, the arm rotates to 45° (pulse 1250µs), deflecting the bead into the red bin.
  • After a 200ms delay, the arm returns to horizontal.

The timing is critical: you need to know the bead’s speed and the distance from the camera to the flipper. If the camera is 10cm upstream and the bead moves at 5cm/s, you have 2 seconds to process the image and trigger the servo. That’s plenty for a Pi 4B.

Code Structure with Threading

Here’s a skeleton that uses a background thread for the camera and a main loop for the servo control. This avoids blocking the GPIO while waiting for the camera.

python import pigpio import cv2 import numpy as np import threading import queue import time

Servo setup

SERVOPIN = 18 pi = pigpio.pi() pi.setservopulsewidth(SERVOPIN, 1500) # neutral position

Camera setup

cap = cv2.VideoCapture(0) cap.set(cv2.CAPPROPFRAMEWIDTH, 320) cap.set(cv2.CAPPROPFRAMEHEIGHT, 240)

Queue for detected colors

color_queue = queue.Queue(maxsize=2)

def detectcolor(frame): # Convert to HSV hsv = cv2.cvtColor(frame, cv2.COLORBGR2HSV)

# Define color ranges (tune these!) red_lower = np.array([0, 100, 100]) red_upper = np.array([10, 255, 255]) green_lower = np.array([40, 100, 100]) green_upper = np.array([80, 255, 255]) blue_lower = np.array([100, 100, 100]) blue_upper = np.array([130, 255, 255])  # Count pixels in each range red_mask = cv2.inRange(hsv, red_lower, red_upper) green_mask = cv2.inRange(hsv, green_lower, green_upper) blue_mask = cv2.inRange(hsv, blue_lower, blue_upper)  red_count = np.sum(red_mask > 0) green_count = np.sum(green_mask > 0) blue_count = np.sum(blue_mask > 0)  if red_count > green_count and red_count > blue_count:     return "red" elif green_count > red_count and green_count > blue_count:     return "green" elif blue_count > red_count and blue_count > green_count:     return "blue" else:     return "unknown" 

def camerathread(): while True: ret, frame = cap.read() if not ret: continue # Only process if queue is empty (avoid backlog) if colorqueue.empty(): color = detectcolor(frame) if color != "unknown": colorqueue.put(color) time.sleep(0.05) # ~20 FPS

def servoactuate(color): if color == "red": pi.setservopulsewidth(SERVOPIN, 1000) # 45° left elif color == "green": pi.setservopulsewidth(SERVOPIN, 1500) # center elif color == "blue": pi.setservopulsewidth(SERVOPIN, 2000) # 45° right time.sleep(0.3) pi.setservopulsewidth(SERVO_PIN, 1500) # return to neutral

Start camera thread

t = threading.Thread(target=camera_thread, daemon=True) t.start()

Main loop

try: while True: if not colorqueue.empty(): color = colorqueue.get() print(f"Detected: {color}") servoactuate(color) time.sleep(0.01) except KeyboardInterrupt: pass finally: pi.setservopulsewidth(SERVOPIN, 0) cap.release() pi.stop()

This code is intentionally basic—you’d add a motion sensor or a photogate to trigger capture, and you’d calibrate the HSV ranges for your lighting. But the core principle is there: asynchronous camera processing + synchronous servo actuation.

Advanced Techniques for Micro Servo Precision in Sorting

1. Micro-Stepping the Servo (Pulse Ramping)

Instead of jumping from 1500µs to 1000µs, ramp the pulse width over 20–50ms in 10µs increments. This reduces mechanical shock and prevents the flipper from overshooting.

python def smooth_move(pi, pin, start_pw, end_pw, steps=20, step_delay=0.005): delta = (end_pw - start_pw) / steps for i in range(steps + 1): pw = int(start_pw + delta * i) pi.set_servo_pulsewidth(pin, pw) time.sleep(step_delay)

2. Using a Feedback Potentiometer for Position Verification

Some micro servos (like the SG90) have an internal pot, but you can’t read it directly. However, you can add an external Hall-effect sensor or a micro switch to confirm the flipper reached the correct position. This is a cheap way to add fault detection.

3. Handling Servo Stall and Overcurrent

Monitor the servo’s current draw via an INA219 sensor. If the current exceeds 500mA for more than 200ms, assume a jam. Then:

  • Send PWM pulse 0 (release servo).
  • Activate a buzzer or LED.
  • Wait 2 seconds, then retry.

This prevents burning out the servo’s motor and the Pi’s power supply.

Real-World Performance: What to Expect

With a Pi 4B and a well-tuned color detection, you can reliably sort 2–3 beads per second. The bottleneck isn’t the servo—it’s the camera exposure and OpenCV processing. If you use a Pi Zero 2 W, expect 1–2 per second. If you use a dedicated vision co-processor (like a Coral TPU), you can push 10+ per second, but then the servo becomes the bottleneck—you’d need a faster actuator or a multi-stage sorting mechanism.

Here’s a performance table from my own bench tests:

| Component | Typical Latency | |-----------|----------------| | Camera capture (320x240) | 20–30ms | | Color detection (HSV mask) | 5–15ms | | Servo move (90° sweep) | 120–180ms | | Total per item (no pipelining) | 150–225ms |

That’s about 4–6 items per second if you pipeline the camera and servo (capture next bead while current bead is being sorted). In practice, you’ll hit 3–4 per second with a single servo.

Troubleshooting Common Micro Servo Issues on Raspberry Pi

Servo Jitters or Twitches

  • Cause: Insufficient power or ground noise.
  • Fix: Add a 470µF capacitor across the servo’s power pins. Use a separate 5V supply. Shorten the signal wire.

Servo Moves Then Stops Randomly

  • Cause: The pigpio daemon lost the PWM signal due to a system load spike.
  • Fix: Increase the servo’s update frequency to 100Hz (set set_PWM_frequency), or move to a dedicated PWM board.

Servo Gets Hot

  • Cause: The servo is fighting a mechanical limit (stall).
  • Fix: Add a mechanical stop. Or in software, reduce the pulse width range to 600µs–2400µs instead of 500µs–2500µs.

Camera and Servo Interfere (Wi-Fi Dropouts)

  • Cause: The servo’s current spikes cause voltage dips that reset the Pi’s Wi-Fi.
  • Fix: Use a ferrite bead on the servo power line. Or better, use a wired Ethernet connection for the Pi.

Scaling Up: Multi-Servo Sorting Arrays

When one servo isn’t enough, you build a sorting matrix. Imagine four servos arranged in a line, each with a flipper. Beads roll down a track. The first camera identifies the bead. The Pi calculates which flipper to activate based on the bead’s position (using a rotary encoder on the conveyor or a set of IR break beams).

Here’s the control logic:

  • Each servo has a “home” angle (e.g., 90°) that lets beads pass.
  • When a bead of color X is detected, the Pi waits until the bead crosses the IR sensor at flipper #2, then triggers servo #2 to 45° for 150ms, then returns.
  • If two beads are close together, the Pi uses a priority queue to schedule servo actions.

This is exactly how industrial sorters work, just scaled down. The Raspberry Pi can handle this with pigpio’s wave chains or a PCA9685 board.

The Future: Micro Servos + Machine Learning on Raspberry Pi

The latest trend is using a Raspberry Pi with a camera and a lightweight neural network (like MobileNet or EfficientNet-Lite) to classify defects on a production line. The micro servo then acts as the physical reject mechanism. For example:

  • A Pi 4B runs TensorFlow Lite to detect cracked solder joints on PCBs.
  • When a defect is found, a micro servo pushes the PCB off the conveyor into a rework bin.

The beauty is that the servo doesn’t care what the “brain” is—it just needs a 50Hz PWM signal. So you can swap out the color detection for a YOLO model and the same servo code works.

Final Thoughts on Micro Servos and Raspberry Pi

The micro servo motor is often dismissed as a hobbyist toy. But in an automated inspection and sorting context, it’s a surprisingly robust actuator when you respect its limitations. The Raspberry Pi, with its GPIO, camera interface, and Python ecosystem, is the perfect partner. Together, they let you build a sorting system that would have cost $10,000 in industrial hardware just a decade ago—for less than $100 and a weekend of coding.

The key takeaways:

  • Always power servos from an external supply – never from the Pi’s 5V rail for more than one servo.
  • Use hardware PWM (pigpio) for jitter-free control.
  • Pipeline camera and servo operations to maximize throughput.
  • Add a stall detection mechanism to protect your servos.
  • Tune your pulse width ranges – not all servos are the same; find your unit’s actual 0° and 180° pulse widths.

So grab a Raspberry Pi, a bag of SG90s, and some random objects from your desk. Build a sorter that separates paperclips by color, or a quality gate that rejects bent pins. The micro servo will surprise you—it’s small, but it punches way above its weight when you give it a good brain.

Copyright Statement:

Author: Micro Servo Motor

Link: https://microservomotor.com/micro-servo-motor-with-raspberry-pi/raspberry-pi-servo-inspection-sorting.htm

Source: Micro Servo Motor

The copyright of this article belongs to the author. Reproduction is not allowed without permission.

About Us

Lucas Bennett avatar
Lucas Bennett
Welcome to my blog!

Tags