ESP32 Smart Bin

Published:

I started this project with a simple idea: a bin that opens when my hand approaches and closes once I move away. It grew into a rechargeable ESP32 device that also estimates how full it is, accepts network commands, and works with Bob, my Raspberry Pi-based AI assistant.

The ESP32 runs the sensors and lid locally, so everyday operation continues when Bob or Wi-Fi is unavailable. Bob adds natural-language Telegram commands, dashboard chat and supported voice interaction, and proactive full-bin notifications.

Preview

Overhead view of the assembled Smart Bin showing the rim-mounted proximity sensor, ESP32 protoboard, servo, and installed 18650 battery
The assembled prototype, with hand detection at the rim and the electronics, servo, and rechargeable battery mounted behind it.

Starting With One Sensor

My first September prototype used an HC-SR04 ultrasonic sensor and a hobby servo on a breadboard. A nearby hand or object triggered the servo, which simulated opening the lid. I added delayed closing, a physical button, and an LED to check the basic interaction before assembling the bin.

Even getting that first test running involved practical debugging. An initial board-recognition problem came down to the USB cable: switching to a working data cable let me upload and inspect Serial readings. It was a reminder to check the physical connection before chasing firmware faults.

Giving Each Sensor a Clear Job

One measurement location could not conveniently detect a hand outside the bin and measure contents inside it. I added a VL53L0X time-of-flight sensor at the rim for hand detection and moved the HC-SR04 to the upper interior to measure the gap above the contents.

I tuned the proximity logic to require a target within 180 mm for 150 ms before opening. The area becomes clear at 250 mm or beyond, giving the system hysteresis so small changes around the trigger distance do not make it repeatedly switch state. Once clear, a three-second closing timer starts. A returning hand cancels that timer.

Open-space timeouts and distances beyond the 500 mm tracked range are treated as clear. Zero readings are invalid, and three consecutive invalid readings are required before the ToF state is marked invalid. Invalid readings cannot initiate opening or start a closing timer.

Two HC-SR04 ultrasonic transducers mounted beneath the Smart Bin lid frame and facing the interior
The HC-SR04 looks into the bin to estimate fill height while the separate ToF module handles approaching hands.

The fill estimate uses provisional reference distances of 28 cm for empty and 4 cm for full. The calculation is (28 - distance_cm) * 100 / (28 - 4), clamped to 0-100%. A 16 cm gap therefore corresponds to about 50%. Missing echoes and readings outside 2-400 cm produce an unknown result instead of a false full reading.

This is a height estimate at the sensor's aim point. Uneven contents and different surfaces affect the reading, so final enclosure calibration and accuracy testing remain part of the next iteration.

Assembling the Circuit and Lid

I moved the controller and local controls onto soldered protoboard and fitted the sensors, servo linkage, battery holder, and power board around the lid assembly. The photographs show this assembled prototype. The mounts and linkage gave me a practical way to bring the electronics and moving lid together.

Close-up of the Smart Bin ESP32 protoboard, pushbutton, status LED, servo linkage, power board, and battery wiring
The controller and controls on protoboard beside the servo and rechargeable power hardware.
ComponentRole
ESP32 development boardLocal control, Wi-Fi, JSON API, and OTA updates
VL53L0XShort-range hand detection over I2C
HC-SR04Interior distance measurement for fill estimation
Micro servo and linkageLid movement
Pushbutton and LEDLocal lid toggle and commanded-state indication
18650 cell, holder, USB-C power board, and rocker switchInstalled rechargeable power and power switching
Protoboard, wiring, and passive componentsCircuit assembly and ECHO voltage divider
Raspberry Pi 5 running Bob/OpenClawAssistant commands and background notification monitoring

Signal Connections

SignalESP32 connection
VL53L0X SDA / SCLGPIO 21 / GPIO 22
HC-SR04 TRIG / ECHOGPIO 5 / GPIO 18, with an external voltage divider on ECHO
Servo signalGPIO 13
Status LEDGPIO 2
PushbuttonGPIO 4 to ground, using INPUT_PULLUP

The controller, sensors, and servo share ground. The HC-SR04's 5 V ECHO signal needs the divider before reaching the ESP32's 3.3 V GPIO. This table describes the signal wiring. The final power board's detailed schematic is still to be established.

Working Towards Rechargeable Power

The early bench setup used a shared 5 V supply for the ESP32 and servo. I then tried a USB power-bank demonstration and investigated a TP4056/MT3608 arrangement while troubleshooting how to power the assembled device. Power regulation became its own engineering task alongside sensing and software.

The assembled bin now runs from an installed rechargeable 18650 cell and charges through its rear USB-C port. I still need to establish the exact charging-board specifications, regulation and protection details, charge time, and measured battery runtime.

Rear of the assembled Smart Bin showing its USB-C charging opening and rocker power switch
Rear access to USB-C charging and the rocker power switch.

Firmware That Keeps Local Control Running

I developed the Arduino firmware in PlatformIO and split sensor handling, the debounced button, lid control, and networking into separate classes. Configuration holds the pin assignments, timings, and calibration values, while a shared state definition keeps commands and status consistent.

Most work is scheduled with millis(). Hand readings update every 100 ms and fill measurements every 250 ms. The ultrasonic echo measurement can still block for up to 30 ms, which is a useful limit to keep in mind when describing the loop's responsiveness. The button has a 40 ms debounce.

I also made the distinction between temporary and persistent commands explicit. Ordinary open and close actions leave automatic sensing active. Hold-open and hold-closed suspend automatic movement until I select auto again. Pressing the physical button exits a hold and toggles the lid. The LED follows the commanded lid state, and the servo avoids redundant writes. Independent physical lid-position feedback remains a future improvement.

