Using Raspberry Pi to Control Servo Motors in Automated Sorting Systems

Micro Servo Motor with Raspberry Pi / Visits:3

When it comes to building a low-cost, high-flexibility automated sorting system, few components pair as elegantly as the Raspberry Pi and the micro servo motor. These tiny but powerful actuators have become the backbone of countless maker-grade industrial prototypes, educational sorting rigs, and even small-scale warehouse automation projects. In this article, we’ll dive deep into how you can leverage the Raspberry Pi’s GPIO capabilities to precisely control micro servo motors, turning a pile of mixed objects into a neatly organized stream. We’ll cover everything from hardware wiring and software libraries to real-world sorting logic and performance tuning.

Why Micro Servo Motors Are the Perfect Fit for Sorting

Micro servo motors—often the SG90 or MG90S variants—are small, lightweight, and surprisingly strong for their size. In an automated sorting system, they typically actuate flaps, gates, or pusher arms that redirect items on a conveyor belt. Here’s why they dominate this application:

  • Precise angular control – With a 180° or 270° rotation range and PWM-based positioning, you can set a micro servo to any angle with 1–2° accuracy. This means you can reliably open a chute at 45° for one category and 90° for another.
  • Fast response time – A typical micro servo can sweep 60° in about 0.12 seconds under no load. In a sorting line running at 30 items per minute, that’s more than enough speed to flip a gate between arrivals.
  • Low power consumption – Running on 5V and drawing only 100–200 mA under load, micro servos can be powered directly from the Raspberry Pi’s 5V rail (with proper current budgeting) or from a small external supply.
  • Cost efficiency – A pack of five SG90 servos costs less than $15. For a multi-lane sorting system, this keeps the bill of materials remarkably low.

Of course, micro servos have limitations. They aren’t designed for continuous rotation (though you can mod them), and their plastic gears can strip under heavy or repeated shock loads. For sorting lightweight items—like plastic caps, small electronic components, or candy—they are ideal. For heavier objects, you’d step up to a standard servo or a linear actuator.

Hardware Setup: Wiring Your Raspberry Pi to a Micro Servo

Before writing a single line of code, you need a reliable electrical connection. The micro servo has three wires: power (red), ground (brown or black), and signal (orange or yellow). The Raspberry Pi’s GPIO pins operate at 3.3V logic, while most micro servos expect a 5V signal. Fortunately, the 3.3V high level is still recognized by most servo controllers as a logic high, so you can drive the signal pin directly from a GPIO.

Wiring Diagram (Simplified)

  • Red wire → Raspberry Pi 5V pin (Pin 2 or 4)
  • Brown/Black wire → Raspberry Pi GND (Pin 6, 14, 20, etc.)
  • Orange/Yellow wire → GPIO 18 (Pin 12) – this is a hardware PWM-capable pin

Important: If you are driving more than two micro servos, do not power them from the Pi’s 5V rail. The Pi’s voltage regulator can only supply about 1.5A total, and each servo can spike to 700 mA during a fast move. Instead, use an external 5V power supply (2A or higher) and connect all servo grounds to the Pi’s ground to maintain a common reference. The signal wire still goes directly to the GPIO.

Power Supply Considerations

For a single micro servo in a demo sorting rig, the Pi’s 5V pin is fine. For three or more servos moving simultaneously, use a dedicated 5V 3A adapter. Connect the adapter’s positive to the servo power rail, and its negative to both the servo ground and the Pi’s ground. This prevents ground loops and brownouts.

Software Foundations: PWM and the pigpio Library

The Raspberry Pi can generate hardware-based PWM on GPIO 12, 13, 18, and 19. Hardware PWM is far more stable than software bit-banging, especially when controlling multiple servos. The pigpio library provides a daemon-based interface that gives you microsecond-level control over pulse width, which is exactly what servos need.

