Why Connect an HC-SR04 to an AI Agent?
The HC-SR04 is a classic, dirt-cheap ultrasonic distance sensor – you can grab one for under $2 on AliExpress. It measures distances from 2 cm to 4 meters with decent accuracy (about ±3 mm). By itself, it’s just a pulsing echo. But when you wire it to a microcontroller and feed the readings into ASI Biont, you transform raw centimeters into intelligence: “Car is 15 cm from the wall – stop!” or “Water level dropped 10% in one hour – possible leak.”
ASI Biont is an AI agent that connects to hardware through a chat interface. You describe your setup, it writes the integration code, and you get real-time monitoring, alerts, and automatic responses – all without building a dashboard. Below, I’ll walk you through a complete parking-assistant example using an ESP32, an HC-SR04, and ASI Biont over MQTT.
Which Connection Method and Why?
For this guide we’ll use MQTT – the de facto protocol for IoT sensors. The ESP32 runs a simple sketch that publishes distance values every second to a broker (e.g., Mosquitto or HiveMQ Cloud). ASI Biont subscribes to that topic via a Python script executed with execute_python (which has full access to paho-mqtt). Alternatively, you could use a Hardware Bridge if the sensor is connected to an Arduino Uno via COM port – see the alternative approach later.
Step 1: ESP32 + HC-SR04 Hardware Setup
| HC-SR04 Pin | ESP32 Pin |
|---|---|
| VCC | 5V (or 3.3V – many HC-SR04 work at 3.3V, check yours) |
| Trig | GPIO 5 |
| Echo | GPIO 18 |
| GND | GND |
Wire it up, power the ESP32 via USB. Upload the following Arduino sketch (uses the NewPing library for stable readings).
#include <WiFi.h>
#include <PubSubClient.h>
#include <NewPing.h>
#define TRIGGER_PIN 5
#define ECHO_PIN 18
#define MAX_DISTANCE 400
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
const char* ssid = "YourWiFi";
const char* password = "YourPassword";
const char* mqtt_server = "test.mosquitto.org"; // or your own broker
const char* mqtt_topic_distance = "home/parking/distance";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32Parking")) {
Serial.println("MQTT connected");
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned int distance = sonar.ping_cm();
if (distance == 0) distance = MAX_DISTANCE; // no echo -> out of range
char msg[10];
itoa(distance, msg, 10);
client.publish(mqtt_topic_distance, msg);
Serial.printf("Published: %s cm\n", msg);
delay(1000); // 1 Hz update rate
}
Upload and open the Serial Monitor – you should see distances being published every second.
Step 2: Connect ASI Biont to the MQTT Stream
Now comes the magic. In ASI Biont chat, simply describe what you want:
“Connect to MQTT broker test.mosquitto.org, subscribe to topic home/parking/distance, and alert me on Telegram when distance is less than 20 cm.”
ASI Biont will instantly generate and run a Python script using execute_python (sandboxed on Railway). Here’s the script it would produce (you can inspect it in the chat history):
import paho.mqtt.client as mqtt
import json
import requests
TELEGRAM_TOKEN = "YOUR_BOT_TOKEN"
CHAT_ID = "YOUR_CHAT_ID"
def send_telegram(text):
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
payload = {"chat_id": CHAT_ID, "text": text}
requests.post(url, json=payload)
def on_message(client, userdata, msg):
distance = int(msg.payload.decode())
print(f"Distance: {distance} cm")
if distance < 20 and distance > 0:
send_telegram(f"⚠️ Parking alert! Distance = {distance} cm")
def on_connect(client, userdata, flags, rc):
print("Connected to broker")
client.subscribe("home/parking/distance")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("test.mosquitto.org", 1883, 60)
client.loop_forever()
Important: The sandbox’s loop_forever() would time out after 30 seconds, so for a long-running subscription you’d use the industrial_command tool instead. But for testing, it works perfectly. ASI Biont will note the limitation and suggest using industrial_command with the publish command for production – or you can deploy your own always-on bridge script outside the sandbox.
Step 3: Automate Actions with AI Rules
Once data flows, you can go further. Ask ASI Biont:
“Create a rule: if distance stays below 15 cm for more than 5 seconds, turn on a red LED connected to an Arduino via COM port.”
ASI Biont will choose the Hardware Bridge path (you run bridge.py on your PC with --ports=COM3 --baud 115200). Then it sends an industrial_command to the bridge:
industrial_command(
protocol='serial',
command='serial_write_and_read',
data='5245440a' # hex for "RED\n"
)
The bridge sends RED\n to the Arduino, which toggles an LED. All without you writing a single line of boilerplate.
Real-World Use Cases for HC-SR04 + ASI Biont
| Use Case | Description | AI Action |
|---|---|---|
| Smart Parking | Sensor mounted in garage – measures distance to car bumper. | Telegram alert when < 20 cm. Log history to Google Sheets for weekly trends. |
| Liquid Level Monitoring | Sensor above a tank, measuring reflected distance from water surface. | Notify when level < 10% capacity. Activate pump (via relay on ESP32) if level too low. |
| Perimeter Security | Sensor aimed across a doorway – detect motion via rapid distance changes. | Send camera snapshot (via SSH to Raspberry Pi) and lock door (via MQTT to smart lock). |
| Robotics Obstacle Avoidance | Robot forwards distance readings to ASI Biont. | AI writes a script that commands the robot motors (via serial) to reverse if distance < 30 cm. |
Alternative: Direct COM Port Connection (Arduino Uno)
If you don’t want to use MQTT, connect the HC-SR04 to an Arduino Uno and use the Hardware Bridge. The Arduino serial prints distance in the format DIST:123. On your PC, run bridge.py with --ports=COM3 --baud 9600. In ASI Biont chat, say:
“Read the distance from COM3 at 9600 baud and alert me if it’s under 50 cm.”
ASI Biont uses industrial_command(protocol='serial', command='serial_write_and_read', data='524541440a') (sends "READ") and parses the response. The bridge handles all COM port quirks (CancelIoEx, PurgeComm) automatically.
Why This Beats Traditional Dashboards
Most IoT platforms force you to configure dashboards, widgets, and rules through a rigid UI. With ASI Biont, you just chat:
- “Send me a Telegram summary every 10th reading.”
- “If distance drops below 10 cm, tweet ‘Car too close!’ and flash a strobe light.”
- “Log all readings to a CSV file on my PC and email it weekly.”
The AI agent generates the code, runs it, and adapts instantly. No waiting for feature requests.
Try It Yourself
- Get an HC-SR04 – any electronics shop has them.
- Wire it to an ESP32 and upload the MQTT sketch above.
- Create an account at asibiont.com – free tier includes MQTT subscriptions.
- Chat with the AI – describe your sensor and desired actions. That’s it.
The HC-SR04 is just the beginning. The same pattern works for any sensor: DHT22, PIR motion, soil moisture, GPS modules – you name it. ASI Biont’s execute_python gives you access to 50+ libraries (pyserial, pymodbus, paho-mqtt, opencv, pandas…). Your only limit is your imagination.
Start building your AI-powered sensor network today.
Comments