The recorded firmware 1.2.0 builds passed for both USB and OTA PlatformIO environments. They used about 15.3% of available RAM and 65.9% of the standard OTA application slot. ESP32Servo and Pololu's VL53L0X library provide the servo and ToF interfaces.

Adding Wi-Fi, a Local API, and OTA

Once the local behaviour worked, I added station-mode Wi-Fi, mDNS discovery, and a JSON API. The ESP32 retries dropped Wi-Fi roughly every 15 seconds while its local sensor and lid logic continues. Status includes firmware version, operating mode, commanded lid state, sensor validity, fill estimate, signal strength, and uptime.

RequestPurpose
GET /healthCheck device availability
GET /statusRead the current device and sensor state
POST /open, POST /closeTemporary lid actions within automatic mode
POST /hold-open, POST /hold-closedPersistent manual modes
POST /autoReturn to automatic operation

Read endpoints are available on the local network. State-changing requests require an X-API-Key, and the firmware disables changes and OTA when its device token is missing or still a placeholder. API-key authentication controls who can act, but the local HTTP interface does not encrypt traffic.

Authenticated OTA made later iterations easier. I verified it by changing the running version from 1.1.0 to 1.1.1, then uploading 1.2.0 and checking its live status and command behaviour. A host-side callback and firewall issue initially blocked uploads. Fixing that connection completed the update path, with USB retained for recovery.

Connecting the Bin to Bob

On the Raspberry Pi, I added a helper that maps a fixed set of bin commands onto the ESP32 API. It loads credentials privately, preserves invalid sensor states, and reports unavailable devices and authentication failures. Both Bob and the background monitor use this same interface.

Through Bob's existing OpenClaw Telegram channel, I can ask questions such as “How full is the bin?” or request “Open the bin”, “Close the bin”, and “Put the bin back in automatic mode”. These paths have worked in real interactions. During an offline case, Bob reported the bin as unreachable.

Bob's dashboard accepts Smart Bin commands through its existing chat and supported voice/chained-conversation paths. Recognised bin phrases go through a local command handler and the same helper, reducing the delay for explicit requests. Dashboard records show status, fill, temporary opening, hold-open, and return-to-auto actions. Broader voice coverage, including GPT Live delegation, still needs end-to-end verification.

Getting a Message Before the Bin Overflows

I wanted the system to tell me when attention was needed. A separate Raspberry Pi watcher checks fill roughly every ten minutes after a two-minute boot delay. A valid reading of 90% or more triggers a Telegram alert.

The watcher latches that alert so each check does not send another message. A valid reading below 75% resets it, while exactly 75%, invalid readings, and offline checks retain the latch. It stores state atomically and restores its previous state if delivery fails so a later check can retry.

Real alerts have reached my Telegram channel. Successful sends were recorded at 90% on 2 October, 94% on 9 October, and 96% on 16 October 2026. That completed the journey from reacting to a hand locally to proactively notifying me through my assistant.

Testing and Lessons Learned

I tested the project in layers. Early hands-on and Serial tests established proximity opening, delayed closing, the button, and LED. The dual-sensor tests then established ToF-triggered movement. Live 1.2.0 API tests verified temporary actions, both firmware-level hold modes, return to auto, and the three-second close timing. An unauthenticated request returned 401 and left the commanded state unchanged.

The final 1.2.0 API session did not separately reverify a hand-trigger event, button, or LED. At the Pi layer, Telegram status/open/close/auto and dashboard hold-open have execution records. Persistent hold-closed works at the firmware layer, while live Pi-side hold-closed still needs confirmation.

Automated checks covered the helper, alert watcher, command classification, and routing consistency. Recorded runs include nine passing command-handler checks and four passing parity checks. I have not established one final run covering all 34 current Smart Bin-focused test methods.

The most instructive challenges crossed hardware and software boundaries: USB cables and occupied Serial ports, noisy distance readings, power experiments, an OTA callback problem, and intermittent hostname resolution between the Pi and bin. The cause of those resolution failures remains unresolved. Keeping the ESP32 autonomous and reporting unknown data explicitly made those failures easier to handle.


Source Code

I have released the actual ESP32 firmware on GitHub under the MIT licence. Built using PlatformIO and the Arduino framework, it includes the sensor handling, lid control, local API, and OTA update support described above.

This excerpt from src/main.cpp converts the ultrasonic distance into a fill percentage using the configured empty and full distances, then clamps the result to 0-100%. The caller checks measurement validity before using this function.

float calculateFillPercent(float distanceCm) {
  const float spanCm = FillCalibration::BIN_EMPTY_DISTANCE_CM -
                       FillCalibration::BIN_FULL_DISTANCE_CM;
  const float percentage =
      (FillCalibration::BIN_EMPTY_DISTANCE_CM - distanceCm) * 100.0F / spanCm;
  return constrain(percentage, 0.0F, 100.0F);
}

The excerpt shows one part of the firmware. You can view, download, or clone the complete project and follow its setup instructions on GitHub.

View the complete ESP32 Smart Bin source on GitHub

The Raspberry Pi, Bob, and OpenClaw integration is maintained separately and is outside the scope of this public ESP32 firmware repository.


What I Want to Improve Next

This build taught me how much work sits between a sensor demonstration and an assembled connected device. Reliable behaviour needed deliberate sensing rules, clear operating modes, a recoverable update process, and consistent handling of failures across the ESP32 and Raspberry Pi.

← Back to Projects