Integrate a PIR Motion Sensor with the ASI Biont AI Agent: A Step-by-Step Guide

Introduction

Motion sensors are the eyes of any smart home or industrial automation system. The humble PIR (Passive Infrared) sensor — like the ubiquitous HC-SR501 — detects movement by sensing changes in infrared radiation. But standalone, it’s just a binary signal. When you connect a PIR sensor to an AI agent like ASI Biont, that simple signal becomes a trigger for complex, context-aware actions: turn on lights, send a Telegram alert, start recording a video, or even adjust HVAC zoning.

In this guide, you’ll learn exactly how to wire an HC-SR501 PIR sensor to an ESP32, connect it to ASI Biont via MQTT, and create automation workflows — all without writing a single line of boilerplate code. The AI agent writes the integration code for you in seconds.

Why Connect a PIR Sensor to an AI Agent?

Traditional PIR setups use a microcontroller to read the pin and toggle a relay. That’s fine for a single room. But with an AI agent:

  • Context-aware decisions: The AI knows the time of day, whether you’re home, or if the security system is armed.
  • Multi-device coordination: One motion event can trigger lights, cameras, and notifications simultaneously.
  • Self-healing: If a sensor goes offline, the AI can log the failure and suggest a replacement.
  • No manual coding: You describe your needs in plain English, and ASI Biont generates and runs the Python integration code.

Which Connection Method to Use

For a PIR sensor connected to an ESP32 (or similar microcontroller), the most practical method is MQTT via the paho-mqtt library. The ESP32 publishes motion events to a topic (e.g., sensor/pir1). ASI Biont subscribes to that topic using a Python script executed in the execute_python sandbox, which has full access to the paho-mqtt library.

Alternatively, if you use an Arduino connected to a PC via USB, you can use the Hardware Bridge (bridge.py) to read serial data from the COM port.

For this article, we’ll focus on the MQTT approach — it’s wireless, scalable, and works with any MQTT-compatible firmware (ESPHome, Tasmota, or custom MicroPython).

Step 1: Wiring the HC-SR501 to ESP32

The HC-SR501 has three pins:

HC-SR501 Pin ESP32 Pin
VCC 3.3V
GND GND
OUT GPIO4

Wiring diagram:

ESP32        HC-SR501
3.3V  -----> VCC
GND   -----> GND
GPIO4 -----> OUT

Note: The HC-SR501 works with 5V logic, but the ESP32’s 3.3V GPIO is still safe because the sensor’s output is open-drain. For production, use a level shifter or voltage divider.

Step 2: ESP32 Firmware (MicroPython) – Publish Motion via MQTT

Here’s a complete MicroPython script that reads the PIR sensor and publishes the state to an MQTT broker every time motion is detected or cleared. Upload this to your ESP32 using Thonny or ampy.

import machine
import time
import ubinascii
from umqtt.simple import MQTTClient

# WiFi credentials
WIFI_SSID = "YourWiFiSSID"
WIFI_PASS = "YourWiFiPassword"

# MQTT broker (Mosquitto on Raspberry Pi or public broker)
MQTT_BROKER = "192.168.1.100"
MQTT_TOPIC = b"sensor/pir1"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())

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

def main():
    connect_wifi()
    pir = machine.Pin(4, machine.Pin.IN)
    client = MQTTClient(CLIENT_ID, MQTT_BROKER)
    client.connect()
    print("MQTT connected")

    last_state = None
    while True:
        current = pir.value()
        if current != last_state:
            msg = b"1" if current else b"0"
            client.publish(MQTT_TOPIC, msg)
            print("Published:", msg)
            last_state = current
        time.sleep(0.5)

try:
    main()
except KeyboardInterrupt:
    print("Stopped")

Replace WiFi and MQTT broker settings with your own. The script publishes 1 on motion, 0 when motion clears.

Step 3: Connect ASI Biont to the MQTT Topic

Now, open the ASI Biont chat and describe what you want. For example:

“Connect to MQTT broker at 192.168.1.100:1883, subscribe to topic sensor/pir1, and when the value is 1, turn on the smart light at 192.168.1.50 via HTTP API /light/on. Also send me a Telegram notification.”

ASI Biont will generate and execute a Python script in its sandbox. Here’s what the AI would write internally (you don’t need to write it — just describe):

import paho.mqtt.client as mqtt
import requests
import json

def on_message(client, userdata, msg):
    payload = msg.payload.decode()
    if payload == "1":
        # Turn on smart light
        requests.get("http://192.168.1.50/light/on")
        # Send Telegram notification (example using requests)
        bot_token = "YOUR_BOT_TOKEN"
        chat_id = "YOUR_CHAT_ID"
        text = "Motion detected! Light turned on."
        url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
        requests.post(url, data={"chat_id": chat_id, "text": text})

client = mqtt.Client()
client.on_message = on_message
client.connect("192.168.1.100", 1883, 60)
client.subscribe("sensor/pir1")
client.loop_forever()

The script runs as long as the sandbox allows (up to 30 seconds for testing; for production, use the Hardware Bridge or a dedicated loop). ASI Biont logs all actions and can even suggest optimizations.

Step 4: Automate Scenarios Without Code

Once the MQTT connection is established, you can create triggers in the AI chat using natural language. Example scenarios:

  • Light automation: “When motion is detected after sunset, turn on the living room lights at 30% brightness via Zigbee.”
  • Security alert: “If motion is detected while I’m away (based on phone GPS status), send me a camera snapshot via HTTP.”
  • Energy saving: “If no motion for 10 minutes, turn off all lights and set thermostat to eco mode.”

Each scenario is a simple conversation with the AI. No dashboards, no buttons — just describe, and the AI writes the integration.

Real-World Use Case: Home Office Occupancy

I set up a PIR sensor in my home office. When I enter, the AI:
1. Turns on the desk lamp via a smart plug (HTTP API).
2. Starts a Pomodoro timer using a Python script.
3. Sends a Slack status: “In the office – focus mode.”

When I leave for more than 5 minutes, it:
1. Turns off the lamp.
2. Logs the session duration to a Google Sheet (via API).
3. Resets the Slack status.

All this was set up in under 10 minutes by chatting with ASI Biont. The AI even debugged a WiFi reconnection issue by adding retry logic to the ESP32 firmware.

Why ASI Biont Is the Fastest Way to Integrate

Traditional IoT platforms require you to build a skill, write a lambda function, or configure a rule engine. With ASI Biont:

  • Universal: Connect to any device via MQTT, Modbus, HTTP, SSH, OPC UA, CAN bus, or COM port.
  • Zero boilerplate: The AI writes the Python integration code using paho-mqtt, requests, paramiko, or any of the 70+ pre-installed libraries.
  • Instant deployment: Describe your setup in the chat — the AI generates, tests, and runs the code.
  • No app or dashboard needed: Everything happens through the conversation. You can manage multiple devices across protocols in one chat.

Conclusion

Integrating a PIR motion sensor with the ASI Biont AI agent transforms a simple binary signal into a powerful automation trigger. Whether you’re building a smart home, a security system, or an industrial occupancy tracker, the process is the same: wire the sensor, publish MQTT messages, and let the AI handle the rest.

Ready to automate your space? Go to asibiont.com, create an account, and start a chat. Describe your sensor setup — the AI will connect it in seconds.

← All posts

Comments