Running, running, every day, we keep running to work, school, and college. In this busy routine, many of us do not even have enough time to eat breakfast properly. Then where do we find the time to clean our homes? Even when we clean, because of laziness or lack of time, we often throw all waste into the same bin without separating biodegradable and non-biodegradable waste. This creates a bigger problem in the future because someone else has to manually separate all the waste, which takes extra time and effort. It is a lot of unnecessary work. So, why not build a system that can automatically detect and separate waste based on whether it is biodegradable or non-biodegradable?
That is exactly what this project focuses on. We have built a Raspberry Pi waste segregation system with CircuitDigest Cloud. To complete this project, we only need four things: a laptop, a Raspberry Pi, a USB camera, and an account in CircuitDigest Cloud. Without further delay, let’s get in and see how to make it possible. You can also check out similar AI projects and Raspberry Pi projects done previously here at Circuit Digest.
Table of Contents
What Is a Smart Waste Segregation System Using Raspberry Pi?
With a Raspberry Pi-based waste segregation system, an image of waste captured by a USB camera can be sent to an Image Processing API located in the Cloud for classification as either biodegradable or non-biodegradable. No trained machine learning is required for classification since the classification is done using an API call. This also makes the tutorial on creating a Raspberry Pi-based waste segregation system very beginner-friendly since you don't need to perform any data labelling or model training; you just need a Raspberry Pi, USB camera, and API call.
Waste Segregation System Using Raspberry Pi Workflow
The system starts with the USB camera, which continuously captures live data. OpenCV is used to access the camera, display the live video feed, and capture images either manually by pressing the Space key in keyboard mode or automatically after a fixed time interval in auto mode. After capturing, the image is converted into JPEG format using OpenCV for easy transmission. The Requests library then sends the image securely to the CircuitDigest Cloud Waste Detection API using an HTTPS POST request along with the API key. The cloud server processes the image using AI-based waste detection and checks whether it's biodegradable or non-biodegradable. The result is then sent back to the system and displayed in the terminal. We have also done an AI-Powered Autonomous Waste-Collecting and Sorting Robot that collects and sorts waste; go through the project for more details.
Components Required
The components below are the ones used to build this Raspberry Pi waste segregation system using Raspberry Pi tutorial.
| S.No | Components | Purpose |
| 1. | Raspberry pi | It is the main controller in this setup for processing. |
| 2. | USB Camera | Used to capture the image for processing |
| 3. | MicroSD Card | Stores the Raspberry Pi OS and project files |
Circuit Diagram Waste Segregation using Raspberry Pi
The circuit diagram below shows that the Raspberry Pi is connected to the external power supply for sufficient power, and the USB camera is connected to the Raspberry Pi board's USB port. The Raspberry Pi is remotely connected to the laptop.
Step-by-Step Procedure for Waste Segregation System Using Raspberry Pi
Unlike ESP32 or Arduino, the code cannot be flashed directly to the Raspberry Pi using the Arduino IDE. Before running the project, the Raspberry Pi must be properly set up by installing the operating system on a microSD card. This process is done using Raspberry Pi Imager on a laptop or PC. First, the microSD card is inserted into the system, and, using Raspberry Pi Imager, the required Raspberry Pi OS and initial configurations, such as Wi-Fi, username, password, and SSH settings, are selected and installed. After the OS installation is completed, the SD card is removed and inserted into the Raspberry Pi’s memory card slot, and the board is powered ON. Although the first-time setup may seem like a lot of work, it is actually simple once completed. A detailed step-by-step guide for the complete Raspberry Pi setup can be found in the Raspberry Pi Complete Setup tutorial. The ways to get the Raspberry Pi connected are as follows,
- Direct Hardware Connection
The first method is by connecting external components such as a monitor, keyboard, and mouse directly to the Raspberry Pi. This allows the Raspberry Pi to work like a normal desktop computer and is mainly useful during the initial setup and for direct operation. - Using SSH (Secure Shell)
The second method is through SSH, where the Raspberry Pi can be accessed remotely from another computer using the same network connection. This method provides command-line control without needing a separate monitor, keyboard, or mouse connected to the Raspberry Pi. - Using VNC Viewer
The third method is by using VNC Viewer, which allows remote access to the full graphical desktop of the Raspberry Pi from another computer. This makes it possible to control the Raspberry Pi exactly like working directly on its own screen, but from a remote location. To work on the setup using VNC Viewer, you can refer to this VNC Viewer for Raspberry Pi tutorial for the detailed step-by-step procedure.
Before stepping into the Thonny IDE present in the Raspberry Pi desktop, first, you need the code. For that, follow the steps below,
Setting Up the CircuitDigest Cloud Waste Detection API
Step 1⇒ Create Your CircuitDigest Cloud Account
First, you need to make an account on the CircuitDigest Cloud. If you already have one, just go to the CircuitDigest Cloud website, scroll down, and you will see the waste detection section; click it and enter.

