Smart Distance Monitoring with HC-SR04 and ASI Biont: From DIY Sensor to AI-Powered Automation

Why Connect a $2 HC-SR04 to an AI Agent?

The HC-SR04 ultrasonic distance sensor is the workhorse of DIY projects — cheap (under $2), easy to use, and surprisingly versatile. But reading raw centimeters on a serial monitor is just the beginning. When you connect it to an AI agent like ASI Biont, that simple sensor becomes a decision-maker: it can trigger a garage door, alert you when your water tank is low, or detect an intruder approaching your window.

In this guide, I’ll show you exactly how to integrate an HC-SR04 with ASI Biont using two popular methods: MQTT via ESP32 (wireless, cloud-connected) and COM port via Arduino (wired, local). You’ll see real Python code that the AI writes for you — no manual integration work needed.


How ASI Biont Talks to Your HC-SR04

ASI Biont doesn’t have a dedicated “HC-SR04 driver”. Instead, it uses execute_python — a sandboxed Python environment with pre-installed libraries (paho-mqtt, pyserial, paramiko, requests, etc.). You simply describe your hardware setup in the chat, and the AI writes the appropriate scripts:

  • For an ESP32 with WiFi → AI generates an MQTT subscriber/publisher script (paho-mqtt) that reads distance values from a topic, analyzes them, and can send commands back via MQTT.
  • For an Arduino over USB → AI uses the Hardware Bridge (bridge.py running on your PC) to send serial commands and parse responses.

The AI never asks you to install a dashboard or click “add device” buttons — everything happens through conversation.


Step-by-Step: ESP32 + HC-SR04 + MQTT + Telegram Alerts

1. The Hardware Setup (you do this part)

Connect HC-SR04 to your ESP32:
- VCC → 5V
- GND → GND
- Trig → GPIO5
- Echo → GPIO18

Flash the ESP32 with MicroPython or Arduino code that publishes distance to an MQTT topic. Here’s a minimal MicroPython example (you can copy-paste this, or ask AI to generate one):

# ESP32 MicroPython MQTT publisher
from machine import Pin, time_pulse_us
import time
import network
import ubinascii
from umqtt.simple import MQTTClient

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

# WiFi and MQTT settings – replace with yours
SSID = "YourWiFi"
PASSWORD = "pass"
BROKER = "mqtt.example.com"
TOPIC = b"sensor/distance"

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
    time.sleep(1)

client = MQTTClient(ubinascii.hexlify(bytearray(4)), BROKER)
client.connect()

while True:
    TRIG.on()
    time.sleep_us(10)
    TRIG.off()
    dur = time_pulse_us(ECHO, 1, 30000)  # timeout 30ms
    dist = dur * 0.034 / 2  # cm
    client.publish(TOPIC, str(round(dist, 1)).encode())
    time.sleep(2)

2. Describe Your System to ASI Biont

In the ASI Biont chat, you write something like:

“I have an ESP32 publishing distance in cm to MQTT topic sensor/distance. Broker is mqtt.example.com:1883. If distance is less than 20cm, send a Telegram message to my chat ID 123456 using bot token ABC:XYZ. Also log all values to a local file ‘distances.log’.”

3. AI Writes and Runs the Integration Code

ASI Biont generates a Python script that runs in the sandbox (execute_python). Here’s what it looks like (simplified):

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

TELEGRAM_BOT_TOKEN = "ABC:XYZ"
TELEGRAM_CHAT_ID = "123456"
THRESHOLD = 20  # cm

def on_message(client, userdata, msg):
    try:
        distance = float(msg.payload.decode())
        print(f"Received distance: {distance} cm")

        # Log to file
        with open("/tmp/distances.log", "a") as f:
            f.write(f"{time.time()},{distance}\n")

        if distance < THRESHOLD:
            msg_text = f"⚠️ Distance {distance:.1f} cm is below threshold!"
            requests.post(f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
                          json={"chat_id": TELEGRAM_CHAT_ID, "text": msg_text})
    except Exception as e:
        print(f"Error: {e}")

