AI Sorting Machine: A DIY Conveyor Belt That Sees and Sorts Objects with a Camera

AI Sorting Machine: A DIY Conveyor Belt That Sees and Sorts Objects with a Camera | Kids Robotics
Robotics + AI Project · Ages 12+

Can a machine see the difference between things? Build one that sorts objects by how they look

Put a mixed pile of small objects on a conveyor belt, one at a time. A camera looks at each one, an AI model that you train yourself decides what it is, and servo arms push it into the right bin. Anything it is not sure about goes to the Other bin.

Try it: watch one object get sorted

camera arm A arm B Bin A: 0 Bin B: 0 Other: 0

Press the button to put an object on the belt.

What you're building

A small factory line with eyes, a brain and hands.

The AI Sorting Machine is a short conveyor belt with a camera on a little gantry over it. When an object reaches the camera, the belt stops and a Raspberry Pi takes a few photos. A trained image model gives each photo a label and a confidence score. If the Pi is sure, it tells an Arduino which bin the object belongs in. The Arduino runs the belt the right distance and fires the right servo arm to push the object off the side. Unknown objects ride all the way to the end and drop into the Other bin.

Eyes: the camera

A USB webcam takes pictures of each object under steady light.

Brain: the AI model

An image model that you train guesses what each object is and how sure it is.

Hands: servo arms

Servo-driven paddles push each object into its bin as it passes.

  1. ArriveThe belt carries an object to the camera and stops.
  2. LookThe camera takes several photos.
  3. DecideThe AI picks a label, or says "not sure".
  4. SortThe belt moves it to the right arm, which pushes it into its bin.

How does a machine learn to see?

It does not understand objects like you do. It learns patterns from examples.

  • You show it examples. In Teachable Machine you take about 100 photos of each kind of object, such as red blocks, green blocks and toy cars.
  • It finds patterns. The model learns which colours, shapes and edges go with each label.
  • It guesses with a score. For every new photo it gives a confidence for each label. The machine only trusts a guess when it is at least 80% sure.
  • It needs an "empty belt" class. That way it can tell when there is nothing to sort instead of guessing.

Machines can be fooled. A shadow, a different background or an object it has never seen can lead to a wrong guess. Spotting why, then fixing it with better photos and better light, is real AI engineering.

Materials list

You need a small computer for the AI and a microcontroller for the motors.

Electronics

  • 1x Raspberry Pi 4 (2GB or more) with a 5V 3A power supply and microSD card with Raspberry Pi OS
  • 1x USB webcam
  • 1x USB LED light strip or small lamp (steady lighting)
  • 1x Arduino Uno and USB cable
  • 1x IR obstacle sensor module
  • 1x L298N motor driver
  • 1x TT gear motor (3 to 6V)
  • 1x battery holder for 4 AA batteries (motor power)
  • 2x SG90 or MG90S servo motors
  • 1x 5V 2A power supply for the servos
  • 1x buzzer, 3 LEDs and 3x 220-ohm resistors
  • Breadboard and jumper wires

Build supplies

  • Foam board, cardboard or wood for the frame
  • 2 rollers (wooden dowels or cardboard tubes)
  • A loop of dark, matte fabric or flat elastic for the belt
  • Craft sticks or 3D-printed paddles for the arms
  • 3 small boxes or cups for bins
  • Black card for a camera hood
  • Small objects to sort (blocks, toy cars, anything that is clearly different)
  • Hot glue gun, tape and craft knife (adult use only)

Circuit diagram

The Raspberry Pi sees and decides. The Arduino drives everything that moves.

USB WEBCAM Looks at the belt USB RASPBERRY PI 4 Runs the AI model Python program PI POWER 5V 3A supply ARDUINO UNO Belt, servos, sensor Powered over USB USB cable power + messages IR OBSTACLE SENSOR Sees an object arrive VCC 5V, GND, OUT to D2 BATTERY PACK 4 AA, about 6V L298N MOTOR DRIVER ENA to D5 (jumper removed) IN1 to D7, IN2 to D8 GND joined to Arduino GND BELT MOTOR TT gear motor SERVO ARM A Signal to D9 SERVO ARM B Signal to D10 BUZZER + 3 LEDs Buzzer D11 LEDs D3, D4, D6 (220 ohm each) SERVO POWER 5V 2A, feeds both servos

