Creating a Servo-Controlled Automated Sorting Machine with Raspberry Pi and Sensors

Micro Servo Motor with Raspberry Pi / Visits:6

If you’ve ever watched a factory conveyor belt in action—where packages zip by and robotic arms flick them into neat bins based on weight, color, or barcode—you’ve witnessed the quiet magic of automation. Now imagine building a scaled-down version of that with a Raspberry Pi, a handful of sensors, and a small but mighty micro servo motor. That’s exactly what we’re diving into today.

Micro servo motors are the unsung heroes of hobbyist robotics. They’re cheap, precise, and easy to control with PWM signals. But when you pair them with a Raspberry Pi’s GPIO pins and a few clever sensors, they transform from simple hinge-movers into the core actuator of a sorting machine that can separate objects by color, size, or even material type.

In this guide, I’ll walk you through the entire process: from selecting the right micro servo and wiring it up, to writing Python code that reads sensor data and commands the servo to flick items into the correct bin. By the end, you’ll have a fully functional desktop sorting machine that demonstrates the same principles used in industrial logistics—minus the six-figure price tag.

Why Micro Servo Motors Are Perfect for This Project

Let’s get one thing straight: not all servos are created equal. For an automated sorting machine, you need speed, torque, and angular precision. A micro servo motor (like the SG90 or MG90S) checks all three boxes.

  • Compact size: Fits easily on a 3D-printed or laser-cut frame.
  • 0° to 180° rotation: Enough range to push objects left, right, or straight ahead.
  • PWM control: Works directly with Raspberry Pi GPIO (no extra motor driver needed).
  • Affordable: Less than $5 each, so you can experiment without breaking the bank.

The key limitation? Micro servos can’t lift heavy loads. But for sorting small items—like M&M’s, screws, or plastic tokens—they’re ideal. The torque of a typical SG90 (around 1.2 kg·cm at 4.8V) is enough to flick a lightweight object off a conveyor ramp.

What Makes This Different from a Standard Servo Project?

Most tutorials show you how to make a servo sweep back and forth. That’s cute, but it’s not a sorting machine. Here, the servo doesn’t just move aimlessly. It reacts in real-time to sensor input. The Raspberry Pi becomes the brain: it reads a sensor, decides which bin the object belongs to, and commands the micro servo to rotate to a specific angle (say, 45° for bin A, 90° for bin B, 135° for bin C). That decision loop is what separates a toy from a functional sorting system.

System Overview: How the Sorting Machine Works

Before we get into wiring and code, let’s map out the physical flow.

  1. Object enters the detection zone – A sensor (color sensor, IR sensor, or ultrasonic sensor) detects the object and captures a property (e.g., color value or distance).
  2. Raspberry Pi processes the data – The Pi runs a Python script that compares the sensor reading to predefined thresholds.
  3. Micro servo motor acts as the gatekeeper – Based on the classification, the servo rotates a small lever or ramp to guide the object into the correct chute.
  4. Object slides into the bin – Gravity or a gentle push from a second servo moves the item along.

The entire cycle happens in under a second. With a well-tuned micro servo, you can sort 10–15 objects per minute—not industrial speed, but impressive for a desktop project.

Hardware Components List

| Component | Purpose | Recommended Model | |---|---|---| | Raspberry Pi | Brain of the operation | Raspberry Pi 3B+, 4B, or Zero 2 W | | Micro servo motor | Sorting actuator | SG90 (plastic gears) or MG90S (metal gears) | | Color sensor | Detect object color | TCS34725 (I2C) | | Ultrasonic sensor | Detect object presence | HC-SR04 | | IR sensor | Simple object detection | TCRT5000 | | Servo power supply | Avoid brownouts | 5V 2A external supply (don’t power from Pi GPIO 5V pin for multiple servos) | | Frame material | Structure | 3D-printed PLA or laser-cut acrylic | | Jumper wires | Connections | Female-to-female, male-to-female |

Wiring the Micro Servo to the Raspberry Pi

This is the part where most beginners make mistakes. The micro servo has three wires: brown/black (ground), red (power), and orange/yellow (signal). The Raspberry Pi GPIO pins output 3.3V logic, but the servo expects a 5V signal. Here’s the safe way to wire it:

Step-by-step Wiring Diagram

  1. Ground – Connect the brown wire to a GND pin on the Pi (e.g., pin 6).
  2. Power – Connect the red wire to a 5V pin on the Pi (e.g., pin 2 or 4). Warning: If you’re using more than one servo, use an external 5V supply. Drawing too much current from the Pi’s 5V rail can crash the system.
  3. Signal – Connect the orange wire to a GPIO pin that supports PWM. I recommend GPIO 18 (physical pin 12) because it’s one of the hardware PWM pins.

For a single micro servo, the Pi’s 5V pin is fine. But if you add a second servo for the conveyor or a pusher, definitely use a separate 5V supply with a common ground.

