From Motion to Action: Connecting a PIR Motion Sensor to ASI Biont AI Agent

From Motion to Action: Connecting a PIR Motion Sensor to ASI Biont AI Agent

A passive infrared (PIR) sensor is one of the simplest yet most useful components in automation. It outputs a single digital signal when a warm body moves through its field of view. But a raw HIGH/LOW pulse is just a fact; it doesn't tell you whether someone entered your office, whether a room is occupied, or whether an intruder is in your backyard. Connecting a PIR sensor to an AI agent like ASI Biont turns that trivial signal into a decision engine: it can notify you on Telegram, switch off HVAC, log motion events, or even distinguish between human and pet movement with additional logic.

In this guide, we'll walk through a real integration: an ESP32 microcontroller with a HC-SR501 PIR sensor, streaming motion events via MQTT to ASI Biont. Along the way, we'll see how ASI Biont's AI agent writes the integration code for you, using the same protocol libraries you'd use manually.

Why connect a motion sensor to an AI agent?

A standalone PIR sensor can blink an LED or sound a buzzer. An AI-connected sensor becomes part of a smart environment. Here are three practical scenarios:

  • Home security: Detect motion during away hours and send an instant alert with the room name and timestamp.
  • Energy saving: A room-in-use signal can trigger a smart thermostat or disable the ventilation when nobody is present.
  • Traffic analytics: In retail or coworking spaces, PIR arrays can estimate footfall and generate daily reports.

The value of ASI Biont is that you don't need to write a single line of the system's integration logic yourself — you describe the hardware setup and the desired behavior, and the AI produces the code and runs it in a sandbox.

The hardware: PIR sensor + ESP32

