Building a Servo-Powered Automated Sorting Robot with Raspberry Pi and Sensors

Micro Servo Motor with Raspberry Pi / Visits:50

When I first started tinkering with robotics, I was fascinated by the precision and versatility of micro servo motors. These tiny actuators, often no bigger than a pack of gum, can rotate to exact positions with remarkable accuracy. They’re the unsung heroes of countless maker projects—from robotic arms to camera gimbals. But what if we could combine several micro servo motors with a Raspberry Pi and a suite of sensors to build something truly functional: an automated sorting robot?

This blog post is a deep dive into exactly that. We’ll walk through the entire process of designing, assembling, and programming a sorting robot that uses micro servo motors for physical sorting actions, a Raspberry Pi as the brain, and optical sensors to identify objects. Whether you’re a hobbyist looking for your next weekend project or an educator seeking a hands-on demonstration of mechatronics, this guide will give you a complete framework.

Why Micro Servo Motors Are the Perfect Choice for Sorting

Before we jump into the build, let’s talk about why micro servo motors are ideal for this application. A sorting robot needs to perform small, repeatable, and precise mechanical movements—pushing objects into bins, rotating a turntable, or opening a gate. Large motors would be overkill, and stepper motors, while precise, require more complex drivers and power. Micro servo motors hit the sweet spot.

Key Advantages of Micro Servos in Sorting Robots

  • Precision Positioning: Most micro servos can rotate from 0 to 180 degrees with a resolution of about 1 degree. That’s enough to align a sorting arm with multiple bins.
  • Built-in Control: They don’t need external encoders or complex PID loops. A simple PWM signal from the Raspberry Pi GPIO pins tells them exactly where to go.
  • Low Power Consumption: A typical micro servo draws 100-200 mA under load, which is perfect for battery-powered or USB-powered Raspberry Pi setups.
  • Small Form Factor: They fit into tight spaces. You can mount three or four of them on a small chassis without making the robot bulky.
  • Cost-Effective: High-quality micro servos like the SG90 or MG90S cost under $5 each. For a sorting robot with three sorting stations, you’re looking at under $15 for all actuators.

Of course, there are trade-offs. Micro servos have limited torque—usually around 1-2 kg·cm—so they can’t lift heavy objects. But for sorting small items like coins, beads, or even plastic tokens, they’re more than adequate.

Overview of the Sorting Robot Architecture

Our robot will consist of three main subsystems:

  1. Sensing: A camera (or multiple color sensors) identifies objects on a conveyor belt or sliding ramp.
  2. Processing: The Raspberry Pi runs a Python script that interprets sensor data and decides which bin the object belongs to.
  3. Actuation: Micro servo motors physically push or guide the object into the correct bin.

The entire system operates in a loop: sense, decide, actuate, repeat. The micro servos are the only moving parts, which keeps mechanical complexity low.

The Mechanical Design at a Glance

  • Base Platform: A laser-cut acrylic or 3D-printed frame, about 20x30 cm.
  • Feeding Mechanism: A gravity-fed ramp or a slow-moving conveyor belt (driven by another servo or a DC motor).
  • Sorting Gates: Three micro servo motors, each controlling a small door or paddle that diverts objects into separate bins.
  • Sensor Array: A Raspberry Pi Camera Module v2 positioned above the ramp, looking down at objects as they pass.

Step 1: Selecting the Right Micro Servo Motors

Not all micro servos are created equal. For this project, I tested three common models: the SG90, the MG90S, and the Tower Pro SG92R. Here’s what I found.

SG90 – The Budget Standard

  • Torque: 1.2 kg·cm at 4.8V
  • Speed: 0.12 sec/60 degrees
  • Gears: Plastic
  • Best For: Light-duty sorting where objects weigh under 10 grams.

The SG90 works fine for pushing paper clips or small plastic beads. However, the plastic gears can strip if you apply too much side load. For a sorting robot that might see continuous use, I recommend upgrading.

MG90S – The Metal-Gear Workhorse

  • Torque: 1.8 kg·cm at 4.8V
  • Speed: 0.10 sec/60 degrees
  • Gears: Metal
  • Best For: Sorting heavier objects (up to 30 grams) or applications requiring durability.

