AutoSort FinalReport
AutoSort FinalReport
ENGINEERING- CS321
BY
Fatma Ouahada
Habib Al Kateb
Rayen Chaibi
ACADEMIC SUPERVISORS
LAB INSTRUCTORS
2025-2026
ABSTRACT
This project presents the design and implementation of a Smart Waste Sorting Trash
Bin based on an STM32 microcontroller platform. The system seamlessly integrates
mechanical actuation, sensing, visual feedback, and artificial intelligence to
automate the waste disposal and sorting process, reducing human intervention and
improving recycling accuracy. A servo motor manages the opening and closing of
the bin lid, while a stepper motor rotates internal compartments to align with the
detected waste type. The fill level of each bin is continuously monitored using an
HC-SR04 ultrasonic sensor, with red and green LEDs providing immediate visual
feedback to indicate whether the bins are full or available.
ii
Table of Contents
ABSTRACT .................................................................................................................. ii
1. INTRODUCTION .................................................................................................. 1
2. SYSTEM DESIGN.................................................................................................. 2
2.1 Components of the system ....................................................................... 2
2.2 Design ......................................................................................................... 3
2.3 System Description .................................................................................... 4
2.3.1 circuit design ............................................................................................... 4
2.3.2 Simulation ................................................................................................. 5
2.3.3 Real Implementation ............................................................................... 5
2.4 Artificial Intelligence Classification System ................................................. 6
2.4.1 Purpose and Role of the AI System ........................................................ 6
2.4.2 Input Data Acquisition ............................................................................. 7
2.4.3 AI Model Architecture ............................................................................. 7
2.4.4 Classification Output and Decision Logic ............................................. 8
2.4.5 Communication with Embedded System .............................................. 8
3. SYSTEM DIAGRAMS AND REQUIREMENTS ............................................................ 9
3.1 System Requirements ..................................................................................... 9
3.1.1 Functional and Non-Functional Requirements ..................................... 9
3.1.2 Requirement Satisfaction Explanation ................................................... 9
3.2 SysML Diagrams ............................................................................................ 10
3.2.1 Structure Diagrams ................................................................................ 10
3.2.2 Behaviour Diagrams ......................................................................... 16
4. CODE IMPLEMENTATION .................................................................................... 20
4.1 Setup .............................................................................................................. 20
4.1.1 STM32CubeMX Configuration ............................................................... 20
4.1.2 Library Integration .................................................................................. 22
4.1.3 Mathematical Equations ....................................................................... 22
4.2 Code Explanation......................................................................................... 23
4.2.1 Embedded Firmware Implementation................................................. 23
iii
4.2.2 AI Software Implementation ................................................................. 28
5. TESTING ................................................................................................................ 32
5.1 Servo Motor Testing (Lid Mechanism) ........................................................ 32
5.2 Ultrasonic Sensor Testing (Fill Level)............................................................ 33
5.3 Camera Module and AI Integration Testing .............................................. 33
5.4 Stepper Motor Testing (Sorting Mechanism) .............................................. 35
6. RESULTS ................................................................................................................ 36
7. SUMMARY............................................................................................................ 37
7.1 Research Goals and Achievements........................................................... 37
7.2 Challenges and Solutions ............................................................................ 37
7.3 Future Enhancements .................................................................................. 38
8. REFERENCES......................................................................................................... 39
iv
1. INTRODUCTION
Effective waste management is a critical component of sustainable urban
development, as improper disposal and inefficient sorting contribute significantly to
environmental pollution and resource loss. Traditional trash bins rely heavily on
manual sorting, which is not only time-consuming but also prone to human error,
often leading to contamination of recyclable materials and increased waste in
landfills. Moreover, conventional bins provide limited feedback to users and offer no
support for hygienic handling, further complicating effective waste management in
densely populated areas.
This project addresses these challenges by designing an automated smart trash bin
system that leverages STM32-based embedded systems and Artificial Intelligence to
streamline waste segregation and minimize human interaction. By integrating an
OV7670 camera module with an external AI classification module, the system
identifies waste types in real time and directs them to specific compartments via
precise stepper and servo motor control. The software architecture, developed
using STM32CubeMX and HAL libraries, emphasizes modularity and scalability for
future smart city integration.
1
2. SYSTEM DESIGN
2.1 Components of the system
Figure 1: STM32 Microcontroller Figure 2: Red + green LEDS Figure 3: OV7670 Camera Module
2
Component Description Role
2.2Design
3
2.3 System Description
2.3.1 circuit design
Pin usage configured in STM32CubeMX:
4
Timers, GPIO modes, and clock prescalers were configured using STM32CubeMX,
while application logic was written using HAL functions
2.3.2 Simulation
5
Figure 13: Camera Module implementation
The Artificial Intelligence (AI) system is responsible for automatically identifying the
type of object/material captured by the camera. Its main role is to replace manual
inspection by performing a fast and consistent classification from an input image.
The embedded system is mainly used for image acquisition and transmission, while
the heavy computation (model inference) is executed on a local AI server to
achieve higher performance and easier model updates. The AI system outputs a
predicted class (e.g., metal, plastic, organic) along with a confidence score that
indicates how certain the model is.
Once a capture condition is met (trigger from a sensor or event logic), the
embedded system captures a single frame and stores it in a memory buffer. The
frame is then transmitted over Ethernet using TCP to a local AI server. The server
reconstructs the image from the received byte stream and performs preprocessing
(resizing/normalizing) before inference.
6
2.4.2 Input Data Acquisition
The input data for the AI system is an image captured using an OV7670 camera
connected to the STM32F439ZI microcontroller through the DCMI interface and
DMA. The camera provides frames in QVGA resolution (320×240) and the image can
be transferred in RGB565 format (2 bytes per pixel) or converted to another format if
required.
Once a capture condition is met (trigger from a sensor or event logic), the
embedded system captures a single frame and stores it in a memory buffer. The
frame is then transmitted over Ethernet using TCP to a local AI server. The server
reconstructs the image from the received byte stream and performs preprocessing
(resizing/normalizing) before inference.
The AI classification model is designed to work with visual features extracted from
the captured images. A lightweight Convolutional Neural Network (CNN) is typically
used because CNNs are highly effective for image classification tasks. The model
may be either:
The architecture is optimized to balance accuracy and speed, since inference must
be fast enough for real-time or near real-time decision making.
7
2.4.4 Classification Output and Decision Logic
After the AI server receives the image frame and completes preprocessing, the
model performs inference and produces a single predicted class label (for example:
plastic, metal, or organic).
• This label is treated as the system’s decision and is sent back to the
embedded system.
8
3. SYSTEM DIAGRAMS AND REQUIREMENTS
3.1 System Requirements
9
3.2 SysML Diagrams
SysML (Systems Modeling Language) is a graphical language for modeling complex
systems, ideal for representing the architecture, behavior, and interactions within the
alarm system that we are developing. By using SysML, we can model the system's
components, how they interact, and the system's requirements. This approach will
provide a clear and structured way to design our embedded alarm system, ensuring
that the system operates as intended and meets its requirements.
[Link] Block Definition Diagram: Shows the main components of the Smart
Waste Sorting System and how they relate conceptually
10
Block summary
11
Relationship summary
AI system is included to
SmartWaste- AIClassificationSyste
Composition enable intelligent waste
SortingSystem m
classification.
12
Ethernet
SmartWaste- Ethernet communication is a
Composition
SortingSystem Communication subsystem of the overall
system.
AI system sends
AIClassificatio
Ethernet classification results
n Dependency
Communication using JSON over
System
Ethernet.
13
[Link] Internal block diagram : Shows how the components interact and connect
internally, illustrating the flow of signals and control.
STM32 Microcontroller
14
Servo Motor (Lid Control)
Camera Module
AI Classification Module
15
3.2.1 Behaviour Diagrams
Actors
• User:
Use Cases
• View Waste Status: User observes whether the bin is full or empty via LEDs.
16
• Automatic Sorting: System rotates internal compartments to align with the
appropriate waste type.
Include Relationships
o Every time the user deposits waste, the system automatically sorts it
based on AI classification results.
Illustrates the chronological flow of operations in the system, from the moment
the user places trash into the system, through AI analysis, motor control, and
bin status update via sensors and LEDs. This diagram highlights the interaction
between all system components.
Actors / Components
• User
17
• AI Module
o Processes the camera image.
o Determines the trash type (e.g., plastic, organic, paper).
o Sends the trash type information to the system.
• System / Controller
o Receives trash type from the AI module.
o Commands stepper and servo motors to handle the trash.
o Monitors motor completion signals.
• Stepper Motor (17HS4401)
o Rotates the mechanism to align the correct bin for the trash.
• Servo Motor
o Opens and closes the top lid of the selected bin so the trash can fall in.
• Bin Sensor
o Detects whether each bin is full or not.
o Sends status to LEDs.
• LEDs
o Show bin status (red = full, green = not full).
o Controlled only by sensors, not by the system.
Process Flow
18
[Link] Activity Diagram:
19
4. CODE IMPLEMENTATION
This chapter describes the software implementation of the smart waste sorting
system. It covers the configuration of the microcontroller, the libraries used, the
mathematical models applied, and a detailed explanation of the main program
logic.
4.1 Setup
• Clock Configuration:
o The system clock (SYSCLK) was configured to ensure stable timing for
PWM generation and sensor measurements.
20
• GPIO Configuration:
o The PWM signal is used to control the opening and closing of the bin
lid.
21
4.1.2 Library Integration
The project uses the STM32 HAL (Hardware Abstraction Layer) libraries, which simplify
peripheral configuration and improve code portability. The following libraries are
integrated:
Additionally, the DWT (Data Watchpoint and Trace) cycle counter is enabled to allow
precise microsecond-level timing required for ultrasonic distance measurement.
Angle × 1000
Pulse Width = 1000 + ( )
180
Where:
Where:
22
4.2 Code Explanation
• Initialization Phase:
23
o The servo opens the lid when the stepper motor signals that the
correct bin position is ready.
Sets the motor rotation direction by driving the DIR pin of the A4988 driver.
24
Figure 25 Stepper Control
o Resets the PA4 signal to indicate that a new sorting operation has
started.
o Commands the stepper motor to rotate to the angle associated with
the detected waste material.
o Sets PA4 high once the rotation is completed, signaling successful bin
alignment.
o Introduces a delay to allow the waste item to fall into the correct bin.
o Returns the motor to its initial position to prepare the system for the
next sorting cycle.
25
• Ultrasonic Sensor Processing:
o If the distance is above the threshold, the bin is not full and the
green LED is turned on.
26
Figure 28: Bin Status Display
• Key Functions
Servo_SetAngle(uint8_t angle)
– Converts a desired angle to PWM duty cycle and moves the servo.
read_ultrasonic_distance(void)
– Triggers the ultrasonic sensor, measures echo time, and returns
distance in cm.
SystemClock_Config(void)
– Configures the system clock.
MX_TIM1_Init(void)
– Initializes Timer 1 for PWM output.
MX_GPIO_Init(void)
– Configures GPIO pins for LEDs, stepper simulation, and ultrasonic
sensor.
Error_Handler(void)
– Infinite loop in case of errors
angle_to_steps(uint16_t angle)
– Converts a rotation angle into the corresponding number of motor
steps.
step_motor(uint16_t steps, GPIO_PinState direction)
– Rotates the stepper motor by a specified number of steps in a given
direction using step pulses.
• Main Loop Execution:
27
4.2.2 AI Software Implementation
Figure 29: Ollama API Integration and Structured JSON Prompt Construction
generate_with_ollama Function : sends text and image data to a local Ollama API to
generate AI responses. It manages the asynchronous connection, processes
streaming chunks of data, and handles the conversion of the final result into a
structured JSON format.
28
[Link] Purpose and Role of the AI System
API endpoint role: receives frame bytes → sends to AI model → returns classification):
(from [Link] — the endpoint that acts as the AI “server” side classifier
29
[Link] Input Data Acquisition
30
[Link] Classification Output and Decision Logic
This module serves as the "instructional brain" of the AI pipeline, ensuring the raw
image data is translated into a precise sorting command. It operates through the
following key mechanisms:
• Strict Whitelist Validation: The code defines a closed set of "allowed" material
categories—such as metal, plastic, and organic—preventing the AI from
returning ambiguous or unsupported classifications.
31
5. TESTING
This section details the functional verification of the individual hardware components
and the software integration. Each component was tested against its design
requirements to ensure reliability before full system assembly
• Procedure: A PWM signal with varying duty cycles was sent to the servo to test
the 0° (closed) and 90° (open) positions.
• Validation :
Figure 35: Lid in initial position (0°) Figure 36: Lid started opening Figure 37: Lid opened (90°)
Figure 38: Lid rotating back to 0° Figure 39: Lid closed (0°)
32
5.2 Ultrasonic Sensor Testing (Fill Level)
• Validation :
Figure 40: Sensor detected bin not full Figure 41: Sensor detected full bin
• Observations: The system correctly identified "Full" status when an object was
within the threshold, triggering the Red LED. It returned to "Available" (Green
LED) when the object was far .
• Validation:
33
Figure 43: Image transfer
• Observations: Partial Success / Failure. While the image transfer and API
communication were successful, the AI misclassified the metal can as "Plastic"
in the most recent trial, despite succeeding in all previous trials.
• Root Cause Analysis: This discrepancy likely stems from lighting conditions or
the low-resolution QVGA capture, which can confuse the AI's feature
extraction. Further refinement of the build_material_prompt logic or the
"Reason" key in the JSON response is required to debug this.
34
5.4 Stepper Motor Testing (Sorting Mechanism)
• Objective: To verify the step accuracy and torque required for the sorting
movement.
• Procedure: Commands were sent to the stepper driver to rotate the sorting
tray to specific coordinates.
35
6. RESULTS
The system demonstrated high reliability in its core control logic. The servo motor
responded correctly to microcontroller triggers for lid operation, status LEDs reflected
the bin’s fill level accurately, and ultrasonic distance measurements were consistent
with physical measurements.
36
7. SUMMARY
7.1 Research Goals and Achievements
The project successfully integrated embedded systems, sensing, and AI-driven
decision-making by bridging hardware control with high-level data analysis. Using
the STM32, the system captures environmental data and converts it into structured
information that provides the necessary context for classification. This data is
processed through specialized prompt engineering, ensuring the AI produces a
machine-readable response instead of unpredictable text. This protocol allows the
local model to act as an expert analyst, delivering precise material identifications
that the system can immediately process. Ultimately, the research achieved a full
closed-loop automation where AI decisions are converted into physical sorting
movements via a stepper motor drive
• Voltage instability and electrical noise affecting the motor driver: This was
mitigated by adding two decoupling capacitors between VCC and GND,
ensuring voltage stability and protecting the driver from current spikes.
37
7.3 Future Enhancements
Advanced Motor Control: Implement closed-loop control using encoders on the
stepper motor to achieve precise positioning and reduce vibration without relying
solely on open-loop timing and current adjustments.
Improved Sensor Fusion: Combine multiple sensors (ultrasonic, IR, or weight sensors)
to increase accuracy in fill-level detection and object presence, reducing false
triggers.
User Feedback and Interface: Introduce an LCD or touch interface to provide real-
time status, system logs, or manual override controls for maintenance and
troubleshooting.
38
8. REFERENCES
[1] I. Sosunova and J. Porras, "IoT-Enabled Smart Waste Management Systems for
Smart Cities: A Systematic Review," IEEE Access, vol. 10, pp. 73326–73363, 2022. doi:
10.1109/ACCESS.2022.3188308.
[7] Seeed Studio, “HC-SR04 Ultrasonic Sensor Datasheet”, 2015. [Online]. Available:
[Link]
[9] Ollama, "Ollama: Local Large Language Models," 2024. [Online]. Available:
[Link]
39