How to Integrate a PIR Motion Sensor with the ASI Biont AI Agent: A Practical Guide for IoT and Smart Home Automation

Introduction

Motion detection is the cornerstone of modern automation — from turning on lights when you enter a room to triggering security alerts. A Passive Infrared (PIR) sensor detects infrared radiation changes caused by moving warm bodies (humans, animals). When paired with an AI agent like ASI Biont, a simple PIR sensor becomes an intelligent trigger that can analyze traffic patterns, send notifications, and coordinate complex multi-device scenarios. This guide walks you through a real integration of a PIR sensor connected to an ESP32 microcontroller with the ASI Biont AI agent — no dashboards, no manual code writing, just natural conversation.

Why Connect a PIR Sensor to an AI Agent?

A standalone PIR sensor outputs only a binary signal: HIGH when motion is detected, LOW when idle. An AI agent adds context, memory, and decision logic:

  • Pattern recognition: distinguish between a person walking and a pet moving
  • Conditional triggers: only notify if motion occurs during night hours or when the user is away
  • Multi-sensor fusion: combine PIR data with light, temperature, or door sensors
  • Remote control: send commands to other devices (lights, alarms, cameras) based on motion events

Connection Methods Supported by ASI Biont

ASI Biont connects to physical devices through several proven methods. For a PIR sensor, the most practical approaches are:

Method Use Case Pros Cons
MQTT (via paho-mqtt) ESP32 publishes sensor data to a broker; ASI Biont subscribes and acts Wireless, scalable, standard IoT protocol Requires MQTT broker setup
Hardware Bridge (COM port) Arduino/ESP32 connected via USB; user runs bridge.py on PC Direct serial access, no network dependency PC must be on; wired connection
SSH (via paramiko) Raspberry Pi with PIR connected to GPIO Full control over Linux host Requires SSH credentials

For this tutorial, we use MQTT — the most flexible and modern approach for IoT devices. The PIR sensor is connected to an ESP32, which publishes motion events to a Mosquitto MQTT broker. ASI Biont’s AI agent writes and executes a Python script that subscribes to the topic, analyzes the data, and triggers actions.

Step-by-Step Integration: PIR + ESP32 + MQTT + ASI Biont

1. Hardware Setup

Components:
- ESP32 development board (e.g., ESP32-WROOM-32)
- HC-SR501 PIR motion sensor
- Jumper wires
- Micro-USB cable

Wiring:
- PIR VCC → ESP32 3.3V
- PIR GND → ESP32 GND
- PIR OUT → ESP32 GPIO 13

2. ESP32 Firmware (MicroPython)

Flash MicroPython on the ESP32 (instructions at micropython.org). Then upload the following code using a tool like ampy or Thonny:

import network
import time
import json
from machine import Pin
from umqtt.simple import MQTTClient

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

# MQTT broker settings
BROKER = "192.168.1.100"  # IP of your MQTT broker
CLIENT_ID = "esp32_pir_01"
TOPIC_PUB = "home/pir/1"

# PIR sensor on GPIO 13
pir = Pin(13, Pin.IN)

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

def connect_mqtt():
    client = MQTTClient(CLIENT_ID, BROKER)
    client.connect()
    print("MQTT connected")
    return client

connect_wifi()
client = connect_mqtt()

last_state = pir.value()
while True:
    current_state = pir.value()
    if current_state != last_state:
        payload = {"motion": bool(current_state), "timestamp": time.time()}
        client.publish(TOPIC_PUB, json.dumps(payload))
        print("Published:", payload)
        last_state = current_state
    time.sleep(0.1)

This script publishes a JSON message {"motion": true/false} every time the PIR sensor changes state.

3. Connect ASI Biont to the MQTT Broker

Now, in the ASI Biont chat, you simply describe the task:

"Connect to MQTT broker at 192.168.1.100:1883, subscribe to topic 'home/pir/1', and whenever motion is detected, send me a Telegram message. Also, if motion is detected between 10 PM and 6 AM, turn on the smart light via HTTP API at 192.168.1.50."

