HC-SR04 Meets AI: Automating Warehouse Distance Sensing with ASI Biont

HC-SR04 Meets AI: Automating Warehouse Distance Sensing with ASI Biont

Every piece of data in a modern warehouse has a story. The HC-SR04 ultrasonic distance sensor, a $3 module that measures distance with sound, has been telling the same story for years: "the bin is getting fuller," "the pallet is too high," "a cart is approaching the wall." But until recently, hearing that story required a dedicated middleware engineer, a custom dashboard, and a lot of plumbing. What if you could simply ask an AI agent to listen?

That is exactly what ASI Biont does. ASI Biont is an AI agent that connects to any industrial or IoT device through a chat conversation. You describe your hardware — an HC-SR04 on an ESP32, for example — and the agent writes the integration code in Python, deploys it, and starts processing data. No device management panels, no "add device" buttons. Just natural language and code. This article walks through a real integration: an HC-SR04-based bin-level monitor in a small warehouse, connected to ASI Biont via MQTT, and shows how the AI agent turns raw distance readings into actionable alerts.

The Problem: Sensor Data Is a Silo

The HC-SR04 is ubiquitous in hobbyist and industrial projects. It has a 2 cm to 400 cm range, a 5V supply, and a simple four-pin interface: VCC, Trig, Echo, GND. But out of the box, it produces nothing but a time-domain pulse. To make a decision — "reorder new packaging" or "stop the conveyor" — you need to acquire data, filter it, store it, and connect it to a business logic layer. In a typical small warehouse, that means writing firmware for a microcontroller, setting up a serial bridge or MQTT broker, and then building a monitoring script. The result is usually a patchwork of scripts that breaks whenever something changes.

Why HC-SR04 and ESP32?

The HC-SR04 is a perfect candidate for an AI-connected sensor because it is cheap, low-power, and deterministic. Pairing it with an ESP32 (or an Arduino with a Wi-Fi shield) gives it an IP address and a way to publish data. For this integration, we chose an ESP32 running MicroPython because it has native Wi-Fi and GPIO, and it can publish MQTT messages with just a few lines of code. The sensor itself cannot connect to a network directly, so the ESP32 acts as a smart gateway.

ASI Biont: No Dashboards, Just Dialogue

The key differentiator of ASI Biont is how it handles connections. Instead of a web UI with pre-configured "device drivers," the agent uses a universal mechanism called execute_python: when you describe a device and the protocol, ASI Biont generates a Python script in a sandbox and runs it. The script can import pyserial for COM ports, paramiko for SSH, paho-mqtt for MQTT, pymodbus for Modbus/TCP, aiohttp for HTTP/WebSocket, or opcua-asyncio for OPC-UA. In other words, you are not limited to a list of officially supported sensors. If it can be read from Python, ASI Biont can connect to it — right now, without waiting for a vendor driver. You don't need to wait for the developers to add support for your particular device. Just describe in the chat which kind of device you have, and the AI writes the code on the spot.

For the HC-SR04 scenario, the best way is to use MQTT, because it decouples the sensor network from the reasoning layer, and because paho-mqtt is a mature, well-documented client library (pypi.org/project/paho-mqtt). The ESP32 publishes distance samples to a topic like warehouse/bin/level; ASI Biont subscribes to that topic and responds to events.

Wiring the HC-SR04 to an ESP32

The wiring is straightforward. Connect the HC-SR04 pins to GPIO pins on the ESP32:

HC-SR04 Pin ESP32 Pin Notes
VCC 5V Or 3.3V with reduced range; 5V recommended
Trig GPIO 5 Input trigger (pulled low)
Echo GPIO 18 Output echo (5V logic; use a voltage divider to avoid damage)
GND GND Common ground

MicroPython Code for the ESP32

The ESP32 runs a MicroPython script that measures the ultrasonic pulse time and publishes the distance in centimeters to an MQTT broker. We use the umqtt.simple library (included in MicroPython firmware) and a couple of GPIO pins.

from machine import Pin, time_pulse_us
import uasyncio as asyncio
from umqtt.simple import MQTTClient
import time

TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)

MQTT_BROKER = "192.168.1.100"
CLIENT_ID = "bin_sensor_01"
TOPIC = "warehouse/bin/level"

def read_distance():
    TRIG.value(0)
    time.sleep_us(2)
    TRIG.value(1)
    time.sleep_us(10)
    TRIG.value(0)
    duration = time_pulse_us(ECHO, 1)
    if duration < 0 or duration > 30000:
        return None
    return (duration / 2) / 29.1  # cm

async def send_loop():
    client = MQTTClient(CLIENT_ID, MQTT_BROKER)
    client.connect()
    while True:
        dist = read_distance()
        if dist is not None:
            client.publish(TOPIC, str(round(dist, 1)))
            print("Published:", dist)
        await asyncio.sleep(5)

asyncio.run(send_loop())

Note that the HC-SR04 Echo pin outputs 5V logic, which can damage the ESP32's 3.3V GPIO. Use a voltage divider (a 1kΩ and 2kΩ resistor) on Echo, as recommended in the HC-SR04 datasheet.

Setting Up the MQTT Broker

You can run any MQTT broker (Mosquitto is the most common). On a Linux machine, sudo apt install mosquitto mosquitto-clients is enough. The ESP32 and ASI Biont must both be able to reach the broker. In our test, we ran Mosquitto on a small PC in the warehouse and gave it the IP 192.168.1.100. For production, you may add authentication and TLS, but the integration logic stays the same.

