PIR Motion Sensor + AI Agent: Smart Motion Detection with ASI Biont Integration

From Simple Pulse to Intelligent Decisions

A PIR (Passive Infrared) motion sensor detects changes in infrared radiation — essentially, it sees heat moving. For decades, PIR sensors have been the backbone of basic automation: turn on a light when someone walks in, trigger an alarm when an intruder crosses a hallway. But a raw PIR signal is just a binary pulse — HIGH when motion is detected, LOW when nothing moves. That pulse alone can't tell you who moved, whether it's a person or a pet, or what to do next.

Connecting a PIR sensor to an AI agent like ASI Biont transforms that simple binary signal into a context-aware decision engine. Instead of hardcoding "if motion → turn light on" in a microcontroller sketch, you let the AI agent analyze the timing, frequency, and patterns of motion events, combine them with other data (time of day, temperature, presence of other devices), and decide the best action — lighting, notification, camera trigger, or ignore false alarms.

How ASI Biont Connects to a PIR Sensor

ASI Biont does not have a single "PIR sensor integration wizard." Instead, the AI agent connects to any device through execute_python — a sandboxed Python environment where the AI writes and runs custom integration code. You describe your hardware and connection method in the chat, and the AI generates the code. No dashboard panels, no plugins to install.

For a PIR sensor, the typical connection methods are:

Connection Method Typical Hardware Why Use It
Serial via Hardware Bridge Arduino / ESP32 connected over USB Direct, low-latency, no network setup. Perfect for local testing and simple sensor nodes.
MQTT ESP32 with WiFi + PIR library Networked sensor, multiple devices, cloud or local broker. Best for smart home integration.
SSH Raspberry Pi with GPIO PIR Full Linux environment, can run complex logic locally, easy to add cameras or relays.
HTTP API ESP32 running a web server Quick RESTful interface, but less efficient for event-driven sensors.

Most practical scenario: ESP32 with PIR → MQTT → ASI Biont.

Real Use Case: Smart Motion-Activated Lighting with Telegram Alerts

Let's walk through a concrete example. You have:
- An ESP32 development board (e.g., ESP32-DevKitC)
- A HC-SR501 PIR motion sensor
- A relay module connected to a lamp
- A local MQTT broker (Mosquitto) or a cloud broker (HiveMQ Cloud)

Step 1: Microcontroller Firmware (MicroPython)

Flash MicroPython on your ESP32. The sensor firmware reads the PIR pin and publishes a message to MQTT on state change.

# ESP32 MicroPython code (upload via Thonny or ampy)
import machine
import time
import ubinascii
from umqtt.simple import MQTTClient

# Configuration
WIFI_SSID = "YourWiFi"
WIFI_PASS = "YourPassword"
MQTT_BROKER = "192.168.1.100"  # or cloud broker URL
MQTT_TOPIC = b"home/motion/livingroom"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())

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

# Connect to WiFi
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
    time.sleep(0.5)

# Connect to MQTT
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.connect()

# Main loop – publish on state change
last_state = pir.value()
while True:
    current_state = pir.value()
    if current_state != last_state:
        # 1 = motion detected, 0 = no motion
        payload = b"motion" if current_state == 1 else b"clear"
        client.publish(MQTT_TOPIC, payload)
        last_state = current_state
    time.sleep(0.1)

Step 2: AI Agent Integration (ASI Biont Chat)

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

"Connect to MQTT broker at 192.168.1.100, subscribe to topic 'home/motion/livingroom'. When motion is detected, turn on a smart plug via HTTP API (http://192.168.1.200/cm?cmnd=Power%20ON) and send a Telegram notification. If no motion for 5 minutes, turn the light off. Also, log motion events to a local CSV file."

The AI agent writes a Python script using paho-mqtt and requests, and runs it in the sandbox environment. Here's what the generated code looks like:

# Generated by ASI Biont AI agent – runs in cloud sandbox
import paho.mqtt.client as mqtt
import requests
import time
import json
from datetime import datetime

# Configuration
BROKER = "192.168.1.100"
TOPIC = "home/motion/livingroom"
SMART_PLUG_URL = "http://192.168.1.200/cm?cmnd="
TELEGRAM_BOT_TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
TELEGRAM_CHAT_ID = "123456789"
LOG_FILE = "/tmp/motion_log.csv"