Dealing with Voltage Level Shifting

The Pi’s 3.3V GPIO output is often enough to trigger the servo signal line, but some servos (especially older ones) expect 5V logic. If your servo jitters or doesn’t respond, insert a level shifter (e.g., a 74AHCT125) between the GPIO and the servo signal wire. For most modern micro servos like the SG90, direct connection works.

Programming the Micro Servo with Python (RPi.GPIO)

Now for the fun part: making the servo dance to your commands. We’ll use the RPi.GPIO library with software PWM. Hardware PWM (via pigpio) is more stable, but software PWM is simpler for beginners.

Basic Servo Sweep Script

python import RPi.GPIO as GPIO import time

SERVOPIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(SERVOPIN, GPIO.OUT)

Create PWM instance at 50Hz (standard for servos)

pwm = GPIO.PWM(SERVO_PIN, 50) pwm.start(0)

def setservoangle(angle): # Convert angle (0-180) to duty cycle (2.5% to 12.5%) duty = 2.5 + (angle / 18.0) pwm.ChangeDutyCycle(duty) time.sleep(0.5) # Give servo time to move pwm.ChangeDutyCycle(0) # Prevent jitter

Test sweep

for angle in [0, 45, 90, 135, 180]: setservoangle(angle) print(f"Moved to {angle} degrees") time.sleep(1)

pwm.stop() GPIO.cleanup()

Why pwm.ChangeDutyCycle(0) after each move? Without it, the servo keeps receiving a signal and may jitter. Setting duty to 0 releases the hold.

Calibrating Your Micro Servo

Not all servos map 0° to the same duty cycle. Run the script above and observe the actual positions. You might find that 0° actually points to 10° to the left. Adjust the duty formula accordingly:

python

Custom calibration for your specific servo

def setservoangle(angle): dutymin = 2.0 # e.g., 0° corresponds to 2.0% duty dutymax = 12.0 # e.g., 180° corresponds to 12.0% duty duty = dutymin + (angle / 180.0) * (dutymax - duty_min) pwm.ChangeDutyCycle(duty) time.sleep(0.3) pwm.ChangeDutyCycle(0)

Integrating Sensors: The Sorting Decision Engine

A servo that just sweeps is a metronome. A servo that responds to sensors is a sorting machine. Let’s integrate a TCS34725 color sensor to classify objects by color.

Wiring the TCS34725 Color Sensor

The TCS34725 communicates via I2C. Connect:

  • VIN → Pi 3.3V (pin 1)
  • GND → Pi GND (pin 6)
  • SDA → Pi SDA (pin 3)
  • SCL → Pi SCL (pin 5)

Enable I2C on the Pi with sudo raspi-config, then install the library:

bash pip install adafruit-circuitpython-tcs34725

Color-Based Sorting Logic

Here’s a script that reads the dominant color of an object and commands the micro servo to sort it into one of three bins:

python import RPi.GPIO as GPIO import board import busio import adafruit_tcs34725 import time

Servo setup (same as before)

SERVOPIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(SERVOPIN, GPIO.OUT) pwm = GPIO.PWM(SERVO_PIN, 50) pwm.start(0)

Color sensor setup

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

def setservoangle(angle): duty = 2.5 + (angle / 18.0) pwm.ChangeDutyCycle(duty) time.sleep(0.3) pwm.ChangeDutyCycle(0)

def classify_color(r, g, b): # Simple threshold-based classification if r > 200 and g < 100 and b < 100: return "red" elif g > 200 and r < 100 and b < 100: return "green" elif b > 200 and r < 100 and g < 100: return "blue" else: return "unknown"

try: while True: r, g, b = sensor.colorrgbbytes color = classify_color(r, g, b) print(f"Detected: R={r} G={g} B={b} -> {color}")

    if color == "red":         set_servo_angle(45)   # Bin 1     elif color == "green":         set_servo_angle(90)   # Bin 2     elif color == "blue":         set_servo_angle(135)  # Bin 3     else:         set_servo_angle(0)    # Reject bin      time.sleep(1)  # Wait for next object 

except KeyboardInterrupt: pwm.stop() GPIO.cleanup()

Mechanical Design: Turning Servo Rotation into Sorting Action

The micro servo’s horn (the plastic arm that comes with it) needs to physically redirect objects. Here are three mechanical approaches:

1. The Flap Gate (Simplest)

Attach a rectangular piece of cardboard or 3D-printed plastic to the servo horn. When the servo rotates, the flap swings left or right, blocking one chute and opening another. Objects slide down a ramp and are diverted by the flap’s position.

Pros: Easy to build, low friction.
Cons: Limited to two sorting directions (left/right) unless you use a multi-position flap.

2. The Rotating Turntable

Mount a small disc on the servo shaft with three or four bins around its perimeter. As the servo rotates, the disc aligns a specific bin under the object drop point.

Pros: Can sort into many bins with one servo.
Cons: Requires precise alignment; objects may not drop cleanly.

