How to Build an AI Waste Sorting Machine Using Arduino and ESP32: Complete DIY Guide (EcoSort AI)


Introduction

Waste segregation is one of the biggest challenges facing modern waste management systems. Plastic bottles, paper, cardboard, and metal cans are often mixed together, making recycling more difficult and expensive.

An AI-powered waste sorting machine offers a practical way to address this problem. By combining computer vision, artificial intelligence, sensors, Arduino, and ESP32 technology, it is possible to build a system that identifies different waste materials and automatically directs them into separate collection bins.

In this tutorial, we will build EcoSort AI, a prototype that identifies four categories of waste:

  • Plastic
  • Paper
  • Cardboard
  • Metal

The project is suitable for STEM exhibitions, school innovation competitions, environmental science projects, engineering demonstrations, and advanced Arduino enthusiasts.

1. What Is EcoSort AI?

EcoSort AI is an automated waste segregation prototype that uses a camera and an artificial intelligence model to identify waste materials.

The camera captures an image of an object placed on the sorting platform. An AI model analyzes the image and predicts its category. The classification result is then sent to an Arduino controller, which activates a servo-operated sorting mechanism.

The machine directs the identified waste into the appropriate collection compartment.

Featured project image

EcoSort AI waste sorting machine concept

Image caption: EcoSort AI concept illustration showing an automated waste segregation prototype. This is a design illustration, not a photograph of a completed physical machine.

2. How Does the AI Waste Sorting Machine Work?

The system operates through five main stages.

  1. Waste detection: An infrared sensor detects an object placed on the sorting platform.
  2. Image capture: The ESP32-CAM captures an image of the waste.
  3. AI classification: A trained machine learning model identifies the material.
  4. Controller communication: The classification result is sent to the Arduino Uno.
  5. Automatic sorting: The Arduino activates the appropriate servo motor to direct the object into a collection bin.

For the first prototype, a laptop or compatible edge computer can run the AI classification model. The ESP32-CAM captures the image, while the Arduino handles the mechanical sorting.

This approach is practical for beginners because it separates image recognition from motor control.

Working principle diagram

EcoSort AI working principle

Image caption: The five-stage operating principle of the AI-powered waste segregation machine.

3. Materials and Components Required

The project uses electronic components, mechanical materials, and programming tools.

Bill of Materials (BOM)

ComponentQuantityPurpose
Arduino Uno R31Controls the sorting mechanism
ESP32-CAM1Captures waste images
ESP32 DevKit1 optionalAdditional processing or communication
IR obstacle sensor1Detects waste objects
Servo motors4Operate the sorting gates
L298N motor driver1Controls conveyor motor
12V geared DC motor1Drives conveyor belt
16×2 I2C LCD1Displays sorting information
LEDs4Indicate sorting categories
Buzzer1Provides an alert
Conveyor belt materials1 setTransports waste
Collection bins4Store sorted materials
Jumper wiresSeveralElectrical connections
Regulated power suppliesAs requiredPower electronic components

Components illustration

EcoSort AI components

Image caption: Main electronic and mechanical components needed to construct the EcoSort AI prototype.

Additional tools

You may also need:

  • Soldering iron and solder wire
  • Screwdrivers
  • Wire stripper
  • Hot glue gun
  • Measuring ruler
  • Drill
  • Laptop or desktop computer
  • Arduino IDE
  • AI model development environment

4. Estimated Project Cost in Kenya

The following is an illustrative budget for planning purposes. Actual prices will depend on the supplier, component quality, and availability.

ComponentEstimated Cost (KES)
Arduino Uno900
ESP32 DevKit900
ESP32-CAM1,200
Sensors1,400
Servo motors1,200
Motor driver450
LCD, LEDs and buzzer800
Conveyor and frame3,500
Wires and connectors1,100
Total11,450

The estimated budget is approximately KSh 11,450, excluding some tools, optional computer equipment, and possible delivery costs.

5. System Architecture

EcoSort AI uses different electronic units to perform specific functions.

The ESP32-CAM captures images of waste materials. The AI classification program runs on a compatible computer or edge device. The computer communicates the predicted category to the Arduino Uno through a USB serial connection.

The Arduino then activates the corresponding servo motor.

System block diagram

EcoSort AI system block diagram

Image caption: System architecture showing communication between the camera, AI classifier, Arduino controller, sensors, and sorting mechanism.

Main system units

1. Image acquisition unit

The ESP32-CAM captures images of waste objects. Good lighting and a consistent camera position improve image quality.

2. Artificial intelligence unit

The AI model analyzes the captured image and predicts whether the object belongs to the plastic, paper, cardboard, or metal category.