client = mqtt.Client()
client.on_message = on_message
client.connect("mqtt.example.com", 1883, 60)
client.subscribe("sensor/distance")

# Wait for one message (sandbox timeout ~30s)
client.loop(timeout=10)

That’s it. The AI handles the MQTT connection, parsing, logic, and Telegram API. You don’t write a single line of the cloud-side code.


Alternative: Arduino + Hardware Bridge (Serial)

If you prefer a wired connection, use an Arduino Uno (or Nano) with the HC-SR04 and connect it via USB to your PC. The AI uses the Hardware Bridge (bridge.py) to access the COM port.

Arduino sketch (upload this once):

const int trig = 9, echo = 10;
void setup() {
  Serial.begin(115200);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}
void loop() {
  if (Serial.available() > 0) {
    String cmd = Serial.readStringUntil('\n');
    if (cmd == "MEASURE") {
      digitalWrite(trig, LOW); delayMicroseconds(2);
      digitalWrite(trig, HIGH); delayMicroseconds(10);
      digitalWrite(trig, LOW);
      long duration = pulseIn(echo, HIGH);
      float dist = duration * 0.034 / 2;
      Serial.println(dist);
    }
  }
}

In ASI Biont chat, describe:

“Arduino on COM3 at 115200 baud. Send command ‘MEASURE\n’ every 10 seconds, parse the returned distance (cm), and if it’s less than 50 cm, turn on an LED by sending ‘LED_ON\n’ back to the Arduino.”

AI will issue commands via the industrial_command tool with serial:// protocol:

industrial_command(
  protocol='serial',
  command='serial_write_and_read',
  data='4d4541535552450a'  # hex for "MEASURE\n"
)

Bridge sends the hex string and returns the Arduino’s response. The AI then parses the distance and sends another command if needed.


Real-World Scenarios

1. Automatic Garage Door Opener

HC-SR04 mounted above the driveway detects when a car is present (distance < 100 cm). ASI Biont receives the MQTT value and publishes a command to an ESP32 that controls a relay → door opens.

2. Liquid Level Monitoring in a Tank

Mount HC-SR04 at the top of a water tank. Distance = empty space, so liquid level = tank height - distance. AI sends an alert when level drops below 20% (e.g., via email or Telegram). All logic and scheduling happen in the sandbox.

3. Intruder Detection with Smart Alarm

Distance suddenly changes from 400 cm to 50 cm? AI can command an IP camera to start recording, or publish an MQTT message to sound a buzzer. You can even chain multiple sensors.


Why ASI Biont? (No Code, Just Describe)

With traditional approaches, you’d need to run your own MQTT broker, write a Python backend, handle database logging, and set up alerting. ASI Biont eliminates all that. The AI agent:
- Writes the exact Python script for your hardware
- Runs it in a secure cloud sandbox
- Handles reconnections, error handling, and threading
- Can schedule tasks, collect historical data, and interact with external APIs (Telegram, Slack, Google Sheets)

You only need to flash one simple sketch on your microcontroller — the rest is conversation.


HC-SR04 vs. Laser Distance Sensors

Feature HC-SR04 (Ultrasonic) VL53L0X (Laser)
Cost ~$2 ~$5-10
Range 2–400 cm Up to 200 cm
Accuracy ±0.3 cm ±0.1 cm
Sensitivity to surface Soft surfaces absorb sound Works on dark surfaces
Best use Budget automation, outdoors Precision indoor tasks

For 90% of smart home and IoT automation, the HC-SR04 is perfectly adequate. The AI can compensate for noise by applying a moving average filter in the Python script.


Ready to Build?

All you need is an HC-SR04, an ESP32 (or Arduino), and an ASI Biont account. No coding experience required for the AI side. Just describe your hardware and what you want, and the agent does the rest.

👉 Start your first integration at asibiont.com – connect any sensor in minutes.

This article was generated with the assistance of ASI Biont’s AI, which also wrote the integration scripts shown above.

← All posts

Comments