ESP32 Smart Dustbin with Touchless Lid & Fill-Level Web Page

Build a touchless ESP32 smart dustbin: wave your hand and the servo opens the lid, while a second ultrasonic sensor shows how full the bin is on a Wi-Fi web page.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUESP32 DevKit V1
  • Parts8 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 smart dustbin opens its lid by itself when you bring your hand close, so you never have to touch a dirty lid. A second ultrasonic sensor inside the lid measures how full the bin is, and the ESP32 shows that level on a simple web page you can open on any phone connected to your Wi-Fi.

It is a good intermediate project because it combines two sensors, a servo, careful 5V to 3.3V level shifting and a small web server. It is useful in a kitchen, office, clinic or school, and the fill-level page tells you when the bin needs emptying before it overflows.

ESP32 smart dustbin with a servo-opened lid, two HC-SR04 ultrasonic sensors and a phone showing the fill level web page

How It Works

  • Hand detection: the lid sensor faces forward and is read about ten times a second. When something is closer than 20 cm, the ESP32 turns the servo to the open angle. The lid stays open for 4 seconds after your hand moves away, then closes.
  • Fill level: the second sensor faces down into the bin. It measures the distance to the top of the rubbish. An empty 30 cm deep bin reads about 30 cm and a full one about 4 cm, and the code turns that into 0 to 100 percent. It takes the middle of five readings to ignore odd echoes, and it only measures while the lid is closed so the sensor is in a fixed position.
  • Level shifting: the HC-SR04 runs on 5V and its ECHO pin outputs 5V, which is too much for an ESP32 pin. A 1 kΩ and 2 kΩ divider on each ECHO line brings it down to about 3.3V. The TRIG pin is fine with the ESP32’s 3.3V signal.
  • Servo signal: ESP32 core 3.x has a built-in PWM unit (LEDC). The sketch sets it to 50 Hz and sends a 500 to 2400 µs pulse, which is all a hobby servo needs, so no servo library is required.
  • Web page: the ESP32 joins your Wi-Fi and serves a page at its IP address or http://smartbin.local. The page asks /data every 2 seconds for the fill percent, lid state and open count, and has an Open lid button that calls /open.
  • Full warning: at 85 percent the on-board LED turns on and the page bar turns red with a message to empty the bin.

Components Required

  • ESP32 DevKit V1 (30-pin) – 1
  • HC-SR04 ultrasonic sensor – 2 (one for the hand, one for the fill level)
  • MG90S metal-gear servo (or SG90 for a very light lid) – 1
  • 1 kΩ resistor – 2 and 2 kΩ resistor – 2 (echo voltage dividers)
  • 470 µF 10V electrolytic capacitor (across servo supply) – 1
  • 5V 2A power adapter with DC jack or USB breakout – 1
  • Dustbin with a hinged flap lid (5 to 10 litre) – 1
  • Breadboard or small perfboard, jumper wires, double-sided tape and a small L-bracket for the servo

Wiring Table

Part / pinESP32 pinNotes
Lid HC-SR04 VCC / GNDVIN (5V) / GNDSensor needs 5V
Lid HC-SR04 TRIGGPIO53.3V trigger works fine
Lid HC-SR04 ECHOGPIO18 through 1 kΩ, 2 kΩ to GNDVoltage divider, never connect ECHO directly
Fill HC-SR04 VCC / GNDVIN (5V) / GNDMount under the lid facing down
Fill HC-SR04 TRIGGPIO19
Fill HC-SR04 ECHOGPIO23 through 1 kΩ, 2 kΩ to GNDVoltage divider
Servo orange (signal)GPIO1350 Hz LEDC PWM
Servo red / brown+5V supply / GNDPower from the 5V 2A adapter, not the 3V3 pin
470 µF capacitorAcross servo +5V and GNDStops ESP32 brownout resets
Full LEDGPIO2 (on-board)No wiring needed

Connection Diagram

The illustration at the top shows how the parts sit on the bin. It is a layout guide only. Follow the pin-accurate drawing below, which matches the wiring table exactly.