3. Control unit

The Arduino Uno receives the classification result and controls the sorting mechanism.

4. Mechanical sorting unit

Servo motors operate gates or directing flaps that guide objects into their respective bins.

5. Display unit

The LCD displays the detected waste category and sorting status.

6. Circuit Connections and Pin Configuration

Connect the electronic components according to the following pin arrangement.

Arduino Uno connections

ComponentArduino Pin
IR sensor OUTD2
Plastic servo signalD3
Paper servo signalD4
Cardboard servo signalD5
Metal servo signalD9
L298N IN1D7
L298N IN2D8
L298N ENAD6
LCD SDAA4
LCD SCLA5

The ESP32-CAM connects to the AI computer for image capture and classification. The AI computer sends the resulting category to the Arduino through USB serial communication.

Circuit connection diagram

EcoSort AI circuit connection plan

Image caption: Reference connection plan for the Arduino-controlled waste sorting mechanism.

Important power supply precautions

  • Do not power four servo motors directly from the Arduino Uno 5V pin.
  • Use a regulated external 5–6V supply with sufficient current capacity for the servos.
  • Connect the external servo supply ground to the Arduino ground.
  • Power the conveyor motor using a suitable separate supply.
  • Check the L298N motor driver’s current and thermal limits.
  • ESP32 devices use 3.3V logic. Use suitable level shifting where an Arduino 5V output connects to an ESP32 input.
  • Check the polarity of every connection before switching on the system.

Incorrect power connections can damage the microcontrollers, sensors, and motors.

7. Mechanical Construction of the Machine

The mechanical structure determines how effectively the machine transports and separates waste.

Step 1: Construct the frame

Use plywood, acrylic sheets, aluminum profiles, or other suitable materials to construct a stable frame.

The frame should accommodate:

  • Camera mounting position
  • Conveyor belt
  • Sorting platform
  • Servo-operated gates
  • Four waste collection compartments

Step 2: Install the conveyor belt

Attach the conveyor belt to the frame and connect it to the geared DC motor.

Ensure that the belt moves smoothly without slipping.

Step 3: Mount the ESP32-CAM

Position the camera above the inspection point. The camera should capture clear images of objects passing through the sorting area.

Step 4: Install the servo gates

Attach the servo motors to the sorting mechanism. Each servo should control a gate or flap directing waste into a particular bin.

Step 5: Install the collection bins

Label the four collection compartments:

  • PLASTIC
  • PAPER
  • CARDBOARD
  • METAL

Construction layout image

EcoSort AI construction layout

Image caption: Suggested physical arrangement of the conveyor, camera, sorting gates, and collection compartments.

8. Artificial Intelligence Model Development

The AI model is responsible for identifying the type of waste.

A beginner-friendly approach is to use a supervised image classification model.

Step 1: Collect image datasets

Collect images of the four waste categories.

CategoryExample Training Images
PlasticWater bottles, containers and plastic packaging
PaperNewspaper, office paper and magazines
CardboardBoxes and carton packaging
MetalAluminum cans and metal containers

Use a variety of images with different backgrounds, lighting conditions, shapes, and orientations.

Step 2: Label the images

Organize the images into four clearly named categories:

  • plastic
  • paper
  • cardboard
  • metal

Step 3: Train the classification model

Use an image classification platform or machine learning framework to train the model.

Suitable options include:

  • TensorFlow
  • TensorFlow Lite
  • Edge Impulse
  • Teachable Machine

For the initial prototype, the model can run on a laptop. The ESP32-CAM captures the image, and the laptop processes it.

Step 4: Test the model

Test the model using images that were not included in the training dataset.

Record the predictions and identify categories that are frequently confused.

Important: The AI model must be trained and tested using actual images. The Arduino code below does not perform image recognition; it controls the sorting mechanism after receiving a classification result.

9. Arduino Programming Code

The following example controls four servo motors using category labels received through USB serial communication.

Install the Servo library through the Arduino IDE before uploading the code.

#include <Servo.h>

Servo plasticServo;
Servo paperServo;
Servo cardboardServo;
Servo metalServo;

const int plasticPin = 3;
const int paperPin = 4;
const int cardboardPin = 5;
const int metalPin = 9;

const int irSensor = 2;

String receivedData = "";

void setup() {
  Serial.begin(9600);

  pinMode(irSensor, INPUT);

  plasticServo.attach(plasticPin);
  paperServo.attach(paperPin);
  cardboardServo.attach(cardboardPin);
  metalServo.attach(metalPin);

  plasticServo.write(90);
  paperServo.write(90);
  cardboardServo.write(90);
  metalServo.write(90);

  Serial.println("EcoSort AI Ready");
}