We use the widely available HC-SR501 PIR sensor module (datasheet reference: https://www.mpja.com/download/hc-sr501datasheet.pdf). It operates at 5V, has a detection range up to 7 meters, and a 3.3V TTL output, so it can directly interface with an ESP32.

Why do we need an ESP32? The PIR sensor outputs only an analog-digital level. It has no IP address, no network stack, and cannot speak MQTT or Modbus. A microcontroller like the ESP32 bridges that gap: it powers the sensor, reads the output, and connects to your Wi-Fi network.

Wiring table

PIR HC-SR501 ESP32 pin
VCC (middle) 5V pin (or 3.3V for 3.3V versions)
GND GND
OUT GPIO 27 (any digital input)

A common mistake is connecting the PIR output to an analog pin. The HC-SR501 output is digital — use a digital GPIO.

Integration architecture

The system has three layers:

[PIR sensor] --GPIO--> [ESP32 + MicroPython] --MQTT--> [broker] --MQTT--> [ASI Biont]

ASI Biont does not talk to the PIR directly; it talks to the MQTT broker, which is the transportation layer. This decouples the sensor from the AI agent and allows multiple sensors to share one broker. MQTT is a lightweight publish/subscribe protocol designed for IoT (see MQTT 3.1.1 spec: https://mqtt.org/mqtt-specification/), and it's one of the twelve protocols supported natively by ASI Biont.

Step 1: MicroPython firmware on the ESP32

Flash MicroPython on your ESP32 (official guide: https://docs.micropython.org/en/latest/esp32/tutorial/intro.html). Then write a simple script that reads the PIR and publishes a message when motion is detected.

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

PIR_PIN = Pin(27, Pin.IN)

WIFI_SSID = 'your_wifi'
WIFI_PASS = 'your_password'
MQTT_BROKER = '192.168.1.100'  # broker IP or hostname
TOPIC = 'sensor/motion/livingroom'

def connect_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)

def publish_motion():
    client = MQTTClient('esp32_' + ubinascii.hexlify(machine.unique_id()).decode(),
                        MQTT_BROKER)
    client.connect()
    payload = ujson.dumps({'motion': True, 'room': 'livingroom'})
    client.publish(TOPIC, payload)
    client.disconnect()

connect_wifi()

last_state = False
while True:
    state = PIR_PIN.value() == 1
    if state and not last_state:
        publish_motion()
        print('Motion detected!')
    last_state = state
    time.sleep(0.1)

Wait — the article says ASI Biont's execute_python is limited to 30 seconds and cannot run infinite loops. That limitation applies to scripts executed by the AI agent in its sandbox, not to your ESP32. The ESP32 firmware runs forever by design. The MQTT subscription that handles the motion events, however, is a long-running process — this is where ASI Biont's native MQTT client comes in.

Step 2: Telling ASI Biont about the sensor

You don't write the integration code for ASI Biont. You describe the setup in natural language. For example:

"There is a PIR sensor in my living room. It publishes MQTT messages to topic 'sensor/motion/livingroom' on broker 192.168.1.100. Every time a message arrives with motion: true, send me a Telegram notification. Also write the event to logs/motion.log."

ASI Biont's AI agent will then:

  1. Generate a Python script that uses paho-mqtt to subscribe to the topic.
  2. Wrap it in its service layer to keep the subscription active.
  3. Add a callback that sends a Telegram message via the Telegram Bot API and appends a line to a log file.

Here's what the generated script looks like (simplified):

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

BROKER = '192.168.1.100'
TOPIC = 'sensor/motion/livingroom'
TELEGRAM_TOKEN = '000000:ABC...'
CHAT_ID = '123456789'
LOG_FILE = 'logs/motion.log'

def on_connect(client, userdata, flags, rc):
    client.subscribe(TOPIC)

def on_message(client, userdata, msg):
    try:
        data = json.loads(msg.payload.decode())
        if data.get('motion'):
            requests.post(f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage',
                          json={'chat_id': CHAT_ID,
                                'text': 'Motion detected in the living room!'})
            with open(LOG_FILE, 'a') as f:
                f.write(f'{msg.topic} at {time.time()}\n')
    except Exception as e:
        print('Error:', e)

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

Note how the AI uses requests.post to the Telegram Bot API — a real, documented endpoint. ASI Biont does not hide functionality behind pseudo-commands; it generates code using widely known libraries.

Alternative: Serial connection via Hardware Bridge

Not all motion sensors are connected to MQTT. Some hobby setups use an Arduino that prints MOTION_DETECTED over a USB serial port. In that case, you'd use ASI Biont's Hardware Bridge — a small program you download from your ASI Biont dashboard. It creates a virtual COM port between your Arduino and the AI agent.

You might launch the bridge like this:

python bridge.py --token=YOUR_TOKEN --ports=COM3 --baud=115200 --rate=10

Then, in the chat, you ask: "Read from COM3 with baud rate 115200. If the line says MOTION_DETECTED, send me a Telegram notification." The AI agent uses industrial_command() to read the serial stream.

# Example of code ASI Biont might generate
result = industrial_command(
    protocol='serial',
    command='read_line',
    port='COM3',
    baudrate=115200,
    timeout=2
)
if 'MOTION_DETECTED' in result:
    send_telegram_alert('Motion detected')

However, for modern installations, MQTT is more robust, as it doesn't depend on a physical cable and works over Wi-Fi or even the cellular network.

Real-world scenario: Security system with a twist

Let's combine the examples into a coherent scenario. Imagine you have a home office. You install PIR sensors in three rooms — living room, hallway, and storage. Each room has its own topic. In the ASI Biont chat, you say:

"Monitor motion in three rooms. If motion is detected between 22:00 and 06:00 in the storage area, send an alert with the room name. Otherwise, only log motion in daily_summary.md."

ASI Biont generates a single script with an MQTT subscription for all three topics and time-aware logic. The data is stored locally, and you get a morning summary.

This is the killer feature: you don't need to manually configure rules in a thousand-dropdown UI. You describe the rules, and the AI encodes them into executable Python.

Why ASI Biont can connect to any device

The crucial advantage of ASI Biont is the universal execute_python capability. When you send a message like "Talk to my PIR sensor," the AI agent chooses the appropriate protocol library and writes the integration script from scratch. It can handle:

  • pyserial for COM ports
  • paho-mqtt for MQTT
  • pymodbus for Modbus/TCP
  • paramiko for SSH
  • aiohttp for HTTP API/WebSocket
  • opcua-asyncio for OPC-UA

And that's not a limit — if your sensor speaks a rare protocol, the AI can use a generic Python library or even a raw socket. You just describe the connection parameters (port, IP, baud rate, API key) and the AI fills in the rest.

There is no waiting for developers to "add support" for your hardware. No plugin ecosystem. The AI is the integration layer.

Practical wiring and setup tips

  • Place the PIR sensor away from direct sunlight and heat sources to prevent false triggers.
  • If using the HC-SR501, adjust the two blue potentiometers: one sets the sensitivity (detection distance), the other sets the hold time (how long the output stays HIGH). For home automation, set the hold time to 5 seconds or less.
  • Use a pull-down resistor (10 kΩ) on the ESP32 GPIO if you experience floating readings.
  • In the MQTT callback, always wrap the payload parsing in a try/except — MQTT messages can come from any source, and malformed JSON shouldn't crash the subscriber.

Conclusion: Try it now

Integrating a PIR motion sensor with ASI Biont is not a project — it's a conversation. You tell the AI what sensor you have and what you want it to do, and it handles the low-level code, the network connection, and the automation logic. Whether it's a security system, an energy-saving solution, or a motion-logging tool, the AI agent turns your raw sensor pulses into meaningful actions in seconds.

Stop writing glue code. Start describing outcomes. Try the integration at asibiont.com and connect your PIR sensor today.

← All posts

Comments