This is my go-to for any project where the servo might encounter resistance. The metal gears handle jams better, and the slightly higher torque means you can use longer lever arms for the sorting paddles.

SG92R – The Slim Profile Option

  • Torque: 1.5 kg·cm at 4.8V
  • Speed: 0.11 sec/60 degrees
  • Gears: Plastic
  • Best For: Tight spaces where height is constrained.

If your chassis design is compact, the SG92R’s lower profile (about 2mm shorter than the SG90) can make a difference.

My Recommendation: Use MG90S servos for the sorting gates. They cost a dollar more each but will save you from mid-project failures. For the feeding mechanism (if you use a servo), an SG90 is fine since it only needs to rotate a light paddle.

Step 2: Hardware Setup – Wiring the Servos to the Raspberry Pi

Wiring micro servo motors to a Raspberry Pi is straightforward, but there are a few gotchas.

The Pinout

Each servo has three wires: - Red: Power (5V) - Brown/Black: Ground - Orange/Yellow: Signal (PWM)

Important: The Raspberry Pi’s 5V rail can only supply about 500 mA total. Three micro servos under load might draw up to 600 mA, which can cause voltage drops and random reboots. Always use an external 5V power supply for the servos, and only connect the signal wires to the Pi’s GPIO pins.

Here’s the wiring diagram I used:

  • External 5V 2A power supply → Breadboard power rail (red)
  • Common ground → Breadboard ground rail (black)
  • Servo 1 Signal → GPIO 17
  • Servo 2 Signal → GPIO 27
  • Servo 3 Signal → GPIO 22
  • Pi Ground → Breadboard ground (to share reference)

Never power the servos from the Pi’s 3.3V pin. They require 5V to operate at full torque.

Power Management Tip

Add a 470 µF electrolytic capacitor across the servo power rails. This smooths out current spikes when multiple servos start moving simultaneously. I learned this the hard way after my Pi kept crashing during the “sort all” test.

Step 3: Sensor Integration – Giving the Robot Eyes

The sorting decision depends on what sensor you choose. I’ll cover two popular options.

Option A: Raspberry Pi Camera with OpenCV

This is the most flexible approach. The camera captures an image of each object, and OpenCV identifies its color, shape, or even a QR code.

Hardware: - Raspberry Pi Camera Module v2 (or v3) - Flexible ribbon cable - A small LED ring for consistent lighting

Software Setup: python import cv2 from picamera2 import Picamera2

picam2 = Picamera2() picam2.configure(picam2.createpreviewconfiguration()) picam2.start()

while True: frame = picam2.capturearray() # Convert to HSV for color detection hsv = cv2.cvtColor(frame, cv2.COLORBGR2HSV) # Define color ranges (e.g., red, green, blue) # ... detection logic ... cv2.imshow("Sorting View", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break

The downside? Processing each frame takes about 0.1–0.2 seconds on a Pi 4, which limits throughput. For a production sorting line, you’d want a faster approach.

Option B: TCS34725 Color Sensor Modules

These are small I2C sensors that detect the RGB value of a surface. They’re much faster than camera processing—readings take about 10 ms.

Setup: - Connect VCC to 3.3V, GND to ground, SDA to GPIO 2, SCL to GPIO 3. - Place the sensor directly above the sorting ramp, about 5 mm from the object.

Code Snippet: python import board import busio import adafruit_tcs34725

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

while True: colorrgb = sensor.colorrgbbytes # Classify based on RGB thresholds if colorrgb[0] > 200 and colorrgb[1] < 100: # Mostly red servoposition = 0 # Bin 1 elif colorrgb[1] > 200: # Mostly green servoposition = 90 # Bin 2 else: servo_position = 180 # Bin 3

For this project, I used the TCS34725 for speed, but I added a camera for debugging and visualization.

Step 4: Programming the Servo Control Logic

Now comes the fun part—making the servos move in sync with the sensor readings.

Using the pigpio Library for Smooth Motion

The standard RPi.GPIO library can generate PWM, but it’s software-based and can be jittery. For precise servo control, I use pigpio, which uses the Pi’s hardware PWM.

Installation: bash sudo apt install pigpio sudo systemctl enable pigpiod sudo systemctl start pigpiod

