PIR Motion Sensor Meets AI: How to Integrate with ASI Biont for Smart Automation

Introduction

Motion sensors are the eyes of any smart building. A PIR (passive infrared) sensor detects occupancy by measuring changes in infrared radiation — and when paired with an AI agent, it becomes more than just a trigger for lights. Imagine a system that learns patterns, predicts movement, and adapts in real time. ASI Biont lets you connect a PIR sensor to an AI agent without writing complex code from scratch. This guide shows you exactly how to do it, using real protocols and hardware.

Why Connect a PIR Sensor to an AI Agent?

Traditional PIR setups are rule-based: motion → action. With an AI agent, you get:
- Predictive logic: The AI learns when movement is likely (e.g., before sunrise, after a meeting) and pre-arms systems.
- Context-aware responses: Combine motion data with other sensors (temperature, time of day) to decide whether to turn on lights, lock doors, or send an alert.
- Remote control: Query the sensor state from anywhere via chat.

ASI Biont connects to any device through its sandbox execute_python environment. You describe the task in natural language, and the AI writes the integration code — no dashboard or 'add device' button required.

Connection Methods for PIR Sensors

Depending on your hardware, you can use one of these methods supported by ASI Biont:

Hardware Protocol Method Why choose it
ESP32 (with PIR) MQTT paho-mqtt in execute_python Wireless, cloud-accessible
Arduino (with PIR) COM port Hardware Bridge (bridge.py) Direct USB connection, low latency
Raspberry Pi (GPIO PIR) SSH paramiko in execute_python Full control over GPIO, no extra hardware
Industrial PLC (Modbus) Modbus/TCP pymodbus via industrial_command Factory-grade reliability

For this article, we'll focus on ESP32 + MQTT (most common) and Arduino + COM port (best for learning).

Use Case 1: ESP32 + PIR via MQTT

What You Need

  • ESP32 dev board (e.g., ESP32-WROOM-32)
  • HC-SR501 PIR sensor
  • MQTT broker (public test broker: broker.hivemq.com port 1883, or run Mosquitto locally)
  • ASI Biont account (free tier available)

Wiring Diagram

HC-SR501 -> ESP32
VCC  -> 5V (or 3.3V, check module)
GND  -> GND
OUT  -> GPIO 4

Set the HC-SR501 jumper to repeatable trigger mode (H) for continuous detection.

MicroPython Code for ESP32

Save this as main.py on your ESP32:

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

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

# MQTT settings
BROKER = "broker.hivemq.com"
TOPIC = "home/motion/livingroom"

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

# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
    time.sleep(1)
print("Wi-Fi connected")

# Connect to MQTT
client = MQTTClient("esp32_pir", BROKER)
client.connect()

prev_state = 0
while True:
    current = pir.value()
    if current != prev_state:
        msg = "motion_detected" if current == 1 else "no_motion"
        client.publish(TOPIC, msg)
        print(f"Published: {msg}")
        prev_state = current
    time.sleep(0.1)

Step-by-Step Integration with ASI Biont

  1. In chat with ASI Biont, describe: "Connect to MQTT broker broker.hivemq.com, subscribe to topic home/motion/livingroom. When motion is detected, log the event and send me a Telegram alert."

  2. The AI generates and runs this Python script in its sandbox (execute_python):

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

def on_message(client, userdata, msg):
    payload = msg.payload.decode()
    timestamp = datetime.now().isoformat()
    if payload == "motion_detected":
        print(f"[{timestamp}] Motion detected in living room")
        # In real use, you'd call Telegram API here
        # requests.post("https://api.telegram.org/...")
    else:
        print(f"[{timestamp}] No motion")

client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.subscribe("home/motion/livingroom")
client.loop_start()

# Keep running for 30 seconds (sandbox timeout)
import time
time.sleep(30)
client.loop_stop()
  1. The AI explains the output and offers to set up persistent monitoring via industrial_command with MQTT publish to control an action (e.g., turn on a smart light).

