HC-SR04 Meets AI: Build a Smart Distance Sensor with ASI Biont in 5 Minutes

Introduction

The HC-SR04 ultrasonic distance sensor is one of the most popular and affordable sensors in the maker community. With a price tag under $2 and a simple four-pin interface, it can measure distances from 2 cm to 4 meters with reasonable accuracy. But what if you could connect this humble sensor to an AI agent that not only reads the data but also makes intelligent decisions—sending alerts when a door opens, turning on lights when someone enters a room, or logging historical trends for security analytics?

This article is a practical integration guide. We will show you how to connect an HC-SR04 to an ESP32 microcontroller, then link it to the ASI Biont AI agent via MQTT. The AI will handle all the logic: parsing distance values, triggering actions, and storing data. No dashboards, no complex setup—just a chat conversation with the AI agent. Let's dive in.

Device Overview: HC-SR04

The HC-SR04 uses sonar (ultrasound) to measure distance. It sends out an 8-cycle burst of 40 kHz ultrasound and listens for the echo. The time between trigger and echo is proportional to distance. Typical accuracy is ±3 mm at ranges up to 2 m, and ±5 mm beyond that. It works best indoors with solid, flat targets.

Parameter Value
Operating Voltage 5V DC
Current Draw 15 mA (typical)
Range 2 cm – 400 cm
Resolution 0.3 cm
Measurement Angle 15° (cone)
Trigger Pin Digital input (10 µs pulse)
Echo Pin Digital output (pulse width)

The sensor is widely used in robotics, parking sensors, tank level monitoring, and security systems. However, standalone, it cannot do much beyond raw distance readings—you need a microcontroller to process the pulses and some logic to act on the data. That's where ASI Biont's AI agent comes in.

Why Connect HC-SR04 to an AI Agent?

A typical Arduino or ESP32 sketch can read the HC-SR04 and print the distance to the serial monitor. But what if you want to:
- Send a Telegram alert when the distance drops below 50 cm (e.g., someone enters a restricted area)?
- Log data every minute to a cloud database for trend analysis?
- Automatically turn on a relay when the measured level in a water tank falls below 30 cm?
- Combine distance data with other sensors (temperature, motion) for complex rules?

Writing all that logic from scratch requires coding skills, API integrations, and debugging. With ASI Biont, you simply describe what you need in natural language, and the AI agent writes the entire integration—from ESP32 firmware to cloud triggers—in seconds. The AI understands the HC-SR04 protocol, MQTT, and your use case, and produces production-ready code.

Integration Architecture

We will use the following setup:

  1. ESP32 with HC-SR04 connected to GPIO pins. The ESP32 runs a MicroPython script that reads the sensor and publishes distance values via MQTT to a broker.
  2. MQTT Broker (e.g., Mosquitto running on a Raspberry Pi or a free public broker like HiveMQ Cloud).
  3. ASI Biont AI agent — connects to the same MQTT broker, subscribes to the sensor topic, and executes logic (alerts, logging, control).
HC-SR04 → ESP32 (MicroPython) → MQTT Broker → ASI Biont AI Agent

The AI agent uses the execute_python tool (sandbox environment) to run a Python script with paho-mqtt. The script subscribes to the topic, receives distance data, and takes actions based on rules defined in the chat conversation. No hardware bridge is needed for MQTT; the AI communicates directly with the broker over the internet.

Wiring Diagram

Connecting the HC-SR04 to an ESP32 is straightforward:

HC-SR04 Pin ESP32 Pin
VCC 5V
GND GND
Trig GPIO 5
Echo GPIO 18

Important: The HC-SR04 is a 5V device, but the ESP32 GPIO pins are 3.3V tolerant. For reliable operation, use a voltage divider on the Echo pin (two resistors: 1kΩ to GND, 2.2kΩ from Echo to GPIO). Alternatively, many users report success by connecting Echo directly to a 3.3V pin, but this is not officially recommended. For this guide, we assume a direct connection with a voltage divider.

Step 1: ESP32 Firmware (MicroPython)

First, flash MicroPython to your ESP32 (instructions at micropython.org). Then upload the following script using a tool like ampy or Thonny:

# hc_sr04_mqtt.py
import machine
import time
import network
from umqtt.simple import MQTTClient

# Configuration
WIFI_SSID = "your_wifi"
WIFI_PASS = "your_password"
MQTT_BROKER = "broker.hivemq.com"  # or your own broker
MQTT_TOPIC = b"sensor/hcsr04/distance"

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

def measure_distance():
    TRIG.off()
    time.sleep_us(2)
    TRIG.on()
    time.sleep_us(10)
    TRIG.off()
    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

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

# Connect MQTT
client = MQTTClient("esp32_hcsr04", MQTT_BROKER)
client.connect()
print("MQTT connected")