Tip: The servos and the belt motor have their own power supplies. Join every GND together (Arduino, L298N, servo supply) so the signals have a common reference.

Wiring reference table

ComponentComponent PinConnects To
USB webcamUSBRaspberry Pi USB port
Arduino UnoUSBRaspberry Pi USB port (power and messages)
IR obstacle sensorVCC / GND / OUTArduino 5V / GND / D2
L298N motor driverENAArduino D5 (take off the ENA jumper)
L298N motor driverIN1 / IN2Arduino D7 / D8
L298N motor driver12V terminal / GNDBattery pack + / battery pack − (and Arduino GND)
L298N motor driverOUT1 / OUT2Belt motor
Servo A (diverter)SignalArduino D9
Servo B (diverter)SignalArduino D10
Servos A and BRed / brown wires5V 2A servo supply + / − (supply − joined to Arduino GND)
Buzzer+ / −Arduino D11 / GND
LEDs (A, B, Other)Anode via 220-ohm resistorArduino D3, D4, D6 (cathodes to GND)

Step-by-step build instructions

Build the belt first, then the eyes, then teach the brain. Test each part before moving on.

  1. Build the conveyor frame and belt

    Make a long, narrow frame with a roller at each end. Loop the dark fabric belt round both rollers and adjust until it is snug but still turns freely. A matte dark belt works best for both the camera and the IR sensor.

  2. Add the motor and test the belt

    Connect the gear motor to one roller (directly on the shaft or with a rubber-band drive). Wire it to the L298N and battery pack, upload the sketch below to the Arduino, and check the belt runs smoothly.

  3. Mount the IR sensor and the camera

    Fix the IR sensor at the side of the belt, aimed across it at object height. Build a small gantry over the belt just after the sensor and mount the webcam pointing straight down. Add a black card hood and the USB light so the lighting is the same every time.

  4. Build the servo diverters and bins

    Fix a servo and a paddle arm at each of two places along one side of the belt. At rest each paddle sits out of the way, and when it swings it sweeps an object off the other side. Place a bin beside each arm, plus a third bin at the end of the belt.

  5. Set up the Raspberry Pi

    Install Raspberry Pi OS, plug in the webcam, and install the software from the setup box below. Check the camera works by opening a short test script or the camera preview.

  6. Teach the AI in Teachable Machine

    On a laptop, open Teachable Machine and start a new Image Project. Plug the mounted webcam into the laptop so you take photos exactly as the machine will see them. Make a class for each object (use names like red_block with no spaces), plus one called empty_belt. Take about 100 photos of each, with the object in different spots and angles, then train the model.

  7. Export the model to the Pi

    Choose Export Model, pick the TensorFlow Lite tab, and download the floating-point version. Unzip it and copy model_unquant.tflite and labels.txt into the same folder as the Python program on the Pi.

  8. Upload the Arduino sketch

    Connect the Arduino to your laptop, upload the sketch, then plug it into the Pi's USB port. The belt should start moving.

  9. Run the Python program

    On the Pi, edit the settings at the top (your label names and which bin each goes to), then run python3 sorter.py. Put an object at the start of the belt and watch the Pi print what it sees.

  10. Calibrate the distances and test

    Adjust the three travel times in the Arduino sketch until each object stops right in front of its arm. Then test with a mixed pile, one object at a time. For any mistakes, take more photos of that object and train again.

The code

Two programs work together. The Arduino moves things and asks "what is it?". The Raspberry Pi answers.

1. Raspberry Pi setup commands

sudo apt update
sudo apt install -y python3-opencv python3-numpy python3-serial
pip3 install tflite-runtime --break-system-packages

