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

Micro Servo Motor with Raspberry Pi / Visits:2

Automation is no longer confined to massive industrial assembly lines. With the rise of single-board computers like the Raspberry Pi and affordable yet precise components like micro servo motors, hobbyists and engineers alike can build intelligent sorting systems right on their workbench. In this guide, we’ll walk through the design, assembly, and programming of a compact automated sorting robot that uses a micro servo motor as its primary actuator, combined with a color sensor and an ultrasonic distance sensor to classify and redirect objects.

Whether you’re a maker looking for your next weekend project or an educator seeking a hands-on demonstration of embedded control, this robot delivers a robust platform for learning about sensor integration, servo motion, and real-time decision-making.

Why Micro Servo Motors Are the Heart of This Project

Before diving into the build, let’s address why the micro servo motor is the star of the show. Unlike larger industrial servos, micro servos (typically the SG90 or MG90S models) offer a compelling balance of torque, speed, and size. They can rotate 180 degrees with a simple PWM signal, making them ideal for tasks that require precise angular positioning—like pushing a sorted object into a specific bin.

Key advantages of micro servos in a sorting robot:

  • Low cost: A standard SG90 micro servo costs under $5, making it accessible for prototyping.
  • Ease of control: You only need one GPIO pin per servo (plus power and ground), and libraries like pigpio or RPi.GPIO handle the PWM generation.
  • Sufficient torque for lightweight objects: With a stall torque around 1.8 kg·cm (for the MG90S metal-gear version), a micro servo can easily nudge small blocks, coins, or capsules into different chutes.
  • Compact form factor: At roughly 23 x 12 x 29 mm, it fits neatly into a 3D-printed or laser-cut robot chassis.

The sorting mechanism in our robot uses a single micro servo to rotate a flipper arm. When the sensor identifies an object as belonging to category A, the servo moves to 0 degrees (left bin). For category B, it sweeps to 90 degrees (center bin). For category C, it goes to 180 degrees (right bin). This simple mapping transforms sensor data into physical action.

Project Overview: What This Robot Does

The automated sorting robot performs three core functions:

  1. Detect an object placed on the input ramp using an ultrasonic sensor.
  2. Identify the object’s color using a TCS34725 color sensor.
  3. Redirect the object into one of three bins by activating the micro servo-driven flipper arm.

All logic runs on a Raspberry Pi 4 Model B (though a Pi 3 or even a Pi Zero 2 W will work). The system operates in a continuous loop: wait for an object, read the color, move the servo, then reset.

Hardware Components List

Here is the complete bill of materials for a single-unit build:

| Component | Quantity | Notes | |-----------|----------|-------| | Raspberry Pi 4 (2GB or more) | 1 | Runs Python script and GPIO control | | Micro Servo Motor (SG90 or MG90S) | 1 | For the sorting flipper | | TCS34725 RGB Color Sensor | 1 | I2C interface, detects color | | HC-SR04 Ultrasonic Sensor | 1 | Detects object presence | | 5V Power Supply (2.5A min) | 1 | Powers Pi and servo via breakout | | Breadboard and Jumper Wires | 1 set | For prototyping connections | | 3D-Printed Chassis & Flipper Arm | 1 set | STL files available online | | Small Plastic Bins (3) | 3 | For sorted output | | Test Objects (colored blocks) | 10+ | Red, green, blue, yellow |

Step 1: Circuit Wiring and Power Considerations

The micro servo motor is the most power-hungry component in the system. When it moves under load, it can draw up to 750 mA momentarily. The Raspberry Pi’s 5V rail cannot supply that safely through its GPIO pins, so we use an external 5V supply.

Wiring Diagram (Simplified)

Raspberry Pi GPIO External Components ----------------- -------------------- GPIO 17 (Pin 11) ---> Servo Signal (orange wire) 5V Pin (Pin 2) ---> Servo VCC (red wire) — via external 5V supply GND (Pin 6) ---> Servo GND (brown wire) — common ground with external supply

GPIO 27 (Pin 13) ---> HC-SR04 Trigger GPIO 22 (Pin 15) ---> HC-SR04 Echo

I2C SDA (Pin 3) ---> TCS34725 SDA I2C SCL (Pin 5) ---> TCS34725 SCL 3.3V (Pin 1) ---> TCS34725 VIN GND (Pin 9) ---> TCS34725 GND

Critical note: Never power the servo directly from the Pi’s 5V pin if you are also running USB peripherals. Use a separate 5V 2A supply for the servo, and connect the ground of that supply to the Pi’s ground. This prevents brownouts and keeps the Pi stable.

Power Distribution Setup

  • Connect the external 5V supply’s positive terminal to the servo’s red wire.
  • Connect the external supply’s negative terminal to the Pi’s ground (any GND pin) and to the servo’s brown wire.
  • Use a 470 µF electrolytic capacitor across the servo’s power terminals to smooth transient spikes.

Step 2: Mechanical Assembly – The Flipper Arm

The sorting mechanism is elegantly simple: a micro servo mounted on the chassis rotates a lightweight arm that deflects objects into different chutes.

Designing the Flipper