ESP32 Smart Dustbin – Pin-Accurate Wiring 5V 2A supply +5V to ESP32 VIN, both HC-SR04 VCC pins and servo red wire GND to ESP32 GND, both HC-SR04 GND pins and servo brown wire 470 µF capacitor across servo +5V and GND (long leg to +5V) Lid sensor (hand) TRIG to GPIO5 ECHO to 1 kΩ to GPIO18 2 kΩ from GPIO18 to GND (5V echo becomes 3.3V) Fill sensor (inside) TRIG to GPIO19 ECHO to 1 kΩ to GPIO23 2 kΩ from GPIO23 to GND Servo (lid) Orange (signal) wire to GPIO13 Red to +5V supply, brown to GND Full LED On-board LED on GPIO2: on when the bin is 85% full or more
Pin-accurate connection diagram for the ESP32 smart dustbin.

Mechanical Setup

  • Fix the servo at the back of the bin with an L-bracket so its horn pushes the lid up from the hinge side. A stiff wire or a small 3D-printed arm between the horn and the lid works well.
  • Stick the lid sensor on the front edge of the lid or bin body, facing forward and slightly upward, so it sees a hand but not people walking past.
  • Stick the fill sensor under the lid in the centre, facing straight down. Measure the distance from its face to the bin floor and put that number in BIN_DEPTH_CM.
  • Keep the ESP32 and wiring in a small box outside the bin, away from moisture.

Code

Install the esp32 by Espressif Systems board package version 3.x in the Arduino IDE (Boards Manager) and choose ESP32 Dev Module. The Wi-Fi, web server and mDNS libraries come with the board package, so nothing else is needed. Replace the Wi-Fi placeholders with your own network name and password, set BIN_DEPTH_CM for your bin, then upload.

/*
  ESP32 Smart Dustbin with Touchless Lid & Fill-Level Web Page
  ardiunoprojecthub.online - Project 52

  - HC-SR04 #1 (on the front of the lid) looks for a hand. When something
    comes closer than OPEN_CM, the servo opens the lid and keeps it open
    for LID_OPEN_MS after the hand goes away.
  - HC-SR04 #2 (under the lid, facing down) measures how full the bin is.
    It is read only while the lid is closed, so the reading is stable.
  - The ESP32 joins your Wi-Fi and serves a web page with a fill gauge,
    lid state, open counter and an "Open lid" button.
  - The on-board LED turns on when the bin is FULL_PERCENT full or more.

  Wiring (ESP32 DevKit V1, 30-pin):
    Lid sensor  : VCC -> VIN (5V), GND -> GND, TRIG -> GPIO5,
                  ECHO -> 1k -> GPIO18, with 2k from GPIO18 to GND
    Fill sensor : VCC -> VIN (5V), GND -> GND, TRIG -> GPIO19,
                  ECHO -> 1k -> GPIO23, with 2k from GPIO23 to GND
    Servo       : red -> 5V supply, brown -> GND, orange (signal) -> GPIO13
    Full LED    : on-board LED on GPIO2
    Power the board and servo from a 5V 2A supply, grounds common.

  No extra libraries are needed with ESP32 core 3.x: the servo pulse is
  made with the built-in LEDC PWM (ledcAttach / ledcWrite).
*/
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

// ---- Wi-Fi (replace the placeholders) ----
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

// ---- Pins ----
#define LID_TRIG   5
#define LID_ECHO   18
#define FILL_TRIG  19
#define FILL_ECHO  23
#define SERVO_PIN  13
#define LED_PIN    2

// ---- Settings ----
const float OPEN_CM        = 20.0;   // hand distance that opens the lid
const unsigned long LID_OPEN_MS = 4000; // stay open this long after the hand leaves
const float BIN_DEPTH_CM   = 30.0;   // distance from fill sensor to the bin floor (empty bin)
const float FULL_GAP_CM    = 4.0;    // distance at which we call the bin 100 % full
const int   FULL_PERCENT   = 85;     // LED and web warning above this
const int   ANGLE_CLOSED   = 0;      // adjust to your lid hinge
const int   ANGLE_OPEN     = 100;

// Servo PWM: 50 Hz, 14-bit resolution (20 ms period = 16384 steps)
const int SERVO_MIN_US = 500;
const int SERVO_MAX_US = 2400;