# If pip cannot find tflite-runtime for your Python version, use this instead:
pip3 install ai-edge-litert --break-system-packages

2. Arduino sketch (belt, sensor and servo arms)

#include <Servo.h>

// ---- Pins ----
#define IR_PIN       2    // object sensor (LOW = object seen)
#define ENA_PIN      5    // belt speed (PWM)
#define IN1_PIN      7    // belt direction
#define IN2_PIN      8
#define ARM_A_PIN    9    // diverter for Bin A
#define ARM_B_PIN    10   // diverter for Bin B
#define BUZZER_PIN   11
#define LED_A_PIN    3
#define LED_B_PIN    4
#define LED_X_PIN    6

// ---- Settings to calibrate ----
const int BELT_SPEED = 150;                      // 0 to 255
const unsigned long STOP_DELAY_MS    = 100;      // coast time so the object stops under the camera
const unsigned long TRAVEL_A_MS      = 1500;     // camera to arm A
const unsigned long TRAVEL_B_MS      = 2800;     // camera to arm B
const unsigned long TRAVEL_END_MS    = 4200;     // camera to the end of the belt
const unsigned long REPLY_TIMEOUT_MS = 6000;     // how long to wait for the Pi
const int ARM_REST = 20;                         // paddle out of the way
const int ARM_PUSH = 100;                        // paddle sweeps the object off

Servo armA;
Servo armB;

void setup() {
  pinMode(IR_PIN, INPUT);
  pinMode(ENA_PIN, OUTPUT);
  pinMode(IN1_PIN, OUTPUT);
  pinMode(IN2_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_A_PIN, OUTPUT);
  pinMode(LED_B_PIN, OUTPUT);
  pinMode(LED_X_PIN, OUTPUT);

  armA.attach(ARM_A_PIN);
  armB.attach(ARM_B_PIN);
  armA.write(ARM_REST);
  armB.write(ARM_REST);

  beltStop();
  Serial.begin(9600);
  delay(500);
  Serial.println("READY");
}

void loop() {
  beltRun();
  if (digitalRead(IR_PIN) == LOW) {          // an object reached the camera
    delay(STOP_DELAY_MS);
    beltStop();
    delay(500);                              // let it settle before the photo
    while (Serial.available()) Serial.read();  // clear old messages
    Serial.println("SEE");                   // ask the Pi: what is it?
    char choice = waitForAnswer();
    sortObject(choice);
  }
}

char waitForAnswer() {
  unsigned long start = millis();
  while (millis() - start < REPLY_TIMEOUT_MS) {
    if (Serial.available()) {
      char c = Serial.read();
      if (c == 'A' || c == 'B' || c == 'X' || c == 'N') return c;
    }
  }
  return 'X';                                // no answer: send it to the Other bin
}

void sortObject(char choice) {
  if (choice == 'N') {                       // nothing there, carry on
    runBelt(800);
    return;
  }

  showChoice(choice);
  if (choice == 'A') {
    runBelt(TRAVEL_A_MS);
    pushWith(armA);
  } else if (choice == 'B') {
    runBelt(TRAVEL_B_MS);
    pushWith(armB);
  } else {
    runBelt(TRAVEL_END_MS);                  // falls off the end into the Other bin
  }

  digitalWrite(LED_A_PIN, LOW);
  digitalWrite(LED_B_PIN, LOW);
  digitalWrite(LED_X_PIN, LOW);
  Serial.println("DONE");
}

void showChoice(char choice) {
  if (choice == 'A') {
    digitalWrite(LED_A_PIN, HIGH);
    tone(BUZZER_PIN, 1000, 200);
  } else if (choice == 'B') {
    digitalWrite(LED_B_PIN, HIGH);
    tone(BUZZER_PIN, 1500, 200);
  } else {
    digitalWrite(LED_X_PIN, HIGH);
    tone(BUZZER_PIN, 500, 200);
  }
}

void pushWith(Servo &arm) {
  arm.write(ARM_PUSH);
  delay(500);
  arm.write(ARM_REST);
  delay(400);
}