Using a 3D printer (or even laser-cut acrylic), create an arm that is:

  • Light: Under 10 grams, so the servo doesn’t struggle.
  • Wide enough: About 40 mm long, with a curved face to gently push objects.
  • Attached securely: Use a servo horn (included with the servo) and a small screw.

The servo is mounted vertically on the chassis, with the horn pointing upward. The flipper arm attaches to the horn and rotates in the horizontal plane. When at 0 degrees, the arm blocks the left chute and directs objects to the right. At 180 degrees, it does the opposite. At 90 degrees, objects fall straight into the center bin.

Calibrating the Servo Range

Not all micro servos have identical end stops. Before final assembly, run a calibration script to find the exact PWM values for 0°, 90°, and 180°:

python import RPi.GPIO as GPIO import time

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

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

def set_angle(angle): duty = angle / 18 + 2 pwm.ChangeDutyCycle(duty) time.sleep(0.5) pwm.ChangeDutyCycle(0)

Test angles

setangle(0) time.sleep(1) setangle(90) time.sleep(1) set_angle(180) time.sleep(1)

pwm.stop() GPIO.cleanup()

If the servo overshoots or undershoots, adjust the duty formula. For most SG90 servos, a duty cycle of 2.5% corresponds to 0°, and 12.5% corresponds to 180°.

Step 3: Sensor Integration – Seeing and Sensing

Color Sensor: TCS34725

The TCS34725 is a high-sensitivity RGB color sensor that communicates over I2C. It returns raw red, green, blue, and clear channel values. We use these to classify objects.

Install the library:

bash pip install adafruit-circuitpython-tcs34725

Reading color in Python:

python import board import busio import adafruit_tcs34725

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

def getcolor(): r, g, b, c = sensor.colorraw # Normalize to percentages total = r + g + b if total == 0: return "unknown" rratio = r / total gratio = g / total b_ratio = b / total

if r_ratio > 0.45 and g_ratio < 0.35:     return "red" elif g_ratio > 0.45 and b_ratio < 0.30:     return "green" elif b_ratio > 0.40 and r_ratio < 0.30:     return "blue" else:     return "yellow" 

Tip: Ambient light affects readings. Enclose the sensor in a small hood or use the sensor’s built-in LED (enable via sensor.led = True).

Ultrasonic Sensor: HC-SR04

The HC-SR04 measures distance by sending a 40 kHz pulse and timing the echo. We place it at the top of the input ramp. When an object blocks the beam (distance < 10 cm), the system triggers a sort cycle.

Distance measurement function:

python import RPi.GPIO as GPIO import time

TRIG = 27 ECHO = 22

GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN)

def measure_distance(): GPIO.output(TRIG, False) time.sleep(0.2) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False)

while GPIO.input(ECHO) == 0:     pulse_start = time.time() while GPIO.input(ECHO) == 1:     pulse_end = time.time()  pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 return round(distance, 2) 

Filtering noise: The HC-SR04 is prone to false triggers. Average three readings and ignore outliers beyond 2 meters.

Step 4: The Core Sorting Algorithm

The main loop ties everything together. It waits for an object, reads its color, then commands the micro servo to the appropriate angle.

Pseudocode

while True: distance = measuredistance() if distance < 10: time.sleep(0.5) # Let object settle color = getcolor() if color == "red": servoangle = 0 elif color == "green": servoangle = 90 elif color == "blue": servoangle = 180 else: servoangle = 90 # Default to center

    move_servo(servo_angle)     time.sleep(2)  # Allow object to fall     move_servo(90)  # Return to center time.sleep(0.1) 

Full Python Implementation

Here’s the complete script that runs on the Raspberry Pi:

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

--- GPIO Setup ---

SERVO_PIN = 17 TRIG = 27 ECHO = 22

GPIO.setmode(GPIO.BCM) GPIO.setup(SERVO_PIN, GPIO.OUT) GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN)

--- Servo PWM ---

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

def move_servo(angle): duty = angle / 18 + 2 pwm.ChangeDutyCycle(duty) time.sleep(0.3) pwm.ChangeDutyCycle(0)

--- Ultrasonic ---

def measure_distance(): GPIO.output(TRIG, False) time.sleep(0.2) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO) == 0: start = time.time() while GPIO.input(ECHO) == 1: end = time.time() duration = end - start distance = duration * 17150 return distance

--- Color Sensor ---

i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruittcs34725.TCS34725(i2c) sensor.integrationtime = 0.1 sensor.led = True

def detectcolor(): r, g, b, c = sensor.colorraw total = r + g + b if total == 0: return "unknown" rratio = r / total gratio = g / total bratio = b / total if rratio > 0.45 and gratio < 0.35: return "red" elif gratio > 0.45 and bratio < 0.30: return "green" elif bratio > 0.40 and r_ratio < 0.30: return "blue" else: return "yellow"

--- Main Loop ---

try: while True: dist = measuredistance() if dist < 10: print(f"Object detected at {dist} cm") time.sleep(0.3) color = detectcolor() print(f"Color: {color}") if color == "red": moveservo(0) elif color == "green": moveservo(90) elif color == "blue": moveservo(180) else: moveservo(90) time.sleep(1.5) move_servo(90) # Reset to center time.sleep(0.1) except KeyboardInterrupt: pwm.stop() GPIO.cleanup() sensor.led = False