WebServer server(80);

bool lidOpen = false;
unsigned long lastHandMs = 0;
unsigned long lastFillMs = 0;
int fillPercent = 0;
float fillDistance = BIN_DEPTH_CM;
unsigned long openCount = 0;

void servoWrite(int angle) {
  angle = constrain(angle, 0, 180);
  int us = map(angle, 0, 180, SERVO_MIN_US, SERVO_MAX_US);
  uint32_t duty = (uint32_t)us * 16384UL / 20000UL;
  ledcWrite(SERVO_PIN, duty);
}

// Returns distance in cm, or -1 if no echo within ~4 m
float readDistance(int trig, int echo) {
  digitalWrite(trig, LOW);
  delayMicroseconds(3);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  unsigned long t = pulseIn(echo, HIGH, 25000UL);
  if (t == 0) return -1;
  return t * 0.0343 / 2.0;
}

// Median of 5 readings to ignore odd echoes
float readMedian(int trig, int echo) {
  float v[5];
  int n = 0;
  for (int i = 0; i < 5; i++) {
    float d = readDistance(trig, echo);
    if (d > 0) v[n++] = d;
    delay(30);
  }
  if (n == 0) return -1;
  for (int i = 1; i < n; i++) {          // simple insertion sort
    float k = v[i]; int j = i - 1;
    while (j >= 0 && v[j] > k) { v[j + 1] = v[j]; j--; }
    v[j + 1] = k;
  }
  return v[n / 2];
}

void openLid() {
  if (!lidOpen) {
    servoWrite(ANGLE_OPEN);
    lidOpen = true;
    openCount++;
    Serial.println("Lid opened");
  }
  lastHandMs = millis();
}

void closeLid() {
  servoWrite(ANGLE_CLOSED);
  lidOpen = false;
  Serial.println("Lid closed");
}

void updateFill() {
  float d = readMedian(FILL_TRIG, FILL_ECHO);
  if (d < 0) return;                      // keep the last good value
  fillDistance = d;
  float pct = (BIN_DEPTH_CM - d) * 100.0 / (BIN_DEPTH_CM - FULL_GAP_CM);
  fillPercent = constrain((int)(pct + 0.5), 0, 100);
  digitalWrite(LED_PIN, fillPercent >= FULL_PERCENT ? HIGH : LOW);
  Serial.printf("Fill: %.1f cm -> %d %%\n", d, fillPercent);
}