3. The Push Arm

Use the servo to push a small lever that nudges the object off the conveyor into a side chute. This works well when combined with a second micro servo that controls a gate.

Pros: Gentle on objects, good for fragile items.
Cons: Slower cycle time.

For your first build, I recommend the flap gate with a 3D-printed part. It’s reliable and easy to debug.

Advanced Features: Adding a Conveyor Belt and Second Servo

A static ramp is fine for demos, but a real sorting machine needs a conveyor. You can build a simple belt using a continuous rotation servo (like the FS90R) or a stepper motor. But if you want to stick with micro servos, use a second standard servo as a pusher that shoves objects onto the flap gate.

Synchronizing Two Micro Servos

python import RPi.GPIO as GPIO import time

SERVOGATE = 18 SERVOPUSHER = 23

GPIO.setmode(GPIO.BCM) GPIO.setup([SERVOGATE, SERVOPUSHER], GPIO.OUT)

pwmgate = GPIO.PWM(SERVOGATE, 50) pwmpusher = GPIO.PWM(SERVOPUSHER, 50) pwmgate.start(0) pwmpusher.start(0)

def move_servo(pwm, angle): duty = 2.5 + (angle / 18.0) pwm.ChangeDutyCycle(duty) time.sleep(0.3) pwm.ChangeDutyCycle(0)

Sorting cycle

def sortobject(color): if color == "red": moveservo(pwmgate, 45) # Set gate for red elif color == "green": moveservo(pwmgate, 90) # Set gate for green time.sleep(0.2) moveservo(pwmpusher, 90) # Push object time.sleep(0.5) moveservo(pwm_pusher, 0) # Retract pusher

Troubleshooting Common Micro Servo Issues

Servo Jitters or Vibrates

  • Cause: PWM signal is unstable or duty cycle not reset to 0.
  • Fix: Add pwm.ChangeDutyCycle(0) after each move. Use pigpio library for hardware PWM.

Servo Doesn’t Move to Full Range

  • Cause: Duty cycle range is too narrow for your servo model.
  • Fix: Experiment with dutymin and dutymax. Some servos need 1.0%–13.0% instead of 2.5%–12.5%.

Servo Stops Working After a Few Cycles

  • Cause: Overheating or power brownout.
  • Fix: Use an external 5V supply. Add a 470µF capacitor across the servo power lines to smooth voltage spikes.

Object Detection Is Unreliable

  • Cause: Sensor placement or lighting conditions.
  • Fix: Add an IR break-beam sensor before the color sensor to trigger reading only when an object is present. This prevents false readings from ambient light.

Performance Tweaks: Speeding Up the Sorting Cycle

The bottleneck in most builds is the micro servo’s rotation speed. A standard SG90 takes about 0.12 seconds to rotate 60°. To reach 135°, that’s about 0.27 seconds. Add sensor reading time (0.1–0.3 seconds) and decision logic (negligible), and you’re at roughly 0.5–0.7 seconds per sort.

To improve throughput:

  • Use a faster servo: The MG90S has metal gears and similar speed but better torque.
  • Pre-position the servo: If you know the next object’s color (e.g., from a previous reading), move the servo before the object arrives.
  • Reduce sensor integration time: The TCS34725 allows you to set the integration time via sensor.integration_time. Lower values (e.g., 24ms instead of 154ms) increase speed but reduce accuracy.

python sensor.integration_time = 0.024 # 24ms (fastest) sensor.gain = 16 # Increase gain to compensate for shorter integration

Scaling Up: From Desktop Demo to Industrial Prototype

What you’ve built is a proof-of-concept. But the same micro servo + Raspberry Pi + sensor stack can be scaled:

  • Replace micro servo with a larger servo (e.g., MG996R) for heavier objects.
  • Use multiple micro servos in a gantry system for multi-axis sorting.
  • Add a camera (Pi Camera Module) and run TensorFlow Lite for object recognition instead of color sensing.
  • Log sorting data to a CSV file or upload to a cloud dashboard via WiFi.

The micro servo’s role remains the same: it’s the final actuator that converts a digital decision into a physical action. No matter how complex your sensor array becomes, the servo is the muscle.

Final Thoughts on Your Sorting Machine Build

Building a servo-controlled automated sorting machine with a Raspberry Pi is one of those projects that feels like magic the first time you see it work. A tiny micro servo, no bigger than your thumb, pivots with purpose—guided by code you wrote—and a red M&M falls into the left bin while a green one lands in the right. It’s a small-scale version of the same logic that runs Amazon warehouses.

The micro servo motor is the star here because it bridges the gap between the digital world of Python and the physical world of moving parts. Without it, your sensor data is just numbers on a screen. With it, you have a machine that acts.

So grab an SG90, wire it to your Pi, and start sorting. The only limit is how many bins you can fit on your desk.

Copyright Statement:

Author: Micro Servo Motor

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