void beltRun() {
  digitalWrite(IN1_PIN, HIGH);
  digitalWrite(IN2_PIN, LOW);
  analogWrite(ENA_PIN, BELT_SPEED);
}

void beltStop() {
  analogWrite(ENA_PIN, 0);
  digitalWrite(IN1_PIN, LOW);
  digitalWrite(IN2_PIN, LOW);
}

void runBelt(unsigned long ms) {
  beltRun();
  delay(ms);
  beltStop();
}

3. Raspberry Pi program: sorter.py (camera and AI)

#!/usr/bin/env python3
import time
from collections import Counter

import cv2
import numpy as np
import serial

try:
    from tflite_runtime.interpreter import Interpreter
except ImportError:
    from ai_edge_litert.interpreter import Interpreter

# ---- Settings you can change ----
MODEL_PATH = "model_unquant.tflite"
LABELS_PATH = "labels.txt"
SERIAL_PORT = "/dev/ttyACM0"       # clone Arduinos may show up as /dev/ttyUSB0
CONFIDENCE_MIN = 0.80              # only trust guesses at least 80% sure
EMPTY_LABEL = "empty_belt"
# Which bin each label goes to. Anything not listed goes to the Other bin (X).
BIN_FOR_LABEL = {
    "red_block": "A",
    "green_block": "B",
}

def load_labels(path):
    labels = []
    with open(path) as f:
        for line in f:
            parts = line.strip().split(" ", 1)
            if len(parts) == 2 and parts[0].isdigit():
                labels.append(parts[1])
            elif line.strip():
                labels.append(line.strip())
    return labels

labels = load_labels(LABELS_PATH)
interpreter = Interpreter(model_path=MODEL_PATH)
interpreter.allocate_tensors()
input_info = interpreter.get_input_details()[0]
output_info = interpreter.get_output_details()[0]
height, width = input_info["shape"][1], input_info["shape"][2]

def classify(frame):
    # Crop the middle square, shrink it, and scale pixels the way Teachable Machine does
    h, w = frame.shape[:2]
    side = min(h, w)
    top, left = (h - side) // 2, (w - side) // 2
    square = frame[top:top + side, left:left + side]
    # If the Pi seems less accurate than the browser, try: square = cv2.flip(square, 1)
    rgb = cv2.cvtColor(cv2.resize(square, (width, height)), cv2.COLOR_BGR2RGB)
    data = np.expand_dims(rgb.astype(np.float32) / 127.5 - 1.0, axis=0)
    interpreter.set_tensor(input_info["index"], data)
    interpreter.invoke()
    scores = interpreter.get_tensor(output_info["index"])[0]
    best = int(np.argmax(scores))
    return labels[best], float(scores[best])

def look_and_decide(cap):
    for _ in range(5):             # throw away old frames waiting in the camera
        cap.read()
    guesses = []
    for _ in range(5):             # take 5 photos and let them vote
        ok, frame = cap.read()
        if ok:
            label, conf = classify(frame)
            if conf >= CONFIDENCE_MIN:
                guesses.append((label, conf))
        time.sleep(0.05)
    if not guesses:
        return "unsure", 0.0
    label, votes = Counter(g[0] for g in guesses).most_common(1)[0]
    if votes < 3:                  # at least 3 of 5 photos must agree
        return "unsure", 0.0
    confs = [g[1] for g in guesses if g[0] == label]
    return label, sum(confs) / len(confs)

def main():
    ser = serial.Serial(SERIAL_PORT, 9600, timeout=1)
    time.sleep(2)                  # the Arduino restarts when the port opens
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        raise SystemExit("Camera not found. Check the USB cable.")

    print("Sorting machine ready. Waiting for objects...")
    tally = Counter()
    while True:
        line = ser.readline().decode(errors="ignore").strip()
        if line != "SEE":
            continue
        label, conf = look_and_decide(cap)
        if label == EMPTY_LABEL:
            code = "N"             # nothing there
        else:
            code = BIN_FOR_LABEL.get(label, "X")
        ser.write(code.encode())
        tally[code] += 1
        print(f"Saw: {label} ({conf:.0%}) -> bin {code}   totals: {dict(tally)}")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Stopped.")