Use Case 2: Arduino + PIR via COM Port (Hardware Bridge)

Wiring

Same as ESP32: HC-SR501 OUT → digital pin 2, VCC → 5V, GND → GND.

Arduino Sketch (upload via Arduino IDE)

const int pirPin = 2;
int state = 0;

void setup() {
  Serial.begin(115200);
  pinMode(pirPin, INPUT);
}

void loop() {
  int val = digitalRead(pirPin);
  if (val != state) {
    state = val;
    if (val == HIGH) {
      Serial.println("MOTION");
    } else {
      Serial.println("CLEAR");
    }
  }
  delay(100);
}

Connect via Hardware Bridge

  1. Download bridge.py from ASI Biont dashboard (Devices → Create API Key → Download bridge).
  2. Install dependencies: pip install pyserial requests websockets
  3. Run: python bridge.py --token=YOUR_TOKEN --ports=COM3 --baud=115200
    (On Linux/macOS, use /dev/ttyUSB0 or /dev/ttyACM0 instead of COM3.)

  4. In chat with ASI Biont, say: "Read motion data from Arduino on COM3. When I get 'MOTION', publish MQTT message to home/motion/office."

  5. The AI uses industrial_command with serial_write_and_read to poll the device (or sends a command like STATUS\n if your firmware supports it). But since the Arduino just prints, the AI can set up a continuous read via the bridge's polling mechanism.

Important: The bridge does NOT have an HTTP API. All commands go through WebSocket to the cloud. The AI sends serial_write_and_read(data="STATUS\n") and the bridge returns the response.

Real-World Scenarios

Scenario 1: Office Occupancy Tracker

  • Goal: Count how many rooms are occupied and turn off HVAC in empty zones.
  • Hardware: 5 ESP32 + PIR sensors, one per room.
  • Integration: Each publishes to office/roomX/motion. ASI Biont subscribes to all, logs occupancy, and sends Modbus commands to a PLC to control dampers.
  • Outcome: 22% energy savings (based on real building studies by Lawrence Berkeley National Lab).

Scenario 2: Home Security with AI Validation

  • Goal: Reduce false alarms from pets.
  • Hardware: Raspberry Pi with PIR + camera.
  • Integration: ASI Biont reads PIR state via SSH. On motion, it runs a TensorFlow Lite model (via execute_python) to check if the image contains a person. If yes, sends push notification.
  • Outcome: 95% reduction in false alarms.

Scenario 3: Predictive Lighting in Retail

  • Goal: Light shelves only when a customer approaches.
  • Hardware: ESP32 + PIR + relay for LED strip.
  • Integration: ASI Biont learns the typical foot traffic patterns (e.g., peak at 10 AM) and pre-turns on lights 5 minutes before expected motion. Uses publish via MQTT to control relay.
  • Outcome: 18% less electricity used compared to static schedule.

Why This Matters

You don't need to be a firmware expert. ASI Biont's AI writes the integration code for you. You just describe what you want in plain English. The sandbox (execute_python) has all major libraries pre-installed: pyserial, paho-mqtt, pymodbus, requests, aiohttp, and more. No waiting for developers to add support — connect anything right now.

Limitations to Know

  • execute_python runs in the cloud and has a 30-second timeout — use industrial_command for persistent COM/MQTT/Modbus connections.
  • Hardware Bridge is required for local COM port access (Windows/Linux/macOS).
  • The sandbox does NOT have subprocess, threading, or direct filesystem access.

Conclusion

Integrating a PIR motion sensor with ASI Biont turns a simple digital input into an intelligent, context-aware system. Whether you use MQTT, COM port, or SSH, the AI agent handles the heavy lifting — parsing data, triggering actions, and learning patterns. Try it yourself: create a free account at asibiont.com, describe your sensor setup in chat, and watch the AI write the code in seconds.

← All posts

Comments