# State variables
motion_detected = False
last_motion_time = 0
LIGHT_OFF_DELAY = 300  # 5 minutes

def send_telegram(text):
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    data = {"chat_id": TELEGRAM_CHAT_ID, "text": text}
    requests.post(url, json=data, timeout=5)

def log_motion(event):
    with open(LOG_FILE, "a") as f:
        f.write(f"{datetime.now().isoformat()},{event}\n")

def on_message(client, userdata, msg):
    global motion_detected, last_motion_time
    payload = msg.payload.decode()
    if payload == "motion":
        if not motion_detected:
            print("Motion detected!")
            motion_detected = True
            # Turn on light
            requests.get(SMART_PLUG_URL + "Power%20ON", timeout=3)
            send_telegram("🚨 Motion detected in living room!")
            log_motion("motion")
        last_motion_time = time.time()
    elif payload == "clear":
        print("Motion cleared")
        motion_detected = False
        log_motion("clear")

# Connect to broker
client = mqtt.Client()
client.on_message = on_message
client.connect(BROKER, 1883, 60)
client.subscribe(TOPIC)
client.loop_start()

# Keep-alive loop with auto off
while True:
    if motion_detected and (time.time() - last_motion_time > LIGHT_OFF_DELAY):
        print("No motion for 5 min – turning off light")
        requests.get(SMART_PLUG_URL + "Power%20OFF", timeout=3)
        send_telegram("💡 Light turned off (no motion)")
        motion_detected = False
    time.sleep(10)

Important: The sandbox has a 30-second timeout for scripts that use while True. For long-running subscriptions, the AI agent uses client.loop_forever() or the script is designed to run as a persistent process via a separate mechanism (the agent can restart it periodically). The example above is illustrative — in production, the AI would restructure it for reliability.

Step 3: Observing Results

The AI agent logs activity. You can ask: "Show me the motion log from the last hour" and it will read the CSV file and display it. Or: "How many motion events today?" and it will parse the log and answer.

Why ASI Biont Beats Traditional Fixed Logic

Traditional PIR integration requires:
- Writing and flashing microcontroller code
- Setting up a separate server or cloud function for logic
- Manual configuration of each action (if-then-else)
- No ability to adapt to changing patterns

With ASI Biont:
- Zero manual coding — you describe the integration in plain English
- AI writes the glue code — MQTT client, HTTP requests, Telegram API calls, file I/O
- Dynamic decision making — the AI can modify its behavior based on conversation ("change notification to email instead of Telegram", "only trigger at night")
- Extensible — add new actions (e.g., turn on a camera) by simply asking

Advanced Scenario: Pet-Immune Motion Detection

A common problem: PIR sensors trigger on pets. With AI, you can implement a simple filter: if motion events occur in bursts of <2 seconds with >10-second gaps, assume it's a pet. The AI agent can write code to debounce and pattern-match:

# AI-generated pet filter logic
motion_events = []
MAX_PET_INTERVAL = 2.0  # seconds

def is_pet():
    if len(motion_events) < 3:
        return False
    # Check if recent events are very close together
    recent = motion_events[-3:]
    intervals = [recent[i+1] - recent[i] for i in range(len(recent)-1)]
    return all(i < MAX_PET_INTERVAL for i in intervals)

No need to reflash the ESP32 — the logic runs in the cloud and can be changed instantly via chat.

Comparison: Connection Methods for PIR

Method Latency Complexity Best For
Serial (Hardware Bridge) <10ms Low Single sensor, local PC, debugging
MQTT 50-200ms Medium Multi-sensor smart home, cloud logic
SSH (Raspberry Pi) <5ms (local) High On-device AI + camera + relays
HTTP API 100-500ms Low Quick prototyping, RESTful devices

Conclusion: From Binary to Intelligent

A PIR sensor doesn't need to be dumb. By connecting it to an AI agent like ASI Biont, you unlock adaptive, context-aware automation that you can modify in real time through natural conversation. No coding skills required — just describe your hardware and what you want, and the AI handles the integration.

Try it yourself: Go to asibiont.com, connect your PIR sensor via MQTT or serial, and tell the AI: "When motion is detected, send me a Telegram message and turn on the lamp for 10 minutes." The AI will write the code, connect your device, and make it happen — all in seconds.

← All posts

Comments