A micro servo’s position is determined by the duration of a 50 Hz PWM pulse (20 ms period):

  • → 1.0 ms pulse (sometimes 0.5 ms, depending on the servo)
  • 90° → 1.5 ms pulse
  • 180° → 2.0 ms pulse (sometimes 2.5 ms)

These values vary slightly between manufacturers. You’ll need to calibrate your specific servo by testing the extremes.

Installing pigpio

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

Then in your Python script:

python import pigpio import time

pi = pigpio.pi() if not pi.connected: exit()

servogpio = 18 pi.setservopulsewidth(servogpio, 0) # off

def setangle(angle): # Convert angle (0–180) to pulse width (1000–2000) pulse = 1000 + (angle / 180.0) * 1000 pi.setservopulsewidth(servogpio, pulse)

Example: sweep from 0 to 180

for angle in range(0, 181, 10): set_angle(angle) time.sleep(0.5)

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

Calibrating Your Micro Servo

Not all servos respond identically. Run a quick calibration script that steps through pulse widths from 500 to 2500 µs and observe the mechanical limits. Record the minimum and maximum safe pulse widths. For many SG90 servos, the safe range is 600–2400 µs. Exceeding these can damage the servo or cause it to jam.

Building the Sorting Logic: From Sensor Input to Servo Action

An automated sorting system needs three things: a way to detect an object, a way to classify it, and a way to physically divert it. The micro servo handles the diversion. Let’s walk through a concrete example: sorting red and blue plastic tokens on a conveyor belt.

Sensor Integration (Briefly)

Assume we have a color sensor (like a TCS34725) positioned above the belt. When a token passes under it, the Raspberry Pi reads the RGB values and classifies the color. Simultaneously, an infrared break-beam sensor triggers to confirm an object is present.

The sorting decision must happen quickly—within 200 ms—so that the servo has time to move before the token reaches the diverter gate.

The Servo as a Gate

The micro servo is attached to a lightweight 3D-printed flap. At rest (0°), the flap is flush with the belt, allowing tokens to pass straight to a default bin. When a red token is detected, the servo rotates to 90°, pushing the flap across the belt and redirecting the token into a side chute. After a short delay (enough for the token to clear), the servo returns to 0°.

Here’s the core logic:

python def sort_token(color): if color == "red": set_angle(90) # divert time.sleep(0.3) # wait for token to fall set_angle(0) # reset elif color == "blue": set_angle(45) # different angle for blue time.sleep(0.3) set_angle(0) else: # do nothing – pass straight pass

Timing Constraints

The belt moves at 10 cm/s. The distance from the sensor to the gate is 15 cm. That gives you 1.5 seconds to process and actuate. Even with Python’s overhead, you can easily meet this. For faster belts (e.g., 50 cm/s), you might need to pre-compute the angle and use a hardware timer or a real-time thread.

Multi-Servo Coordination for Complex Sorting

When you have multiple sorting stations—say, three bins for different material types—you need multiple micro servos working in sequence. The Raspberry Pi can control up to 12 servos with hardware PWM if you use a PWM driver board like the PCA9685. But for up to 4 servos, direct GPIO control with pigpio works fine.

Example: Three-Way Sorter

  • Servo 1 controls a gate that either passes the item straight or diverts it to a secondary belt.
  • Servo 2 on the secondary belt diverts to Bin A or Bin B.
  • Servo 3 handles a reject flap for unclassified items.

The challenge is timing. You cannot move Servo 2 until the item has physically arrived on the secondary belt. You can calculate this from belt speed and distance, or use a second break-beam sensor to trigger the action.

State Machine Approach

A simple state machine keeps everything organized:

python currentstate = "IDLE" itemcolor = None

while True: if sensortriggered(): itemcolor = classifycolor() currentstate = "PRIMARY_SORT"

