How to Build a Smart Garbage Monitoring System Using Arduino, Ultrasonic Sensor and IoT

Learn how to build a smart garbage monitoring system using Arduino, an ultrasonic sensor and IoT. Includes circuit connections, source code and ThingSpeak dashboard setup.

Main components: Arduino-compatible ESP8266 NodeMCU, HC-SR04 Ultrasonic Sensor, Wi-Fi and IoT Dashboard.

- YouTube
Part 3 , project 2 : Smart dustbin Monitoring dashboard with IoT technology.
GitHub - sanskreate/SmartBin: SmartBin · GitHub

1. Introduction

Waste management is an important challenge in homes, schools, hospitals, shopping centres and urban environments. Traditional garbage collection systems often depend on fixed collection schedules rather than the actual amount of waste inside garbage bins.

As a result, some bins are collected before they are full, while others overflow before the next collection visit. Overflowing garbage bins can cause unpleasant smells, attract pests and contribute to environmental pollution.

The Smart Garbage Monitoring System Using Arduino, Ultrasonic Sensor and IoT is designed to address this challenge through automated waste-level monitoring.

The project uses an ultrasonic sensor to measure the amount of available space inside a garbage bin. An ESP8266 NodeMCU microcontroller processes the measurements and sends the information to an online IoT dashboard through Wi-Fi.

When the garbage reaches a predefined level, the system sends an alert to notify waste management personnel that the bin needs to be emptied.

Project objective: To develop an IoT-based garbage monitoring system that measures waste levels in real time and supports efficient waste collection.

2. How the Smart Garbage Monitoring System Works

The system uses an HC-SR04 ultrasonic sensor mounted at the top of a garbage bin, facing downwards.

The sensor sends ultrasonic waves towards the garbage surface and measures the time taken for the reflected waves to return.

The ESP8266 NodeMCU uses this distance measurement to calculate the percentage of the bin occupied by waste.

The system then transmits the waste-level information to an IoT dashboard through a Wi-Fi connection.

The operating process is as follows:

  • The ultrasonic sensor measures the distance between the sensor and the garbage surface.
  • The microcontroller calculates the garbage fill percentage.
  • The ESP8266 connects to a Wi-Fi network.
  • The waste-level readings are transmitted to an online dashboard.
  • When the garbage level reaches 80%, the system identifies the bin as nearly full.
  • At 95% or above, the system indicates a critical collection requirement.
Smart Dustbin for Clean City IOT Based Project

3. Materials and Components Required

The following components are required to construct the project.

ComponentQuantityFunction
ESP8266 NodeMCU1Main controller and Wi-Fi communication
HC-SR04 ultrasonic sensor1Measures garbage level
Garbage bin/container1Holds the waste
Breadboard1Circuit assembly
Jumper wiresSeveralElectrical connections
1 kΩ resistor1Voltage divider
2 kΩ resistor1Voltage divider
USB cable1Programming and power supply
5V power supply1Powers the system

Additional materials:

  • Computer with Arduino IDE.
  • Wi-Fi internet connection.
  • ThingSpeak IoT platform account.
  • Suitable enclosure for protecting the electronics.

4. Circuit Diagram and Wiring Connections

The HC-SR04 ultrasonic sensor has four pins:

  • VCC
  • TRIG
  • ECHO
  • GND

The ESP8266 NodeMCU controls the sensor and processes the distance measurements.

Wiring connections

HC-SR04 pinESP8266 NodeMCU pin
VCCVIN / 5V supply
GNDGND
TRIGD5 (GPIO14)
ECHOD6 (GPIO12) through voltage divider

Important voltage protection: The HC-SR04 produces a 5V ECHO signal, while ESP8266 GPIO pins operate at 3.3V. Never connect the ECHO pin directly to the ESP8266.

Use a voltage divider:

  • Connect HC-SR04 ECHO to a 1 kΩ resistor.
  • Connect the other end of the 1 kΩ resistor to D6.
  • Connect a 2 kΩ resistor between D6 and GND.