Control Code: python import pigpio import time

pi = pigpio.pi() servopins = [17, 27, 22] servopositions = [0, 0, 0] # Store current positions

def setservoangle(pin, angle): # Convert angle (0-180) to pulse width (500-2500 µs) pulsewidth = 500 + (angle / 180.0) * 2000 pi.setservopulsewidth(pin, pulsewidth) servopositions[servopins.index(pin)] = angle

Initialize all servos to 0 degrees

for pin in servopins: setservo_angle(pin, 0) time.sleep(1)

Example: Sort an object to bin 2 (servo at 90 degrees)

setservoangle(17, 90) time.sleep(0.5) # Wait for gate to open

... object passes ...

setservoangle(17, 0) # Close gate

Smooth Transitions with Ramping

Abrupt servo movements can shake the robot or cause objects to tip over. I implemented a simple ramping function:

python def smooth_move(pin, target_angle, step_delay=0.01): current = servo_positions[servo_pins.index(pin)] step = 1 if target_angle > current else -1 for angle in range(current, target_angle + step, step): set_servo_angle(pin, angle) time.sleep(step_delay)

This moves the servo one degree at a time, creating a smooth, lifelike motion. It also reduces mechanical stress on the gears.

Step 5: Building the Physical Sorting Mechanism

The mechanical design is where micro servo motors shine because of their small size. Here’s how I built the sorting gates.

The Sorting Gate Design

Each gate is a 3D-printed paddle attached directly to the servo horn. The paddle is about 4 cm long and 2 cm wide, with a curved edge to gently push objects sideways.

Key Design Considerations: - Pivot Point: The servo horn should be as close to the pivot axis as possible. Use the supplied screw to secure the horn tightly. - Friction Reduction: Add a small piece of PTFE tape on the ramp surface where the paddle contacts it. This prevents objects from sticking. - Return Spring: For the default (closed) position, the servo should hold the paddle at 0 degrees. The metal gears of the MG90S hold position well without back-driving.

Aligning the Three Gates

I mounted the three servos side by side on a 3D-printed bracket, spaced 6 cm apart. Each gate corresponds to a bin positioned below. When an object is detected, the appropriate servo rotates the paddle from 0 to 90 degrees, deflecting the object into the bin.

Pro Tip: Calibrate each servo’s zero position manually. Because of manufacturing tolerances, a “0 degree” command might result in a slightly different physical angle on different servos. Use a small adjustment screw or software offset to align them.

Step 6: The Complete Sorting Loop

With all components integrated, here’s the full Python script that runs the sorting robot:

python import pigpio import time import board import busio import adafruit_tcs34725

Initialize hardware

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

servopins = [17, 27, 22] currentangles = [0, 0, 0]

def setangle(pin, angle): pulse = 500 + (angle / 180.0) * 2000 pi.setservo_pulsewidth(pin, pulse)

def smoothmove(pin, target, delay=0.008): idx = servopins.index(pin) current = currentangles[idx] step = 1 if target > current else -1 for angle in range(current, target + step, step): setangle(pin, angle) current_angles[idx] = angle time.sleep(delay)

Initialize servos

for pin in servopins: setangle(pin, 0) time.sleep(1)

Main loop

while True: # Read color r, g, b = sensor.colorrgbbytes

# Simple classification if r > 180 and g < 100:     bin = 0  # Red → Bin 1 elif g > 180:     bin = 1  # Green → Bin 2 else:     bin = 2  # Other → Bin 3  # Actuate the corresponding servo smooth_move(servo_pins[bin], 90)  # Open gate time.sleep(0.6)                    # Allow object to pass smooth_move(servo_pins[bin], 0)   # Close gate time.sleep(0.3)                    # Debounce 

This loop runs at about 1–2 objects per second, depending on the ramp speed. With faster servos (like the MG90S) and optimized delays, you can push it to 3–4 objects per second.

Optimizing Servo Performance for High-Throughput Sorting

If you want to sort faster, micro servo motors have limitations you need to work around.

Thermal Management