if current_state == "PRIMARY_SORT":     if item_color == "metal":         set_servo_angle(1, 90)   # divert to secondary belt         current_state = "WAIT_FOR_SECONDARY"     elif item_color == "plastic":         set_servo_angle(1, 0)    # pass straight to bin         current_state = "IDLE"     else:         set_servo_angle(1, 45)   # reject         current_state = "IDLE"  if current_state == "WAIT_FOR_SECONDARY":     if secondary_sensor_triggered():         set_servo_angle(2, 90)   # divert to metal bin         time.sleep(0.3)         set_servo_angle(2, 0)         current_state = "IDLE" 

This keeps the code readable and prevents conflicting servo commands.

Advanced Control: Smooth Motion and Acceleration

A micro servo that snaps from 0° to 90° instantly can cause the object to bounce or the flap to overshoot. For delicate items, you want smooth acceleration and deceleration. You can achieve this by breaking the movement into smaller steps with incremental delays.

Ramping Function

python def smooth_move(start_angle, end_angle, duration=0.5): steps = 20 step_delay = duration / steps angle_step = (end_angle - start_angle) / steps for i in range(steps + 1): current_angle = start_angle + angle_step * i set_angle(current_angle) time.sleep(step_delay)

This creates a gentle, linear motion. For even smoother operation, you can apply an easing function (e.g., ease-in-out) to vary the step size.

Using Hardware PWM Frequency

The pigpio library’s set_servo_pulsewidth is already hardware-timed, so the pulse width is precise. However, the update rate is limited by your loop speed. For truly smooth motion, consider using the hardware_PWM function to generate a continuous PWM signal and then modulate the pulse width in a separate thread. This offloads the timing from Python’s GIL.

Real-World Performance Tuning

In production-like sorting, you’ll encounter several practical issues:

Jitter and Noise

If your servo jitters at a specific angle, the pulse width might be at a boundary where the servo’s internal potentiometer is noisy. Slightly adjust the pulse by ±20 µs. Also, ensure your power supply is clean—add a 100 µF capacitor across the servo power rails.

Heat Management

Micro servos running continuously (e.g., 50 cycles per minute) can overheat. If your sorting system runs for hours, reduce the holding torque by sending a “relax” command (pulse width of 0) when the servo is not actively moving. This stops the motor from fighting against the feedback potentiometer.

Calibration Drift

Over time, the mechanical linkage (flap, arm) may wear or loosen. Re-calibrate the end stops every few hundred cycles. You can automate this by homing the servo to a physical stop and recording the pulse width.

Scaling Up: From Prototype to Production

A Raspberry Pi with four micro servos can handle a modest sorting line (20–40 items per minute). For higher throughput, consider these upgrades:

  • Use a dedicated servo controller – The PCA9685 can drive 16 servos over I2C, freeing up the Pi’s GPIO for sensors. It also handles the 50 Hz PWM generation in hardware, reducing CPU load.
  • Parallel processing – Use Python’s threading or multiprocessing to handle sensor reading and servo control in separate threads. The pigpio library is thread-safe.
  • Feedback loop – Add a potentiometer or encoder to the servo shaft for closed-loop position control. This compensates for load variations and ensures the flap always reaches the exact angle.

Example with PCA9685

python from adafruit_servokit import ServoKit kit = ServoKit(channels=16)

kit.servo[0].angle = 90 # moves servo on channel 0 to 90° kit.servo[0].setpulsewidth_range(600, 2400)

The ServoKit library abstracts away PWM details and gives you a clean API. It also supports continuous rotation servos if you ever need a conveyor belt drive.

Putting It All Together: A Complete Sorting Cycle

Let’s outline a full, code-level example for a single-lane sorter that separates three types of objects using two micro servos.

Hardware: - Raspberry Pi 4 - 2x SG90 micro servos (Servo A: primary gate, Servo B: secondary gate) - TCS34725 color sensor (I2C) - IR break-beam sensor (GPIO 17)