This reduces the ECHO voltage to a safer level for the ESP8266.

NodeMCU with ultrasonic sensor never wake up - General Guidance - Arduino Forum

5. Calculating the Garbage Fill Percentage

The system determines the amount of garbage inside the bin by comparing the measured distance with the internal height of the empty bin.

The formula is:

\text{Fill Level}=
\frac{H-D}{H}\times100

Where:

  • = Internal height of the empty garbage bin.
  • = Distance between the ultrasonic sensor and the garbage surface.

Example:

Assume the garbage bin has an internal height of 60 cm.

The ultrasonic sensor measures a distance of 15 cm from the sensor to the garbage surface.

\text{Fill Level}=
\frac{60-15}{60}\times100=\frac{45}{60}\times100=75\%

Therefore, the garbage bin is approximately 75% full.

6. Arduino Source Code

The following program uses the ESP8266 NodeMCU, HC-SR04 ultrasonic sensor and ThingSpeak IoT platform to monitor garbage levels.

Before uploading the program:

  • Install the ESP8266 board package in Arduino IDE.
  • Install the ESP8266WiFi library.
  • Create a ThingSpeak account.
  • Create a channel with a field named Garbage Fill Level.
  • Copy your Wi-Fi credentials and ThingSpeak Write API Key into the program.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

// Wi-Fi credentials
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";

// ThingSpeak API key
String apiKey = "YOUR_THINGSPEAK_WRITE_API_KEY";

// Ultrasonic sensor pins
const int trigPin = D5;
const int echoPin = D6;

// Internal height of garbage bin in cm
const float binHeight = 60.0;

// Variables
float distance;
float fillLevel;

unsigned long lastUpdate = 0;
const unsigned long updateInterval = 20000;

WiFiClient client;

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

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  digitalWrite(trigPin, LOW);

  Serial.println("Smart Garbage Monitoring System");

  WiFi.begin(ssid, password);

  Serial.print("Connecting to WiFi");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi Connected!");
  Serial.println(WiFi.localIP());
}

float measureDistance() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH, 30000);

  if (duration == 0) {
    return -1;
  }

  float distance =
    duration * 0.0343 / 2.0;

  return distance;
}

void uploadToThingSpeak(float level) {

  if (WiFi.status() == WL_CONNECTED) {

    HTTPClient http;

    String url =
      "http://api.thingspeak.com/update?api_key="
      + apiKey +
      "&field1=" + String(level, 1);

    http.begin(client, url);

    int responseCode = http.GET();

    Serial.print("ThingSpeak Response: ");
    Serial.println(responseCode);

    http.end();

  } else {

    Serial.println("WiFi Disconnected!");
  }
}

void loop() {

  distance = measureDistance();

  if (distance < 0) {
    Serial.println("Sensor measurement error");
    delay(1000);
    return;
  }

  // Calculate garbage fill percentage
  fillLevel =
    ((binHeight - distance) / binHeight) * 100.0;

  // Restrict percentage to 0-100
  fillLevel = constrain(fillLevel, 0, 100);

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  Serial.print("Garbage Fill Level: ");
  Serial.print(fillLevel);
  Serial.println("%");

  // Display garbage status
  if (fillLevel >= 95) {

    Serial.println("CRITICAL: BIN FULL!");

  } else if (fillLevel >= 80) {

    Serial.println("WARNING: BIN ALMOST FULL");

  } else {

    Serial.println("STATUS: BIN HAS SPACE");
  }

  // Upload readings every 20 seconds
  if (millis() - lastUpdate >= updateInterval) {

    uploadToThingSpeak(fillLevel);

    lastUpdate = millis();
  }

  delay(2000);
}

Understanding the Arduino program

Code instructionPurpose
WiFi.begin()Connects the controller to Wi-Fi
pulseIn()Measures the ultrasonic echo duration
measureDistance()Calculates the distance to the waste
fillLevelStores the percentage of garbage inside the bin
constrain()Keeps the calculated percentage between 0 and 100
uploadToThingSpeak()Sends readings to the IoT platform
updateIntervalControls the frequency of data transmission