void resetGates() {
  plasticServo.write(90);
  paperServo.write(90);
  cardboardServo.write(90);
  metalServo.write(90);
}

void sortWaste(String category) {

  resetGates();
  delay(300);

  if (category == "PLASTIC") {
    plasticServo.write(30);
  }

  else if (category == "PAPER") {
    paperServo.write(30);
  }

  else if (category == "CARDBOARD") {
    cardboardServo.write(30);
  }

  else if (category == "METAL") {
    metalServo.write(30);
  }

  else {
    Serial.println("Unknown category");
    return;
  }

  Serial.print("Sorting: ");
  Serial.println(category);

  delay(1000);

  resetGates();
}

void loop() {

  if (Serial.available()) {

    receivedData = Serial.readStringUntil('\n');

    receivedData.trim();
    receivedData.toUpperCase();

    sortWaste(receivedData);
  }
}

How the code works

  1. The Arduino initializes the four servo motors.
  2. It waits for a classification label from the AI computer.
  3. When it receives PLASTIC, it activates the plastic servo.
  4. When it receives PAPER, it activates the paper servo.
  5. When it receives CARDBOARD, it activates the cardboard servo.
  6. When it receives METAL, it activates the metal servo.
  7. The servo returns to its default position after sorting.

The 30-degree and 90-degree positions are starting examples. Adjust them according to the mechanical arrangement of your gates.

10. Operating Flowchart

The operating sequence can be summarized as follows:

  1. Start the system.
  2. Initialize the camera, sensors, Arduino, and display.
  3. Detect waste at the inspection point.
  4. Capture an image.
  5. Send the image to the AI classification program.
  6. Identify the waste category.
  7. Send the category label to Arduino.
  8. Activate the corresponding sorting gate.
  9. Direct the waste into the correct bin.
  10. Reset the gate and wait for another object.

Operating flowchart image

EcoSort AI operating flowchart

Image caption: Flowchart showing the decision-making process used by the automated waste sorting machine.

11. Testing and Evaluation

After completing the construction, test the machine using different waste samples.

The evaluation should determine whether the system correctly identifies and sorts materials.

Suggested testing procedure

  1. Place a plastic bottle on the conveyor.
  2. Allow the camera to capture its image.
  3. Record the AI prediction.
  4. Observe whether the correct gate activates.
  5. Repeat the process using paper, cardboard, and metal.
  6. Record successful and unsuccessful sorting attempts.

Suggested performance indicators

ParameterMeasurement
Classification accuracyPercentage of correct AI predictions
Sorting success ratePercentage of objects placed in correct bins
Response timeTime taken from detection to sorting
False classificationIncorrect category predictions
ThroughputNumber of objects sorted per minute

Classification accuracy formula

\[
\text{Accuracy} = \frac{\text{Correct Predictions}}{\text{Total Predictions}} \times 100
\]

Sorting success rate formula

\[
\text{Sorting Success Rate} =
\frac{\text{Correctly Sorted Objects}}{\text{Total Objects Tested}} \times 100
\]

Testing setup image

EcoSort AI testing setup

Image caption: Suggested testing arrangement for evaluating waste identification and automatic sorting performance.

Research note: Do not report assumed accuracy figures as experimental findings. Collect actual measurements during testing and use them in your final project report.

12. How to Fix Common Arduino and ESP32 Upload Errors

Problem 1: ESP32-CAM fails to upload code

Possible causes:

  • Incorrect board selection.
  • Incorrect COM port.
  • Insufficient power.
  • Incorrect programming connections.

Solutions:

  • Select the correct ESP32 board.
  • Check the USB-to-serial adapter connections.
  • Ensure the programming configuration is correct.
  • Use an adequate power supply.

Problem 2: Servo motors vibrate or fail to move

Possible causes:

  • Insufficient current.
  • Incorrect wiring.
  • Poor ground connection.

Solutions:

  • Use an external regulated servo supply.
  • Connect the grounds together.
  • Check the signal wires.
  • Avoid powering multiple servos directly from the Arduino.

Problem 3: LCD displays no information

Possible causes:

  • Incorrect I2C address.
  • Incorrect SDA and SCL connections.
  • Loose wiring.

Solutions:

  • Run an I2C scanner.
  • Check the LCD address.
  • Confirm the connections to A4 and A5 on the Arduino Uno.

Problem 4: The machine sorts waste incorrectly

Possible causes:

  • Poor training images.
  • Inadequate lighting.
  • Incorrect AI labels.
  • Incorrect servo positions.