Workflow:

  1. Wait for IR sensor to trigger.
  2. Read color sensor.
  3. Decide category: Metal, Plastic, or Paper.
  4. If Metal: move Servo A to 90° (divert to secondary belt), wait for second IR sensor, then move Servo B to 90° (into Metal bin).
  5. If Plastic: move Servo A to 45° (direct to Plastic bin directly).
  6. If Paper: keep Servo A at 0° (pass straight to Paper bin).
  7. Reset all servos to idle (0°).

Python Pseudocode:

python import pigpio import time import board import busio import adafruit_tcs34725

pi = pigpio.pi() i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_tcs34725.TCS34725(i2c)

SERVOA = 18 SERVOB = 19 IR_PIN = 17

def setangle(servo, angle): pulse = 1000 + (angle / 180.0) * 1000 pi.setservo_pulsewidth(servo, pulse)

def classify_color(r, g, b): if r > 200 and g < 100: return "metal" # reflective surface elif g > 150 and b < 100: return "plastic" else: return "paper"

pi.setmode(IRPIN, pigpio.INPUT)

while True: if pi.read(IRPIN) == 0: # object detected time.sleep(0.05) # debounce r, g, b = sensor.colorrgbbytes category = classifycolor(r, g, b)

    if category == "metal":         set_angle(SERVO_A, 90)         time.sleep(0.5)         # wait for secondary sensor (simulated)         time.sleep(0.3)         set_angle(SERVO_B, 90)         time.sleep(0.3)         set_angle(SERVO_B, 0)         set_angle(SERVO_A, 0)     elif category == "plastic":         set_angle(SERVO_A, 45)         time.sleep(0.5)         set_angle(SERVO_A, 0)     else:         # paper – do nothing         pass      time.sleep(0.2)  # gap between items 

This is a fully functional sorting loop. In practice, you’d add error handling, logging, and a user interface (maybe a simple Flask dashboard) to monitor throughput and servo health.

Optimizing for High-Speed Sorting

If you need to sort 60+ items per minute, the bottleneck becomes Python’s loop speed and the servo’s physical movement time. You can mitigate this by:

  • Pre-calculating angles – Store pulse widths in a lookup table instead of computing them on the fly.
  • Using C extensions – The pigpio library is already a C daemon, but you can write a small C program that reads sensor data from a FIFO and controls servos directly.
  • Double buffering – While one servo is moving, the next object is already being classified. This requires careful state management but doubles throughput.

Micro Servo Lifespan in Sorting Duty

A typical micro servo is rated for 50,000–100,000 cycles. In a sorting system running 8 hours a day at 30 cycles per minute, that’s about 14,400 cycles per day. You’ll hit the lifespan in roughly a week. For longer-running systems, use metal-gear servos (MG90S) or industrial-grade micro servos with replaceable potentiometers. Also, lubricate the output shaft periodically with silicone grease.

Final Thoughts on Raspberry Pi and Micro Servo Synergy

The combination of a $35 Raspberry Pi and a $3 micro servo motor creates a sorting system that is affordable, reprogrammable, and surprisingly capable. Whether you’re building a STEM classroom demonstration, a recycling sorter for a community workshop, or a prototype for a small business, the principles are the same: clean power, precise PWM, and well-timed logic.

The micro servo’s role in this ecosystem is often underestimated. It’s not just a “toy motor”—it’s a precision actuator that, when paired with the Pi’s GPIO and a good software library, can reliably perform thousands of sorting operations per hour. The key is to respect its mechanical limits, calibrate thoroughly, and design your sorting logic to minimize unnecessary movement.

As you scale up, you’ll discover that the micro servo’s small size becomes an advantage—you can pack multiple diverters into a compact footprint, creating a dense sorting matrix. With a PCA9685 and a few dozen servos, you can build a system that rivals commercial sorters at a fraction of the cost.

So grab a Raspberry Pi, a handful of micro servos, and start sorting. The only limit is how creative you want to get with your gates, flaps, and pushers.

Copyright Statement:

Author: Micro Servo Motor

Link: https://microservomotor.com/micro-servo-motor-with-raspberry-pi/automated-sorting-servo-raspberry-pi.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