7. Setting Up the IoT Dashboard Using ThingSpeak

Akıllı Çöp — IoT Projesi. Çöp kutusunun doluluk oranının NodeMCU… | by Özge Çinko | Medium
ThingSpeak Read - Read data stored in ThingSpeak channel - Simulink
Water Level Control and Monitoring System in a Tank Made With Arduino Uno and NodeMCU ESP8266 Development Boards[v1] | Preprints.org
Weather Monitoring Using Esp32dht11oledthingspeak 7 Steps
ESP32. MQTT. Broker. Publish. Subscribe. ThingSpeak - Internet of Things - MIT App Inventor Community

ThingSpeak is an IoT platform that allows connected devices to send, store and visualize sensor data.

In this project, ThingSpeak displays the percentage of garbage inside the bin.

Steps to configure ThingSpeak

  • Visit ThingSpeak.
  • Create a free account or sign in.
  • Select Channels.
  • Click New Channel.
  • Name the channel Smart Garbage Monitoring System.
  • Enable Field 1 and name it Garbage Fill Level.
  • Save the channel.
  • Open the API Keys section.
  • Copy the Write API Key.
  • Insert the key into the Arduino program.
  • Upload the program to the ESP8266 NodeMCU.

Once the system starts operating, the sensor readings will appear on the ThingSpeak channel.

Expected IoT dashboard readings

Smart Garbage Monitoring Dashboard

Garbage fill level

35%

Space available

Bin status

Normal

Collection not yet required

Illustrative dashboard values, not live sensor readings.

8. Expected System Operation

The system classifies the garbage level according to the following thresholds.

Garbage levelSystem statusRecommended action
0–49%NormalContinue monitoring
50–79%FillingMonitor the bin
80–94%Almost fullPlan collection
95–100%CriticalPrioritize collection

When the garbage reaches the critical level, the waste management team can use the dashboard information to prioritize collection.

9. Project Assembly Procedure

Bot Verification
Smart Dustbin With IOT Notifications
Part 3 , project 2 : Smart dustbin Monitoring dashboard with IoT technology.
【開統編】arduino智能垃圾桶超聲波自動感應創客競賽大中小學科技活動作品*匯豐五金icyqqboy | 蝦皮購物
Smart Kitchen Containers - Hackster.io
IoT Based Smart Dustbin Project using NodeMCU – QuartzComponents
Advancing Sustainability Through an IoT-Driven Smart Waste Management System with Software Engineering Integration
iot based smart dustbin management system
아두이노 스마트 쓰레기통
Final Year Project: Smart Dustbin with IoT | Pratik Lodha posted on the topic | LinkedIn
Pembuatan Tempat Sampah Otomatis Berbasis Arduino oleh Mahasiswa KKN NR 7 UNTAG | kumparan.com
IOT Smart Dustbin Using NodeMCU and ESP8266 – svsembedded, 7842358459, 9491535690
Photograph of the developed smart trash bin. a Populated printed... | Download Scientific Diagram

Follow these steps to construct the prototype:

  • Obtain a suitable plastic garbage container.
  • Mount the HC-SR04 ultrasonic sensor at the top of the container.
  • Ensure the sensor faces downwards towards the garbage.
  • Connect the ultrasonic sensor to the ESP8266 NodeMCU.
  • Assemble the voltage divider for the ECHO signal.
  • Connect the NodeMCU to a computer using a USB cable.
  • Upload the Arduino program.
  • Connect the ESP8266 to a Wi-Fi network.
  • Configure the ThingSpeak dashboard.
  • Introduce waste into the bin and observe the changes in the measured distance and fill percentage.

The electronic components should be enclosed in a protective casing to prevent exposure to moisture and garbage.

10. Applications of the Smart Garbage Monitoring System