Solutions:

  • Collect more representative training images.
  • Improve camera lighting.
  • Retrain the model.
  • Adjust the mechanical gates.

13. Applications of EcoSort AI

The project can be developed for several practical applications.

Schools and learning institutions: Demonstrates artificial intelligence, electronics, environmental conservation, and automation.

Recycling centers: A larger version could assist with preliminary separation of recyclable materials.

Shopping centers: Smart waste collection systems could help separate selected recyclable materials.

Municipal waste management: AI-based sorting technology could support more efficient waste processing.

Research and innovation: The prototype can be extended to investigate computer vision, robotics, and smart environmental monitoring.

14. Possible Future Improvements

EcoSort AI can be upgraded to include:

  • Wi-Fi monitoring using ESP32.
  • Cloud-based waste collection reports.
  • A mobile application for monitoring sorting statistics.
  • A dashboard showing the quantity of each waste category.
  • Additional classification categories such as glass and organic waste.
  • A weight sensor to measure collected waste.
  • Solar power for improved energy independence.
  • A larger conveyor system for increased throughput.

A future version could also use an edge AI model to perform image classification without requiring a separate laptop.

15. Environmental and Educational Benefits

EcoSort AI demonstrates how technology can contribute to environmental sustainability.

The project encourages proper waste segregation, improves awareness of recycling, and introduces learners to practical applications of artificial intelligence.

It also integrates several STEM disciplines:

STEM AreaApplication
ScienceWaste materials and environmental conservation
TechnologyAI image recognition and embedded systems
EngineeringConveyor, frame, and sorting mechanism
MathematicsAccuracy, percentages, measurements, and data analysis

For schools implementing Competency-Based Education (CBE), the project provides opportunities for practical learning, innovation, collaboration, problem-solving, and environmental responsibility.

16. Frequently Asked Questions

Can I build an AI waste sorting machine using Arduino?

Yes. Arduino can control the sorting mechanism, while an ESP32-CAM or another camera captures images. An AI model running on a compatible computer or edge device identifies the waste category.

What is the role of ESP32-CAM in the project?

The ESP32-CAM captures images of waste materials. These images are sent to an AI classification system for analysis.

Does Arduino Uno support AI image recognition?

The Arduino Uno has limited memory and processing capability. It is better suited to controlling motors, sensors, and sorting mechanisms. Image classification should run on a more capable computer or compatible edge device.

How many types of waste can EcoSort AI identify?

The initial design identifies four categories: plastic, paper, cardboard, and metal. More categories can be introduced by expanding the training dataset and modifying the sorting mechanism.

How much does it cost to build the project in Kenya?

The illustrative component budget in this guide is approximately KSh 11,450. The final cost depends on component prices, construction materials, and additional equipment.

Can this project be presented at a science fair?

Yes. It can be presented as an environmental science, engineering, computer science, or STEM innovation project. A strong presentation should include the working prototype, research methodology, testing data, limitations, and recommendations.

Conclusion

EcoSort AI demonstrates how artificial intelligence, Arduino, ESP32-CAM, sensors, and mechanical automation can be combined to develop a smart waste segregation system.

The prototype provides a practical introduction to machine learning, computer vision, embedded systems, and environmental engineering.

Although the initial version uses a separate computer for AI classification, future improvements could integrate edge AI processing, IoT monitoring, and more advanced sorting mechanisms.

For students, teachers, innovators, and technology enthusiasts, this project offers an opportunity to turn an environmental challenge into a practical engineering solution.


mbeva

Dominic Mbeva is a science teacher, experienced researcher, innovator, and creative technologist with expertise in STEM education, digital media, and scientific research. As a Kenya Science and Engineering Fair (KSEF) advisor and projects manager, he mentors young scientists, guiding them in developing award-winning innovations. He is also an IC Technorat, leading advancements in science and technology. Beyond education, Dominic is a skilled photographer and video editor, using visual storytelling to make science more engaging. His philosophy, “If you take care of minutes, hours will take care of themselves,” reflects his belief in consistent effort, strategic thinking, and innovation to drive success in both research and creativity.

Related Posts

How to Build an ESP32-CAM Wi-Fi Video Streaming Security Camera This is the complete project article again, covering the AI-Thinker ESP32-CAM with OV2640 camera, Arduino IDE programming, FTDI wiring, live…

Read more

How to Build a Bluetooth Low Energy Smart Lock Using ESP32

Learn how to build an ESP32 Bluetooth Low Energy smart lock with a motorized deadbolt, smartphone control, wiring diagrams, code, and safety tips. 1. Introduction A conventional door lock depends…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *