How to Integrate HC-SR04 Ultrasonic Distance Sensor with AI Agent ASI Biont: ESP32, MQTT, and Automation Scenarios

How to Integrate HC-SR04 Ultrasonic Distance Sensor with AI Agent ASI Biont: ESP32, MQTT, and Automation Scenarios

Imagine a warehouse where a robotic arm stops automatically when a bin is full. Or a parking system that alerts you via Telegram when a spot is occupied. Or a robot that avoids obstacles without a single line of hand-coded logic. All this is possible by connecting a humble $2 sensor — the HC-SR04 ultrasonic distance module — to an AI agent that writes the integration code for you. In this guide, you'll learn how to pair HC-SR04 with ASI Biont using an ESP32 and MQTT, automate tasks with thresholds, and see real-world scenarios — all without writing complex boilerplate.

Why Connect HC-SR04 to an AI Agent?

The HC-SR04 is a classic ultrasonic distance sensor: it emits a 40 kHz pulse, measures the echo return time, and outputs distance (2 cm to 400 cm, ±3 mm accuracy). By itself, it's just raw data. Connected to an AI agent like ASI Biont, it becomes part of a decision-making system. The AI can:
- Read distance values continuously
- Detect thresholds (e.g., distance < 10 cm means "obstacle")
- Trigger actions: send alerts, control motors, log data
- Adapt thresholds based on context (e.g., night mode vs day mode)

ASI Biont does this by generating Python code on the fly — you just describe your setup in natural language.

Connection Method: MQTT via ESP32

For HC-SR04, the most practical integration is via MQTT using an ESP32 (or ESP8266) microcontroller. Here's why:
- ESP32 has built-in Wi-Fi and two timers for precise pulse timing
- MQTT is lightweight, ideal for IoT sensors
- ASI Biont's execute_python environment has paho-mqtt pre-installed
- No need for a PC to run bridge software — the ESP32 publishes data directly to a broker

Alternatively, you could use Hardware Bridge (COM port) if the ESP32 is connected via USB, but MQTT is wireless and scalable.

Wiring Diagram: HC-SR04 to ESP32

HC-SR04 Pin ESP32 Pin
VCC 5V (or 3.3V — check your module)
GND GND
TRIG GPIO 5
ECHO GPIO 18 (via voltage divider, 5V → 3.3V)

Important: HC-SR04 is a 5V device. The ECHO pin outputs 5V, which can damage ESP32's 3.3V GPIO. Use a voltage divider (two resistors: 1kΩ and 2.2kΩ) or a level shifter. Connect ECHO through the divider to GPIO 18.

Step-by-Step Integration

1. Flash ESP32 with MicroPython

Install MicroPython on your ESP32 (instructions at micropython.org). Then upload this script via Thonny or ampy. It reads distance and publishes to an MQTT broker.

# ESP32 MicroPython code: HC-SR04 + MQTT
import machine
import time
import network
import ubinascii
from umqtt.simple import MQTTClient

# Wi-Fi credentials
WIFI_SSID = "YourWiFi"
WIFI_PASS = "YourPassword"

# MQTT broker (use your broker IP, e.g., test.mosquitto.org or local)
MQTT_BROKER = "test.mosquitto.org"
MQTT_TOPIC = "sensor/hc-sr04/distance"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())

# HC-SR04 pins
TRIG = machine.Pin(5, machine.Pin.OUT)
ECHO = machine.Pin(18, machine.Pin.IN)

def measure_distance():
    # Send 10us pulse
    TRIG.off()
    time.sleep_us(2)
    TRIG.on()
    time.sleep_us(10)
    TRIG.off()
    # Wait for echo
    while ECHO.value() == 0:
        pulse_start = time.ticks_us()
    while ECHO.value() == 1:
        pulse_end = time.ticks_us()
    pulse_duration = time.ticks_diff(pulse_end, pulse_start)
    distance = pulse_duration * 0.0343 / 2  # cm
    return distance

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect(WIFI_SSID, WIFI_PASS)
        while not wlan.isconnected():
            time.sleep(1)
    print("WiFi connected")

connect_wifi()
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.connect()

while True:
    dist = measure_distance()
    print("Distance:", dist, "cm")
    client.publish(MQTT_TOPIC, str(dist))
    time.sleep(2)  # read every 2 seconds