Continuous operation causes servos to heat up. After 10 minutes of non-stop sorting, my MG90S servos reached 45°C—warm but within spec. To extend lifespan:

  • Reduce the load on the paddle (shorten the lever arm).
  • Add a small heatsink to the servo casing.
  • Implement a “rest” cycle where servos return to 0 degrees for 100 ms between sorts.

Reducing Jitter

Jitter occurs when the PWM signal is unstable. Using pigpio instead of software PWM reduces jitter by 90%. Also, ensure your power supply is clean. A cheap 5V phone charger can introduce noise that makes servos twitch.

Parallel vs. Sequential Movement

In my first version, all servos moved sequentially. This created a bottleneck. I later modified the code to allow one servo to open while another closes, using threading:

python import threading

def sorttobin(binnum): pin = servopins[binnum] smoothmove(pin, 90) time.sleep(0.6) smooth_move(pin, 0)

In main loop:

threading.Thread(target=sorttobin, args=(bin,)).start()

This increased throughput by about 30% because the robot could start processing the next object while the previous gate was still closing.

Troubleshooting Common Micro Servo Issues

Even with careful design, things go wrong. Here are the most common problems I encountered and their fixes.

Servo Hums but Doesn’t Move

This usually means the servo is receiving a signal but is stalled. Causes: - Overload: The paddle is hitting something. Check for mechanical binding. - Incorrect PWM range: Some servos require a narrower pulse range. Try 600–2400 µs instead of 500–2500. - Low voltage: Measure the voltage at the servo under load. If it drops below 4.5V, upgrade your power supply.

Servo Jumps to Random Positions

This is classic electrical noise. Solutions: - Add a 100 nF ceramic capacitor between power and ground near each servo. - Use twisted-pair wires for the signal lines. - Keep servo power wires away from the camera ribbon cable.

Servo Drifts Over Time

If a servo slowly moves away from its commanded position, the potentiometer inside is wearing out. This is common with cheap plastic-gear servos. Replace it with a metal-gear model.

Expanding the Robot – Beyond Three Bins

The beauty of using micro servo motors is that scaling up is easy. Want to sort into six bins? Add three more servos and extend the bracket. The Raspberry Pi has 26 GPIO pins, enough for 26 servos (though you’d need a separate PWM driver like the PCA9685 for more than 10).

Using a PCA9685 PWM Driver

For large-scale sorting, the PCA9685 lets you control 16 servos with just two I2C pins. Here’s a quick adaptation:

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

Control servo 0

kit.servo[0].angle = 90

This offloads all PWM generation from the Pi, freeing up CPU for sensor processing.

Real-World Testing and Performance Metrics

After building the robot, I ran a 500-object sorting test using three colors: red, green, and blue plastic tokens.

Results

  • Accuracy: 97.8% (11 mis-sorts out of 500)
  • Average Cycle Time: 0.82 seconds per object
  • Servo Failures: Zero (MG90S servos)
  • Power Consumption: 5.2V @ 1.1A peak

The mis-sorts were primarily due to two tokens passing the sensor simultaneously—a feeding mechanism issue, not a servo problem. Improving the ramp design to single-file objects would push accuracy above 99%.

Servo Lifespan Test

I ran the robot continuously for 8 hours, sorting about 35,000 objects. The MG90S servos showed no degradation in positioning accuracy. The plastic-gear SG90 on the feeding mechanism, however, started to slip after 12,000 cycles. This reinforces the importance of using metal-gear servos for any load-bearing application.

Final Thoughts on Micro Servos in Automated Sorting

Building this robot taught me that micro servo motors are far more capable than their tiny size suggests. With proper power management, smooth ramping algorithms, and thoughtful mechanical design, they can perform reliable, high-speed sorting tasks that would typically require much larger actuators.

The key is to respect their limitations. Don’t ask a micro servo to lift heavy loads or run at full speed for hours without cooling. But if you design within their torque and duty cycle envelope, they’ll reward you with precise, repeatable motion that forms the backbone of an effective sorting system.

If you’re planning to build your own, start with a single servo and one sensor. Get that working reliably, then scale up. The satisfaction of watching your robot flawlessly sort 100 objects in a row—each micro servo clicking into position exactly as programmed—is one of the best feelings in robotics.

Copyright Statement:

Author: Micro Servo Motor

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