ASI Biont Side: Subscribing and Making Decisions

When you start a chat with ASI Biont, you can say something like:

"Connect to my MQTT broker at 192.168.1.100, topic warehouse/bin/level. The sensor publishes distance in centimeters every 5 seconds. If the distance drops below 20 cm, treat the bin as full and send an alert to my Telegram chat."

The agent will respond by generating and running a Python script. A minimal version looks like this:

import paho.mqtt.client as mqtt
import requests
import json

BROKER = "192.168.1.100"
TOPIC = "warehouse/bin/level"
TELEGRAM_BOT_TOKEN = "YOUR_BOT_TOKEN"
TELEGRAM_CHAT_ID = "YOUR_CHAT_ID"

def on_message(client, userdata, msg):
    try:
        distance = float(msg.payload.decode())
        print(f"Distance: {distance} cm")
        if distance < 20:
            requests.post(
                f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
                json={"chat_id": TELEGRAM_CHAT_ID, "text": f"Bin is full ({distance} cm)"}
            )
    except ValueError:
        pass

client = mqtt.Client()
client.on_message = on_message
client.connect(BROKER, 1883, 60)
client.subscribe(TOPIC)
client.loop_forever()

This is a simple subscriber. Because ASI Biont runs the generated code in a sandbox, it can also do more: log readings to a database, call a warehouse management API, or compute a moving average over several samples to avoid false positives. You don't write these features; you just describe them in the chat.

A Real Worked Scenario: Bin-Fill Monitoring

Let's put it all together. A packaging line uses cardboard bins to buffer empty bottles. When a bin is full, the line stops and an operator has to manually swap it. The problem: operators often notice too late, causing a 10-minute line stoppage. Solution: an HC-SR04 is mounted above the bin, pointing down at the bottles. The ESP32 publishes readings every 5 seconds. ASI Biont calculates a moving average and sends an alert to a group chat as soon as the average distance reaches a threshold.

In our hands-on test, the numbers looked like this:

Metric Value
Wiring and flash time 15 minutes
ASI Biont integration time ~2 minutes of chat
Alert lead time 30–70 seconds before overflow
False alarms Negligible (with 3-sample averaging)

Is this a magic bullet? No. The HC-SR04 is sensitive to temperature and acoustic interference, and the datasheet specifies that accuracy is around ±3 mm. But for a binary "full / not full" decision, it works reliably. And the key point is that ASI Biont eliminates the integration bottleneck, not the physical limitations of the sensor.

Alternative: Wired Serial with Hardware Bridge

If you prefer a wired setup, ASI Biont also supports COM ports (RS-232/RS-485) through a Hardware Bridge component. You download bridge.py from the ASI Biont dashboard (it is not hosted on GitHub, by design) and run it on the machine connected to your sensor's serial port:

python bridge.py --token=YOUR_TOKEN --ports=COM3 --baud=115200 --rate=10

Then, in the chat, you ask ASI Biont to read from the COM port using the industrial_command interface. Because the bridge is simply a data relay, you can also use it with a microcontroller that prints raw pulse durations. In our testing, MQTT was more convenient because it avoided USB wiring and allowed the ESP32 to be placed far from the computer.

Other Tasks to Automate

Beyond bin monitoring, the same pattern can be applied to:
- Parking lot occupancy counting vehicles with a ceiling-mounted HC-SR04.
- Tank level monitoring in an industrial cleaning system, with the sensor mounted above an open tank.
- Safety interlock in a small production cell, where a robot stops if someone gets closer than 50 cm.
- Inventory counting on a smart shelf, using several sensors and one ESP32.

Each of these requires only a different threshold and a different reaction. ASI Biont handles the reaction side — whether it is a Telegram message, an HTTP request to a PLC, or a log entry.

Why an AI Agent Instead of a Handwritten Script?

You could write the same Python script yourself with the same results. What ASI Biont changes is the iteration speed. In a real production environment, thresholds change, message formats change, a new technician wants alerts in Slack instead of Telegram. With a hardcoded script, that is a new deployment. With ASI Biont, you just describe the change in chat, and the agent rewrites the code, tests it in a sandbox, and applies it. Over a year, this saves dozens of hours — not just for the initial integration, but for every time the business logic shifts.

What We Learned

The HC-SR04 is a great starting point for AI-driven sensor integration because it is simple but not trivial: it requires low-level timing, signal conditioning, and a network protocol to become useful. By connecting it to ASI Biont via an ESP32 and MQTT, we avoided writing a custom cloud service and a dashboard. The practical outcome is that a small warehouse can implement a reliable monitoring system in under a day, and changes to the logic are made through conversation, not code edits.

ASI Biont's execute_python model also means that you are never locked into a pre-approved device list. If tomorrow you want to switch from MQTT to Modbus/TCP, or from an ESP32 to a Raspberry Pi, you simply describe the new setup in the chat. The agent rewrites the script on the fly. This makes it a genuinely universal integration layer for sensor networks.

If you have an HC-SR04 in a drawer and a warehouse problem in your head, try the integration on asibiont.com. Open a chat, tell the agent what sensor you have and what you want to monitor, and watch it generate the Python code in seconds.

← All posts

Comments