Upload this to ESP32. It will publish distance in cm every 2 seconds to topic sensor/hc-sr04/distance.

2. Connect ASI Biont to MQTT Broker

Now, in the ASI Biont chat, describe what you want:

"Connect to MQTT broker at test.mosquitto.org, subscribe to topic sensor/hc-sr04/distance. Read the distance value. If distance < 10 cm, send me a Telegram alert. If distance > 100 cm, log 'safe'. Run every 5 seconds."

ASI Biont will generate and execute this Python script in its sandbox:

import paho.mqtt.client as mqtt
import time
import requests

# Telegram config (example using bot API)
TELEGRAM_TOKEN = "YOUR_BOT_TOKEN"
TELEGRAM_CHAT_ID = "YOUR_CHAT_ID"

def send_telegram(msg):
    url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
    payload = {"chat_id": TELEGRAM_CHAT_ID, "text": msg}
    requests.post(url, json=payload)

# MQTT callback
def on_message(client, userdata, msg):
    distance = float(msg.payload.decode())
    print(f"Received distance: {distance} cm")
    if distance < 10:
        alert = f"⚠️ Obstacle detected! Distance: {distance} cm"
        print(alert)
        send_telegram(alert)
    elif distance > 100:
        print("Safe zone")

# Connect to broker
client = mqtt.Client()
client.on_message = on_message
client.connect("test.mosquitto.org", 1883, 60)
client.subscribe("sensor/hc-sr04/distance")
client.loop_forever()  # runs until timeout (30s sandbox limit)

Note: Sandbox has a 30-second timeout. For long-running monitoring, you'd use a persistent cloud function or a separate bridge. But for testing and one-shot alerts, this works perfectly.

Real-World Scenarios

1. Warehouse Bin Level Monitoring

Setup: HC-SR04 mounted above a storage bin. ESP32 publishes distance. ASI Biont subscribes and when distance drops below 15 cm (bin full), it sends an email via SendGrid API to the logistics manager.

AI prompt: "When distance < 15 cm, send email to warehouse@company.com with subject 'Bin full' and body containing current distance."

2. Automated Parking Spot Detection

Setup: Sensor mounted on ceiling above a parking spot. When a car is present, distance decreases from 200 cm to ~50 cm. ASI Biont updates a Google Sheet via HTTP API to show spot status.

AI prompt: "If distance < 100 cm, mark parking spot as occupied in Google Sheets. If > 100 cm, mark as free. Update every 10 seconds."

3. Robot Collision Avoidance

Setup: HC-SR04 on a robot chassis. ESP32 publishes distance. ASI Biont reads and sends a command back via MQTT to stop motors if obstacle < 20 cm.

AI prompt: "If distance < 20 cm, publish 'STOP' to topic robot/command. If distance > 30 cm, publish 'GO'."

Why This Matters: No Manual Coding

Traditional integration would require you to write:
- MQTT client code on both sides
- Threshold logic
- Error handling
- Reconnection logic

With ASI Biont, you just describe the goal. The AI writes, debugs, and executes the code. It's like having a senior embedded engineer on call 24/7.

Advanced: Using Hardware Bridge for Direct COM Port

If you prefer a wired connection (ESP32 connected via USB), use Hardware Bridge. Download bridge.py from the ASI Biont dashboard (Devices → Create API Key → Download bridge). Run:

pip install pyserial requests websockets
python bridge.py --token=YOUR_TOKEN --ports=COM3 --baud 115200

Then in chat: "Send command to ESP32 via COM3 to read distance." The AI uses industrial_command(protocol='serial://', command='serial_write_and_read', data='DIST?\n'). The ESP32 firmware must respond to that command.

Conclusion

HC-SR04 is a simple sensor, but paired with an AI agent, it becomes the eyes of your automation system. Whether you're monitoring a warehouse, automating a parking lot, or building a robot, ASI Biont lets you connect, control, and react without writing boilerplate. The sensor costs $2, the ESP32 costs $5, and the AI integration takes seconds.

Ready to connect your HC-SR04? Go to asibiont.com, start a chat with the AI agent, and describe your sensor setup. Watch as it generates the code and brings your distance data to life.

← All posts

Comments