// ---- Web page (stored in flash) ----
const char PAGE[] PROGMEM = R"HTML(
<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Smart Dustbin</title>
<style>
body{font-family:Arial,sans-serif;text-align:center;background:#f4f6f8;margin:0;padding:20px}
.card{background:#fff;max-width:340px;margin:auto;border-radius:14px;padding:20px;box-shadow:0 2px 8px #0002}
.bar{height:26px;background:#e0e0e0;border-radius:13px;overflow:hidden;margin:12px 0}
#fill{height:100%;width:0;background:#43a047;transition:width .5s}
#pct{font-size:48px;font-weight:bold;margin:6px 0}
button{font-size:18px;padding:10px 24px;border:0;border-radius:8px;background:#1565c0;color:#fff}
.warn{color:#c62828;font-weight:bold}
</style></head><body><div class="card">
<h2>Smart Dustbin</h2>
<div id="pct">--%</div>
<div class="bar"><div id="fill"></div></div>
<p id="state">Loading...</p>
<p>Lid: <b id="lid">-</b> &middot; Opened <b id="count">0</b> times</p>
<button onclick="fetch('/open')">Open lid</button>
</div>
<script>
function tick(){fetch('/data').then(r=>r.json()).then(d=>{
 document.getElementById('pct').textContent=d.fill+'%';
 var f=document.getElementById('fill');f.style.width=d.fill+'%';
 f.style.background=d.fill>=d.full?'#c62828':(d.fill>=50?'#fb8c00':'#43a047');
 var s=document.getElementById('state');
 if(d.fill>=d.full){s.textContent='Bin is full, please empty it';s.className='warn';}
 else{s.textContent='Space left: about '+(100-d.fill)+'%';s.className='';}
 document.getElementById('lid').textContent=d.lid?'Open':'Closed';
 document.getElementById('count').textContent=d.opens;
}).catch(()=>{});}
tick();setInterval(tick,2000);
</script></body></html>
)HTML";

void handleRoot() { server.send_P(200, "text/html", PAGE); }

void handleData() {
  char json[96];
  snprintf(json, sizeof(json), "{\"fill\":%d,\"dist\":%.1f,\"lid\":%s,\"opens\":%lu,\"full\":%d}",
           fillPercent, fillDistance, lidOpen ? "true" : "false", openCount, FULL_PERCENT);
  server.send(200, "application/json", json);
}

void handleOpen() {
  openLid();
  server.send(200, "text/plain", "OK");
}

void setup() {
  Serial.begin(115200);
  pinMode(LID_TRIG, OUTPUT);
  pinMode(FILL_TRIG, OUTPUT);
  pinMode(LID_ECHO, INPUT);
  pinMode(FILL_ECHO, INPUT);
  pinMode(LED_PIN, OUTPUT);

  ledcAttach(SERVO_PIN, 50, 14);          // ESP32 core 3.x API
  closeLid();

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to Wi-Fi");
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 20000) {
    delay(400);
    Serial.print(".");
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("\nOpen http://");
    Serial.println(WiFi.localIP());
    if (MDNS.begin("smartbin")) Serial.println("or http://smartbin.local");
  } else {
    Serial.println("\nWi-Fi not connected: the lid still works offline");
  }

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.on("/open", handleOpen);
  server.begin();
  updateFill();
}

void loop() {
  server.handleClient();

  // Hand detection, about 10 times a second
  static unsigned long lastLid = 0;
  if (millis() - lastLid > 100) {
    lastLid = millis();
    float d = readDistance(LID_TRIG, LID_ECHO);
    if (d > 2 && d < OPEN_CM) openLid();
  }

  // Close after the hand has gone for LID_OPEN_MS
  if (lidOpen && millis() - lastHandMs > LID_OPEN_MS) {
    closeLid();
    lastFillMs = millis() - 4000;         // measure fill 1 s after closing
  }

  // Fill level every 5 s, only when the lid is closed
  if (!lidOpen && millis() - lastFillMs > 5000) {
    lastFillMs = millis();
    updateFill();
  }
}

Testing

  • Open the Serial Monitor at 115200 baud and wait for “Open http://192.168.x.x”.
  • Wave your hand 10 to 15 cm in front of the lid sensor: the lid should open and close again about 4 seconds after you move away.
  • With the bin empty, check that the Serial Monitor shows a fill distance close to BIN_DEPTH_CM and about 0 percent.
  • Put a box or a stack of books inside and confirm the percentage goes up on the web page within about 5 seconds of the lid closing.
  • Tap Open lid on the phone page and make sure the lid opens.

Troubleshooting

ProblemFix
ESP32 resets when the lid opensThe servo current spike is pulling the 5V rail down. Use a 2A adapter, add the 470 µF capacitor at the servo, and keep the servo ground wire short.
Distance always reads -1 or 0Check the ECHO divider: 1 kΩ from ECHO to the GPIO and 2 kΩ from the GPIO to GND. Make sure the sensor VCC really has 5V.
Lid opens by itselfThe lid sensor sees a wall or the floor. Angle it upward or lower OPEN_CM to 12 to 15 cm.
Fill level jumps aroundSoft rubbish like paper absorbs sound. Keep the sensor in the centre, away from the bin walls, and let the median filter work. Increase the check interval if needed.
Lid does not open fully or buzzesChange ANGLE_OPEN and ANGLE_CLOSED to suit your hinge, or use a metal-gear MG90S or MG996R for a heavy lid.
Web page does not loadThe phone must be on the same 2.4 GHz Wi-Fi. Use the IP address if smartbin.local does not work on your phone.

Ideas to Extend

  • Send a phone notification with ntfy or Telegram when the bin crosses 85 percent.
  • Add a small OLED on the lid to show the fill level without a phone.
  • Run several bins in an office and show them all on one dashboard.

1 thought on “ESP32 Smart Dustbin with Touchless Lid & Fill-Level Web Page”

Leave a Comment