The project can be applied in different environments.

  • Schools: Monitoring garbage bins in classrooms, laboratories and school compounds.
  • Hospitals: Monitoring waste containers in designated waste collection areas.
  • Shopping centres: Monitoring bins in busy public spaces.
  • Residential estates: Improving household waste collection.
  • Municipalities: Supporting smart city waste management.
  • Industries: Monitoring waste containers in production facilities.
  • Public institutions: Improving environmental cleanliness.

11. Advantages of the Project

  • Real-time monitoring: Provides information about garbage levels remotely.
  • Reduced overflowing bins: Identifies bins that require collection.
  • Efficient waste collection: Helps collection teams prioritize nearly full bins.
  • Low-cost technology: Uses affordable electronic components.
  • Remote access: Allows waste levels to be monitored through an internet-connected dashboard.
  • Environmental protection: Supports cleaner surroundings and improved sanitation.
  • Expandable design: Can be upgraded to monitor several garbage bins.

12. Possible Project Improvements

The basic prototype can be upgraded with additional electronic components and IoT features.

Smart Waste Collection & Sensing System - Share Project - PCBWay
Additional componentImprovement
GPS module (NEO-6M)Identifies the geographical location of mobile bins
GSM module (SIM800L)Sends SMS notifications
LCD displayDisplays garbage fill percentage
BuzzerProvides a local warning when the bin is nearly full
Solar panelProvides renewable power
ESP32Supports advanced wireless connectivity
Additional ultrasonic sensorsMonitors several garbage bins
Mobile applicationEnables remote monitoring by collection teams

A more advanced version could include a centralized dashboard displaying multiple garbage bins, their locations and current fill levels.

13. Project Testing and Evaluation

The project should be tested using different quantities of waste to determine whether the ultrasonic sensor accurately measures the garbage level.

TestExpected observation
Empty garbage binFill level close to 0%
Bin filled to 25%Dashboard displays approximately 25%
Bin filled to 50%Dashboard displays approximately 50%
Bin filled to 80%Almost-full warning
Bin filled to 95%Critical collection warning
Wi-Fi disconnectedSensor continues measuring locally, but online updates stop

Record the readings obtained during testing and compare them with the actual garbage levels.

14. Safety Precautions and Limitations

  • Protect the ESP8266 and electrical connections from moisture.
  • Keep electronic components away from direct contact with garbage.
  • Use a waterproof enclosure where necessary.
  • Ensure the ultrasonic sensor is firmly mounted.
  • Avoid placing waste directly against the sensor.
  • Calibrate the sensor using the actual internal height of the garbage bin.
  • Irregular waste surfaces may produce inaccurate measurements.
  • Wi-Fi connectivity is required for remote monitoring.
  • Provide a reliable power supply for continuous operation.

The prototype is designed for educational demonstrations and should be improved with appropriate environmental protection before outdoor deployment.

15. Conclusion

The Smart Garbage Monitoring System Using Arduino, Ultrasonic Sensor and IoT demonstrates how modern electronics and internet connectivity can improve waste management.

By combining ultrasonic distance measurement with ESP8266 Wi-Fi communication, the system can monitor garbage levels and transmit information to an online dashboard.

The project provides a practical solution for identifying nearly full garbage bins and supporting more efficient waste collection.

It is an excellent STEM project for learners interested in Arduino programming, Internet of Things, environmental conservation, automation and smart city technologies.

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 Make a Smart River Water Level and Pollution Monitoring Boat / Buoy Using ESP32 and GPS

Meta Description: Learn how to build a smart river water level and pollution monitoring boat using ESP32, GPS and water quality sensors. Includes components, circuit connections, Arduino code and IoT…

Read more

How to build an automatic street light controller using Arduino and an LDR sensor.

Meta Description: Learn how to build an automatic street light controller using Arduino and an LDR sensor. Explore circuit connections, components, Arduino code and how the system works. 1. Introduction…

Read more

Leave a Reply

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