Step 2⇒ Configure the Confidence Threshold
There, you will notice the try api section, various options such as image, classes, confidence, and result, and a board selection section with its corresponding codes. First, you can minimise and maximise the confidence level according to your needs because the confidence value sets the minimum probability threshold for waste detection. A higher value results in more accurate detections but may miss some, while a lower value detects more objects but with less certainty.

Step 3⇒ Test Image Processing for Waste Segregation
Now, to try without any microcontroller boards, you need to take a picture that has some biodegradable waste and non-biodegradable waste. Upload it to the image section and click Run Test. In a few seconds, you will get the result with waste detection and its count also.

Step 4⇒ Get the Raspberry Pi Code
Below the page, you can see the microcontroller selection. Now, we are going to try this system with the Raspberry Pi. Click the Raspberry Pi, and the website will give you the code. Just copy the code; now go to the Raspberry Pi desktop, click Thonny IDE for programming. In that, paste the copied code after making all connections correct. Nothing, just connect the USB camera to the Raspberry Pi and run the code; that's it. Take any dummy picture from the internet that has some biodegradable and non-biodegradable waste, or you can test this in real time by taking a picture of real-time by taking a biodegradable and non-biodegradable waste using the keyboard keys. You can set it automatically by changing the MODE = "keyboard" in the code, like,
» Keyboard Mode
In this mode, the user captures the image manually by pressing the SPACE key on the keyboard. It is mainly used when working directly with a monitor or through VNC Viewer.
» Auto Mode
In this mode, the system automatically captures images after a fixed time interval without any user interaction. It is useful for continuous monitoring applications.
» SSH Mode
In this mode, the program runs through terminal access using SSH and captures images automatically without using the OpenCV display window. The results are shown directly in the terminal.
Raspberry Pi Waste Segregation System Output
The image below shows the captured image from the Raspberry Pi. Along with it, you can see the detection results of the image, where the waste is Biodegradable or non-biodegradable. Below that, the serial monitor displays the detection output, which includes the count and the confidence value for each identified thing.
Code Explanation for Waste Segregation System Using Raspberry Pi
The code is written in Python for real-time waste detection using a USB camera and CircuitDigest Cloud API. OpenCV is used to capture live images and display the camera feed on the screen. The program supports keyboard mode for manual capture and auto mode for automatic image capture. The captured image is converted into JPEG format for easy transmission. Using the Requests library, the image is sent securely to the cloud API through HTTPS. The server processes the image and returns the waste detection result to the terminal.
import cv2
import requests
import time
import os
import sys
SERVER_URL = "https://www.circuitdigest.cloud/api/v1/waste-detection/detect"
API_KEY = "YourApikey"This section imports all the required Python libraries for camera access, API communication, timing control, and system handling. OpenCV is used for capturing images from the USB camera, while the Requests library is used to send the captured image to the CircuitDigest Cloud API. The server URL and API key are also defined here for waste detection processing.
MODE = "keyboard"
AUTO_INTERVAL = 5
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)This part selects the working mode of the system, either keyboard mode for manual capture or auto mode for automatic image capture after a fixed interval. The USB camera is initialised using OpenCV, and the resolution is set for clear image capture. The auto interval decides how often images are captured in automatic mode.
if not cap.isOpened():
print("Camera not found! Check USB camera connection.")
sys.exit()This section checks whether the USB camera is properly connected and detected by the Raspberry Pi. If the camera is not available, the program displays an error message and stops execution immediately. This prevents the project from running without valid camera input.
_, img_encoded = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 90])
img_bytes = img_encoded.tobytes()
response = requests.post(SERVER_URL, headers=headers,
files=files, timeout=15)This part captures the image from the live camera feed and converts it into JPEG format for efficient transmission. The image is then sent securely to the CircuitDigest Cloud Waste Detection API using an HTTPS POST request. The API processes the image and classifies the waste as biodegradable or non-biodegradable.
if response.status_code == 200:
safe_response = response.text.encode('utf-8', errors='replace').decode('utf-8')
print("Response:", safe_response)This section handles the response received from the cloud server after image processing. If the API request is successful, the result is displayed in the terminal, showing the detected waste category. This helps the user quickly identify whether the waste is biodegradable or non-biodegradable.
Troubleshooting for Waste Segregation System Using Raspberry Pi
Issue 1: Camera not detected
If the USB camera is not detected, the program may display “Camera not found” and stop running. This usually happens because of a loose USB connection or incorrect camera selection. Reconnect the camera properly and make sure it is firmly attached. You can also try changing cv2.VideoCapture(0) to cv2.VideoCapture(1) if another camera device is connected.
Issue 2: API request timeout
Sometimes the captured image may not be sent to the server, and the program shows a timeout error. This usually happens due to a slow internet connection or unstable network access. Check whether the Raspberry Pi is properly connected to Wi-Fi or Ethernet. Increasing the timeout value in the request function can also help solve this issue.
Issue 3: Invalid API key error
If the API key is incorrect, the cloud server will reject the request and waste detection will fail. This can happen if the key is copied incorrectly or contains extra spaces. Recheck the API key from the CircuitDigest Cloud account and paste it correctly in the code. Make sure there are no missing or extra characters.
Issue 4: Incorrect waste classification result
Sometimes the system may classify waste incorrectly because of poor lighting, unclear object visibility, or improper camera angle. Blurry images and low image quality can also affect detection accuracy. Place the camera in a proper position with good lighting conditions. Increasing camera resolution can also improve classification results.
Issue 5: Program crashes during execution
The program may stop suddenly because of missing Python libraries or frame capture errors. This usually happens when OpenCV or Requests is not installed properly on the Raspberry Pi. Make sure all required libraries are installed before running the project. Restarting the Raspberry Pi and checking the camera feed can also help fix the problem.
Advantages and limitations of the Waste Segregation System with Raspberry Pi
The following table gives a clear idea about the limitations and the advantages of Waste segregation using Raspberry Pi
| S.No | Advantages | Limitations |
| 1. | Automatically detects biodegradable and non-biodegradable waste in real time | Requires a stable internet connection for cloud processing |
| 2. | Reduces manual work in waste segregation | Detection accuracy depends on camera quality |
| 3. | Easy to implement using a Raspberry Pi and a USB camera | Poor lighting can affect classification results |
| 4. | Supports both manual and automatic image capture modes | Cloud API usage may have daily or monthly limits |
| 5. | Improves cleanliness and promotes smart waste management | Slight delay may occur due to API response time |
The key advantage of this setup is that we don't need to take any datasets manually or download them from the internet, don't need to label the objects, or create any model. With the help of the CircuitDigest Cloud, we are just flashing the code and using it like a ready-made model. This saves time, and with this time we can focus more on other hardware modifications for future enhancements. This method will eliminate the use of ML training websites like Edge Impulse and TensorFlow Lite. Not only have we done another way of a waste segregation system with Arduino Uno Q, but check out the Automatic Waste Segregation system project for more details.
Frequently Asked Questions
⇥ Does this system work without an internet connection?
No, this system requires an internet connection because the captured image is sent to the CircuitDigest Cloud API for waste detection processing. Without the internet, the detection will not work.
⇥ Can I use any USB camera for this project?
Yes, most standard USB webcams can be used with the Raspberry Pi for this project. However, using a better-quality camera improves image clarity and classification accuracy.
⇥ What is the use of keyboard mode and auto mode?
Keyboard mode allows the user to manually capture an image by pressing the SPACE key. Auto mode captures images automatically after a fixed time interval, making it useful for continuous waste monitoring applications.
⇥ How can I improve waste segregation accuracy?
You can improve accuracy by placing the camera in proper lighting conditions and keeping the waste object clearly visible in front of the camera. Increasing image resolution also helps in better classification results.
⇥ Can this system detect different types of waste at the same time?
The system mainly classifies waste into biodegradable and non-biodegradable categories based on the captured image. It helps users identify the correct waste type for proper disposal.
⇥ Why is Raspberry Pi used for this project?
Raspberry Pi is used because it can run Python, OpenCV, and internet-based API communication smoothly. It provides enough processing power to handle image capture and cloud-based waste segregation efficiently.
⇥ Can this system be used in public places and industries?
Yes, this project can be used in public places like malls, parks, and railway stations, as well as in factories and industries. It helps improve waste segregation and supports cleaner and smarter waste management systems.
Raspberry Pi Waste Segregation GitHub
Get the complete codebase for an AI-powered waste segregation system. Use Raspberry Pi, computer vision, and CircuitDigest Cloud to automate waste sorting. Follow the guide and bring your smart recycling project to life.
Related Raspberry Pi Projects
Discover a collection of Raspberry Pi projects that showcase real-world applications of sensors, computer vision, and automation. These hands-on tutorials can help you build smarter IoT solutions and expand the functionality of your Raspberry Pi-based systems.
Measure Distance using Raspberry Pi and HCSR04 Ultrasonic Sensor
In this project, we are going to interface the HC-SR04 Ultrasonic sensor module to the Raspberry Pi to measure distance. Through this project, we can measure distance with a Raspberry Pi. Before going any further, let's learn about the Ultrasonic sensor.
CCTV Motion Detection with Alarm using OpenCV on Raspberry Pi
In this article, we will learn how to leverage the power of OpenCV and build a Raspberry Pi Motion Detection system on our live CCTV footage. If an activity is detected on any camera, our Raspberry Pi will automatically switch to that particular camera screen and highlight which activity took place, all this in real-time with just 1.5 seconds of lag.
Servo Motor Control with Raspberry Pi
We will be covering all the basic functionalities of the Raspberry Pi in these tutorials. In each tutorial, we will discuss one of the functions of the Pi. In this tutorial, we will control a servo motor with a Raspberry Pi. Before going to the servo, let’s talk about PWM because the concept of controlling a servo motor comes from it.
Complete Project Code
import sys
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
import cv2
import requests
import time
import os
os.environ['DISPLAY'] = ':0'
SERVER_URL = "https://www.circuitdigest.cloud/api/v1/waste-detection/detect"
API_KEY = "YourApikey"
MODE = "keyboard"
AUTO_INTERVAL = 5
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
if not cap.isOpened():
print("Camera not found! Check USB camera connection.")
sys.exit()
print("Camera initialized.")
print(f"Running in [{MODE}] mode")
if MODE == "keyboard":
print("Press SPACE to capture | Press ESC to quit")
elif MODE == "auto":
print(f"Auto capturing every {AUTO_INTERVAL} seconds | Press ESC to quit")
def classify_waste(frame):
for _ in range(3):
cap.read()
ret, frame = cap.read()
if not ret:
print("Capture failed")
return
_, img_encoded = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 90])
img_bytes = img_encoded.tobytes()
headers = { "X-API-Key": API_KEY }
files = { "imageFile": ("snap.jpg", img_bytes, "image/jpeg") }
try:
print("\nPhoto captured! Sending to API...")
response = requests.post(SERVER_URL, headers=headers,
files=files, timeout=15)
if response.status_code == 200:
safe_response = response.text.encode('utf-8', errors='replace').decode('utf-8')
print("Response:", safe_response)
else:
print(f"HTTP error: {response.status_code}")
except requests.exceptions.Timeout:
print("Request timed out!")
except Exception as e:
print(f"Error: {str(e).encode('utf-8', errors='replace').decode('utf-8')}")
last_capture_time = 0
while True:
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
cv2.imshow("Waste Classification - SPACE: capture | ESC: quit", frame)
key = cv2.waitKey(1) & 0xFF
if MODE == "keyboard":
if key == 32:
print("\nCapturing image...")
classify_waste(frame)
elif MODE == "auto":
current_time = time.time()
if current_time - last_capture_time >= AUTO_INTERVAL:
last_capture_time = current_time
print("\nAuto capturing...")
classify_waste(frame)
if key == 27:
print("Quitting...")
break
cap.release()
cv2.destroyAllWindows()