Beginner tip

Most sorting mistakes come from light, not from the AI. Keep the lamp and hood fixed, use a plain belt, and take your training photos with the same camera in the same place. If the machine keeps missing one object, add 50 more photos of it in different positions and train again.

Safety notes for young makers

Keep fingers, hair and loose sleeves away from the belt and rollers, and from the swinging servo arms, which can pinch. Unplug the power before you adjust anything that moves. Ask an adult to help with cutting, the mains power supplies and the battery pack, and never leave the machine running unattended. Keep small objects away from young children.

Why this project works so well for learning

This one build covers a lot of real engineering. Training an image model shows how data decides what a machine can learn. Confidence scores and a vote across five photos show that AI gives probabilities, not certainties. Splitting the job between a Raspberry Pi and an Arduino shows how real systems combine a "thinking" computer with a "doing" controller, talking through a simple message protocol. And calibrating belt timings is a hands-on lesson in tuning a physical system.

Frequently asked questions

What age and skill level is this project for?

It is an intermediate project for ages 12 and up, with an adult helping with the power supplies, cutting and wiring. Younger makers can do the AI training part, which happens in a web browser.

Do I need to know how to program AI?

No. You teach the AI by showing it photos of your objects in Google's Teachable Machine, and the Python and Arduino code is provided. You only change a few settings, such as the names of your objects.

Why use both a Raspberry Pi and an Arduino?

The Raspberry Pi is a small computer that can run the image model. The Arduino is better at steady motor, servo and sensor timing. They talk to each other over a USB cable.

Can I use a laptop instead of a Raspberry Pi?

Yes. The same Python script can run on a laptop once the packages are installed and the serial port name is changed to match the Arduino.

Why does my machine make mistakes?

The usual causes are changing light, a busy background, or too few training photos. Use steady lighting and a plain belt, take training photos with the same camera in the same position, add photos of each object from different angles, and keep an empty belt class.

Can I sort more kinds of objects?

Yes. Add another servo diverter and travel time for each extra bin, train a new class for each new object, and add it to the BIN_FOR_LABEL list in the Python code.

Built for curious young engineers. Always build and power on electronics with adult supervision.

Comments

Product Cards
Buddy Bot eBook
⭐ New 2026 Release
Build Your
Own Robot!
3D design, wiring &
Arduino coding.
★★★★★ Young inventors love it!
🖨️
3D Print
All parts
⚡
Wire it
Circuit guide
💻
Code it
Arduino IDE
🤖
Watch it
Walk & react
📋 Your Details
Enter your name
Valid 10-digit no.
Enter a valid email
Special Website Offer
₹499 ₹300
🌍 International: $5 USD
One-time · Instant digital delivery
🔒 Secured by Razorpay · Your data is safe
📄 Download Free Sample Copy
🔒 Secured by Razorpay · Your data is safe
🍓
Raspberry Pi Pico Mastery
21 Projects
⚡ Launch Price — 80% OFF
Learn Pico
Build 21 Projects!
MicroPython · Wokwi
IoT · Certificate
★★★★★ Perfect for beginners!
🖥️
Wokwi
No hardware
🐍
MicroPy
From zero
🔨
21 Projects
IoT + sensors
📄
Certificate
Verified cert
📋 Your Details
Enter your name
Valid 10-digit no.
Enter a valid email
Special Launch Offer
₹999 ₹200 80% OFF
🌍 International: $5 USD
One-time · Lifetime access · No subscription
🔒 Secured by Razorpay · UPI · Cards · NetBanking
🎉

You're in!

Payment successful! Your Buddy Bot eBook is ready. Time to build!

📖 Access Your eBook Now
🎉

Enrolled!

Payment successful! Lifetime access to all 21 Pico Projects is yours!

🍓 Go to My Course