The AI agent automatically generates and executes a Python script using the execute_python sandbox with the paho-mqtt library. Here is what the AI writes:

import paho.mqtt.client as mqtt
import json
import asyncio
import aiohttp
from datetime import datetime

BROKER = "192.168.1.100"
PORT = 1883
TOPIC = "home/pir/1"
TELEGRAM_BOT_TOKEN = "your_telegram_bot_token"
TELEGRAM_CHAT_ID = "your_chat_id"
LIGHT_API_URL = "http://192.168.1.50/api/light"

def on_message(client, userdata, msg):
    payload = json.loads(msg.payload.decode())
    motion = payload.get("motion", False)
    if motion:
        # Send Telegram notification
        asyncio.run(send_telegram("Motion detected!"))
        # Check if it's night time (22:00 - 06:00)
        now = datetime.now()
        if now.hour >= 22 or now.hour < 6:
            asyncio.run(turn_on_light())

def on_connect(client, userdata, flags, rc):
    print("Connected to MQTT broker")
    client.subscribe(TOPIC)

async def send_telegram(text):
    async with aiohttp.ClientSession() as session:
        url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
        params = {"chat_id": TELEGRAM_CHAT_ID, "text": text}
        async with session.get(url, params=params) as resp:
            return await resp.json()

async def turn_on_light():
    async with aiohttp.ClientSession() as session:
        payload = {"state": "on"}
        async with session.post(LIGHT_API_URL, json=payload) as resp:
            return await resp.json()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(BROKER, PORT, 60)
client.loop_forever()

Important: The execute_python sandbox has a 30-second timeout, so loop_forever() is not used in production. The AI agent runs the script as a long-lived background task; the example above is simplified. In practice, the agent will use client.loop_start() and keep the connection alive.

4. How the User Interacts

No dashboards, no “add device” buttons. The entire integration happens through chat:

  1. User: "Connect to my MQTT broker at 192.168.1.100, subscribe to home/pir/1."
  2. AI: "I'll write a script using paho-mqtt. What should happen when motion is detected?"
  3. User: "Send me a Telegram notification and turn on the smart light between 10 PM and 6 AM."
  4. AI: Generates the script, runs it in the sandbox, confirms successful connection.

Automation Scenarios Made Possible

Once the PIR sensor is integrated, you can extend the logic without touching hardware:

Scenario How AI Agent Handles It
Security alert If motion detected while no one is home (based on geofence or schedule), AI sends SMS via Twilio and records camera snapshot
Energy saving AI tracks motion patterns and turns off lights/HVAC after 15 minutes of inactivity
Visitor counting AI aggregates motion events over time, calculates daily traffic, and emails a report
Elderly care If no motion for 12 hours, AI sends a caregiver alert
Pet detection AI combines PIR with weight sensor to distinguish humans from pets

Why This Approach Is Better Than Traditional Smart Home Hubs

Traditional hubs (Home Assistant, SmartThings) require you to manually create automations via YAML or drag-and-drop. With ASI Biont:

  • Zero coding — you describe what you want in plain English
  • Any protocol — MQTT, Modbus, SSH, HTTP, OPC-UA — all supported by the same AI
  • Dynamic logic — change automation rules instantly by chatting
  • Edge-to-cloud — the AI runs in the cloud but talks to local devices via bridges or MQTT

According to the 2025 IoT Analytics Report (IoT Analytics GmbH), 67% of industrial IoT projects fail during integration due to protocol fragmentation. ASI Biont solves this by having the AI adapt to any protocol on the fly.

Conclusion

Integrating a simple PIR motion sensor with the ASI Biont AI agent turns a dumb binary switch into an intelligent, context-aware automation hub. Whether you are building a smart home, a small office security system, or an industrial occupancy tracker, the process is the same: connect the sensor to a microcontroller, publish data via MQTT, and let the AI handle the rest.

Ready to automate with AI? Go to asibiont.com, start a chat, and describe your device setup. The AI agent will write the integration code in seconds — no coding required.

← All posts

Comments