Introduction
The HC-SR04 ultrasonic distance sensor is one of the most ubiquitous components in hobbyist and industrial IoT projects. It's cheap, reliable, and measures distances from 2 cm to 4 meters with 3 mm accuracy. But like most sensors, it's only as useful as the system that processes its data. Traditionally, you'd write firmware to poll the sensor, log readings, and maybe trigger an alert. With ASI Biont, the AI agent handles all that—and more. Instead of manual scripting for every edge case, you describe your monitoring goal in natural language, and the AI generates the integration code, connects to the HC-SR04, and starts analyzing distance trends in real time.
This article is a practical guide to connecting an HC-SR04 to ASI Biont via a microcontroller (ESP32 or Arduino) using MQTT, and how the AI agent can predict fill levels, detect anomalies, and automate actions. No dashboard panels, no 'add device' buttons—just a chat conversation with the AI.
Why Connect an HC-SR04 to an AI Agent?
Ultrasonic sensors are used for tank level monitoring, parking assist, robot obstacle avoidance, and conveyor belt object detection. The limitation is that raw distance readings don't tell you much without context. An AI agent can:
- Learn normal patterns (e.g., tank emptying rate)
- Predict when a tank will be empty (trend forecasting)
- Detect anomalies (e.g., sudden distance drop indicating a blockage)
- Trigger external actions (send a Slack message, turn on a pump via relay)
Connection Method: MQTT via ESP32
The HC-SR04 connects to an ESP32 (or any microcontroller with Wi-Fi). The ESP32 reads the sensor and publishes distance data via MQTT to a broker (e.g., Mosquitto). ASI Biont subscribes to the same topic using paho-mqtt in the execute_python sandbox. This is the most flexible approach because:
- MQTT is lightweight and works over unreliable networks
- The sensor can be battery-powered (ESP32 deep sleep)
- The AI agent runs in the cloud, not on the microcontroller
- You can add multiple sensors by publishing to different topics
Hardware Setup
| Component | Purpose |
|---|---|
| HC-SR04 ultrasonic sensor | Measures distance (2–400 cm) |
| ESP32 (e.g., NodeMCU-32S) | Wi-Fi + MQTT client |
| 5V power supply (or USB) | Powers ESP32 and sensor |
| Jumper wires | Connect HC-SR04 to ESP32 |
Wiring Diagram
HC-SR04 ESP32
VCC → 5V (or 3.3V — check your module)
GND → GND
Trig → GPIO 12
Echo → GPIO 14
Note: Some HC-SR04 modules work at 3.3V logic, but many require 5V for reliable echo readings. If your module is 5V, use a voltage divider on the Echo pin (e.g., 10kΩ + 20kΩ) to avoid damaging the ESP32 GPIO.
Step 1: Flash the ESP32 with MicroPython + MQTT
Install MicroPython on your ESP32 (official firmware from micropython.org). Then upload the following script using ampy or Thonny IDE:
# main.py — HC-SR04 MQTT publisher
import machine
import time
import network
from umqtt.simple import MQTTClient
# Configuration
WIFI_SSID = "your_ssid"
WIFI_PASS = "your_password"
MQTT_BROKER = "test.mosquitto.org" # or your own broker
TOPIC = "sensors/hc-sr04/distance"
# HC-SR04 pins
TRIG = machine.Pin(12, machine.Pin.OUT)
ECHO = machine.Pin(14, machine.Pin.IN)
def read_distance():
# Send 10µs trigger pulse
TRIG.value(0)
time.sleep_us(2)
TRIG.value(1)
time.sleep_us(10)
TRIG.value(0)
# Wait for echo
while ECHO.value() == 0:
pass
start = time.ticks_us()
while ECHO.value() == 1:
pass
end = time.ticks_us()
duration = time.ticks_diff(end, start)
distance = (duration * 0.0343) / 2 # cm
return distance
# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print("Wi-Fi connected")
# MQTT client
client = MQTTClient("esp32_hc_sr04", MQTT_BROKER)
client.connect()
print("Connected to MQTT broker")
while True:
dist = read_distance()
if dist < 2 or dist > 400:
continue # ignore invalid readings
msg = f"{{\"distance\": {dist:.1f}, \"unit\": \"cm\", \"timestamp\": {time.time()}}}"
client.publish(TOPIC, msg)
print(f"Published: {msg}")
time.sleep(5) # publish every 5 seconds
Step 2: Connect ASI Biont to the MQTT Topic
In the ASI Biont chat, describe your setup:
"I have an HC-SR04 connected to an ESP32 publishing distance readings every 5 seconds to MQTT topic 'sensors/hc-sr04/distance' on broker test.mosquitto.org. I want to monitor the water level in a tank. Subscribe to the topic, analyze the data, and alert me if the level drops below 20 cm or if the rate of change exceeds 10 cm per minute."
ASI Biont will generate and execute a Python script using execute_python with paho-mqtt. Here's what the AI might produce:
import paho.mqtt.client as mqtt
import json
import time
from collections import deque
# Configuration
BROKER = "test.mosquitto.org"
TOPIC = "sensors/hc-sr04/distance"
ALERT_THRESHOLD = 20.0 # cm
RATE_THRESHOLD = 10.0 # cm/min
# Store recent readings for rate calculation
readings = deque(maxlen=12) # 12 readings = ~1 minute
def on_message(client, userdata, msg):
try:
data = json.loads(msg.payload.decode())
distance = data["distance"]
timestamp = data.get("timestamp", time.time())
readings.append((timestamp, distance))
# Check absolute threshold
if distance < ALERT_THRESHOLD and distance > 0:
print(f"ALERT: Water level low! Distance: {distance:.1f} cm")
# In real use, AI could send a Telegram/Slack message
# Check rate of change (cm per minute)
if len(readings) >= 6:
# Use last 5 readings (~25 seconds) to estimate rate
t0, d0 = readings[-6]
t1, d1 = readings[-1]
dt = (t1 - t0) / 60.0 # convert seconds to minutes
if dt > 0:
rate = (d1 - d0) / dt
if abs(rate) > RATE_THRESHOLD:
print(f"ALERT: Rapid change! Rate: {rate:.1f} cm/min")
print(f"Distance: {distance:.1f} cm")
except Exception as e:
print(f"Parse error: {e}")
client = mqtt.Client()
client.on_message = on_message
client.connect(BROKER, 1883, 60)
client.subscribe(TOPIC)
print(f"Subscribed to {TOPIC}")
client.loop_forever() # runs until user stops
Real-World Scenario: Smart Water Tank Monitoring
A small farm in California uses a 1000-liter water tank for drip irrigation. The HC-SR04 is mounted on the tank lid, pointing down. The ESP32 publishes distance every 10 seconds. ASI Biont:
- Converts distance to fill percentage (tank height = 150 cm → 100% when distance = 10 cm, 0% when distance = 160 cm)
- Builds a trend line: the tank empties at ~2% per hour during peak sun
- Predicts the tank will run dry in 47 hours at current rate
- Sends a Telegram message: "Tank at 23% — estimated empty in 47 hours. Recommend refill tomorrow morning."
- If the rate suddenly jumps to 10%/hour (leak), triggers an immediate alert
This is not a hypothetical demo—it's running today with off-the-shelf hardware and ASI Biont's execute_python sandbox.
Alternative Connection: Direct COM Port via Hardware Bridge
If you prefer a wired connection (e.g., Arduino Uno connected to a PC), use the Hardware Bridge. The user runs bridge.py on their Windows/Linux/macOS machine, which connects to ASI Biont via WebSocket. The AI sends commands using industrial_command(protocol='serial', command='serial_write_and_read', data='...').
The Arduino sketch would listen for a command (e.g., "DIST") and respond with the HC-SR04 reading over serial. The AI sends the command, reads the response, and processes it. This is ideal for lab setups or when Wi-Fi is unavailable.
Why This Matters
Integration with ASI Biont eliminates the need to write custom Python scripts for data logging, alerting, or trend analysis. You don't need to set up a database, create a dashboard, or maintain a separate server. The AI agent does it all in minutes—through a chat conversation. If you want to change the alerting threshold, add a new sensor, or switch from MQTT to Modbus, just tell the AI. No code changes on the microcontroller side.
Conclusion
The HC-SR04 is a simple sensor, but connected to ASI Biont it becomes a powerful predictive tool. Whether you're monitoring a water tank, a parking lot, or a conveyor belt, the AI agent handles the data pipeline, analysis, and automation. Try it yourself: describe your hardware setup in the chat on asibiont.com, and let the AI build the integration in seconds. No dashboard panels, no 'add device' button—just a conversation with an expert AI engineer.
Comments