Step 5: Testing and Tuning the System

Common Issues and Fixes

Servo jitter or failure to move:
- Check the external power supply. A 5V 2A supply is recommended.
- Verify the ground connection between the external supply and the Pi.
- Reduce the load on the flipper arm—it should be as light as possible.

Color misclassification:
- Calibrate the color thresholds for your specific lighting. Use a white balance routine that reads a white object and adjusts ratios.
- Add a delay between detecting the object and reading the sensor to allow the object to settle under the sensor.

Ultrasonic false triggers:
- Use a timeout in the echo reading loop (e.g., while GPIO.input(ECHO) == 1 and time.time() - start < 0.1).
- Place the sensor at least 15 cm above the ramp to avoid detecting the ramp itself.

Performance Optimization

For higher throughput, consider these enhancements:

  • Use threading: Run the ultrasonic polling in a separate thread so the servo movement doesn’t block sensor reads.
  • Reduce servo settling time: The time.sleep(0.3) after each move can be lowered to 0.1 seconds if the servo is fast enough.
  • Implement a conveyor belt: Instead of a gravity ramp, use a small DC motor with a belt to feed objects continuously.

Expanding the Project: Advanced Features

Once the basic sorting robot is working, you can add capabilities that push the micro servo to its limits.

Multi-Servo Sorting with a Turntable

Instead of a single flipper, use two micro servos to create a 2-axis sorting turntable. Servo 1 rotates the turntable (0–180 degrees) to select the row, and Servo 2 tilts the platform to drop the object into a bin. This allows sorting into a 3×3 grid (9 categories).

Wiring two servos:

  • Servo 1 Signal → GPIO 17
  • Servo 2 Signal → GPIO 18
  • Both share the same external 5V and ground.

Code modification:

python pwm1 = GPIO.PWM(17, 50) pwm2 = GPIO.PWM(18, 50)

Move both simultaneously

pwm1.ChangeDutyCycle(duty1) pwm2.ChangeDutyCycle(duty2) time.sleep(0.5) pwm1.ChangeDutyCycle(0) pwm2.ChangeDutyCycle(0)

Adding a Camera for Object Recognition

Replace the color sensor with a Raspberry Pi Camera Module and run TensorFlow Lite to classify objects (e.g., screws vs. washers vs. nuts). The micro servo still handles the physical sorting, but the decision logic becomes much smarter.

Hardware change:
- Remove the TCS34725.
- Attach the camera module to the CSI port.
- Use a Python script with tflite_runtime to run a custom model.

Why the micro servo remains essential: Even with advanced vision, you still need a low-cost, precise actuator to physically separate objects. The micro servo’s simplicity and reliability make it the perfect partner for AI-driven sorting.

IoT-Enabled Remote Monitoring

Add an ESP8266 or a Wi-Fi dongle to the Raspberry Pi, and stream sort counts to a cloud dashboard. When the micro servo moves, increment a counter and push it via MQTT. This turns your sorting robot into a data-generating IoT device.

Sample MQTT publish:

python import paho.mqtt.client as mqtt

client = mqtt.Client() client.connect("broker.emqx.io", 1883, 60)

def moveservo(angle): # ... servo code ... client.publish("sortingbot/counts", f"{color}:1")

Real-World Applications and Learning Outcomes

Building this robot teaches you more than just wiring and coding. You’ll gain practical experience with:

  • PWM signal generation for precise motor control.
  • Sensor fusion combining distance and color data.
  • Real-time decision-making under timing constraints.
  • Power management in embedded systems.

In an educational setting, students can experiment with different servo speeds, sensor placements, and sorting algorithms. They learn that a $5 micro servo, when paired with a $35 Raspberry Pi, can replicate the core function of industrial sorting systems that cost thousands.

A Note on Micro Servo Longevity

Micro servos are designed for intermittent duty. Continuous operation under load will wear out the plastic gears (in SG90) or even the metal gears (in MG90S) over time. For a sorting robot that runs for hours, consider these tips:

  • Use metal-gear servos (MG90S, MG996R) if possible.
  • Mount the servo with rubber grommets to absorb vibration.
  • Limit the servo’s angular range to 0–180 degrees—don’t force it past mechanical stops.
  • In software, always set the duty cycle to 0 after a move to reduce holding current.

Final Thoughts on the Build

The servo-powered sorting robot is a perfect example of how a humble micro servo motor can be the bridge between digital logic and physical action. It’s not just about moving an arm; it’s about creating a system that sees, decides, and acts—all within a few hundred milliseconds.

As you refine your robot, you’ll discover that the micro servo’s limitations (torque, speed, range) force you to think creatively about mechanical design and software efficiency. That constraint is exactly what makes this project educational and satisfying.

Whether you sort M&M’s by color, separate resistors by value, or teach a classroom about automation, the micro servo remains the unsung hero—small in size, big in impact, and endlessly adaptable.

Copyright Statement:

Author: Micro Servo Motor

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