# Main loop
while True:
    dist = measure_distance()
    payload = str(dist)
    client.publish(MQTT_TOPIC, payload)
    print("Published:", payload, "cm")
    time.sleep(5)  # measure every 5 seconds

This script reads the sensor every 5 seconds and publishes the distance (in cm) as a string to the MQTT topic sensor/hcsr04/distance. The AI agent will subscribe to this topic.

Step 2: Connect ASI Biont AI Agent via MQTT

Now, open the chat with ASI Biont. Describe your setup:

"Connect to MQTT broker broker.hivemq.com, subscribe to topic 'sensor/hcsr04/distance'. Read the distance value (a float in cm). If the distance drops below 30 cm, send a Telegram alert to my chat ID 123456789 using the Telegram Bot API token 'YOUR_BOT_TOKEN'. Also log every reading to a CSV file stored on the server."

The AI agent will generate and execute a Python script using execute_python with paho-mqtt and requests (for Telegram). It will:
- Subscribe to the topic.
- Parse incoming messages as floats.
- Check the threshold.
- Send HTTP POST to Telegram API if triggered.
- Append data to a CSV file (or database).

Here is an example of the script the AI might produce:

# AI-generated MQTT subscriber
import paho.mqtt.client as mqtt
import requests
import csv
import os
from datetime import datetime

TELEGRAM_TOKEN = "YOUR_BOT_TOKEN"
CHAT_ID = "123456789"
THRESHOLD = 30.0  # cm
CSV_FILE = "distance_log.csv"

def send_telegram_alert(msg):
    url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
    payload = {"chat_id": CHAT_ID, "text": msg}
    try:
        requests.post(url, json=payload, timeout=5)
    except Exception as e:
        print("Telegram error:", e)

def log_to_csv(distance):
    file_exists = os.path.isfile(CSV_FILE)
    with open(CSV_FILE, mode='a', newline='') as f:
        writer = csv.writer(f)
        if not file_exists:
            writer.writerow(["timestamp", "distance_cm"])
        writer.writerow([datetime.now().isoformat(), distance])

def on_message(client, userdata, msg):
    try:
        distance = float(msg.payload.decode())
        print(f"Received distance: {distance} cm")
        log_to_csv(distance)
        if distance < THRESHOLD:
            send_telegram_alert(f"Alert! Distance {distance:.1f} cm is below threshold!")
    except Exception as e:
        print("Error processing message:", e)

client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.subscribe("sensor/hcsr04/distance")
print("Subscribed to sensor/hcsr04/distance. Waiting for messages...")
client.loop_forever()

Note: The execute_python sandbox has a 30-second timeout, so loop_forever() will be interrupted. In production, the AI would use a non-blocking loop or schedule the script as a background task. However, for demonstration and short-lived tasks, this works perfectly.

Real-World Use Cases

1. Security / Intrusion Detection

Mount the HC-SR04 near a door or window. When the distance changes suddenly (e.g., from 150 cm to 40 cm as someone opens the door), the AI sends an SMS (via Twilio) or a push notification. The AI can also trigger a relay to turn on a siren.

2. Smart Parking Sensor

Place the sensor in a garage pointing at the wall. When the distance drops below 100 cm (car present), the AI turns on a green LED via another MQTT command. When distance is > 150 cm (garage empty), it turns on a red LED. Log occupancy over time for analytics.

3. Water Tank Level Monitoring

Install the sensor at the top of a water tank pointing down. The AI calculates fill level as level = (max_distance - current_distance) / max_distance * 100. If level falls below 20%, the AI sends a Telegram alert to refill.

4. People Counting + Energy Saving

Combine the HC-SR04 with a PIR motion sensor. The AI counts entries/exits based on distance changes. When the room is empty for 10 minutes, the AI turns off lights and HVAC via MQTT commands to smart plugs.

Why ASI Biont Makes This Easy

Traditional IoT integration requires:
- Writing firmware for the microcontroller.
- Setting up a broker.
- Writing a backend service (Node.js, Python) to handle data.
- Coding alert logic, database writes, and API calls.
- Debugging and maintaining all components.

With ASI Biont, you only need to:
1. Flash the ESP32 with the simple MicroPython script above (or copy-paste from the AI's suggestion).
2. Describe your integration goal in the chat.
3. The AI writes and runs the backend logic in seconds.

No need to wait for platform updates, no need to learn complex APIs. The AI agent understands MQTT, serial, Modbus, HTTP, and dozens of other protocols—it can connect to any device you describe.

Conclusion

The HC-SR04 ultrasonic sensor is a perfect entry point for experimenting with AI-driven IoT. By connecting it to ASI Biont via MQTT, you can create powerful automation scenarios without writing thousands of lines of code. Whether you're building a security system, a smart parking sensor, or a water tank monitor, the AI agent does the heavy lifting.

Try it yourself today: asibiont.com — no sign-up required to start a conversation. Just describe your sensor and your goal, and watch the AI connect your hardware to the cloud in minutes.

← All posts

Comments