Introduction
Air quality monitoring is no longer a luxury—it's a necessity. From detecting natural gas leaks in smart homes to measuring CO levels in industrial workshops, the MQ series of gas sensors (MQ-2, MQ-7, MQ-135) have become the go-to choice for makers and engineers. These analog sensors are affordable, widely available, and capable of detecting gases like LPG, methane, smoke, carbon monoxide, and ammonia. But raw sensor data is just voltage readings. To turn that into actionable intelligence—automatic alerts, trend analysis, and cross-device automation—you need an AI agent that can interpret, decide, and act. That's exactly what ASI Biont brings to the table.
In this guide, we'll walk through a real-world integration of an MQ-135 sensor (air quality) with an ESP32 microcontroller, connected to ASI Biont via MQTT. You'll see how the AI agent reads sensor values, detects dangerous thresholds, and sends Telegram notifications—all without writing a single line of boilerplate. By the end, you'll understand why connecting any sensor to ASI Biont is a game-changer for rapid prototyping and production deployments.
Why Connect MQ Sensors to an AI Agent?
Traditional sensor logging involves writing firmware, setting up a database, and building a dashboard. That's weeks of work. With ASI Biont, you just describe your hardware setup in natural language, and the AI generates the integration code—complete with MQTT publish, threshold logic, and notification hooks. The result: you get a smart gas detector that learns from data and acts autonomously, without manual coding.
Choosing the Right Connection Method
For our use case, we'll use MQTT (Message Queuing Telemetry Transport) via the paho-mqtt library. Why MQTT?
- It's lightweight and ideal for IoT devices with limited bandwidth.
- ESP32 has native MQTT support through libraries like PubSubClient.
- ASI Biont's execute_python sandbox includes paho-mqtt, allowing the AI to subscribe and publish to the same broker.
Other possible methods for MQ sensors:
- Hardware Bridge + COM port if you connect the sensor directly to a PC via Arduino.
- SSH if the sensor is attached to a Raspberry Pi running a Python script.
- HTTP API if the sensor is part of a commercial smart-home hub.
For this tutorial, we assume an ESP32 running MicroPython, publishing sensor data every 10 seconds to an MQTT broker (e.g., Mosquitto running locally or on a cloud VM).
Real-World Use Case: Smart Air Quality Monitor with Telegram Alerts
Scenario
You have an MQ-135 sensor connected to an ESP32 in your living room. You want ASI Biont to:
- Read the air quality index (AQI) every 10 seconds via MQTT.
- Detect when CO2 or smoke levels exceed safe thresholds.
- Send an immediate Telegram alert to your phone.
- Log all readings for later analysis.
Hardware Setup
- ESP32 Dev Board (e.g., ESP32-WROOM-32)
- MQ-135 Gas Sensor (analog output to GPIO34)
- MQTT Broker (Mosquitto on a Raspberry Pi or cloud)
- Power supply (5V micro USB)
Wiring: MQ-135 VCC → ESP32 3.3V, GND → GND, AO → GPIO34.
Step 1: ESP32 Firmware (MicroPython)
import machine
import time
import ujson
from umqtt.simple import MQTTClient
# MQTT config
BROKER = "192.168.1.100"
TOPIC = "home/airquality"
CLIENT_ID = "esp32_mq135"
# Sensor setup
adc = machine.ADC(34)
adc.atten(machine.ADC.ATTN_11DB) # 0-3.6V range
def read_sensor():
raw = adc.read() # 0-4095
voltage = raw / 4095.0 * 3.3
# MQ-135 typical conversion (simplified)
ppm = voltage * 100 # approximate
return {"raw": raw, "voltage": round(voltage, 2), "ppm": round(ppm, 1)}
def connect_mqtt():
client = MQTTClient(CLIENT_ID, BROKER)
client.connect()
print("Connected to MQTT broker")
return client
client = connect_mqtt()
while True:
data = read_sensor()
payload = ujson.dumps(data)
client.publish(TOPIC, payload)
print("Published:", payload)
time.sleep(10)
Upload this script to the ESP32 using ampy or Thonny. The sensor now publishes JSON like {"raw": 2048, "voltage": 1.65, "ppm": 165.0} to topic home/airquality.
Step 2: ASI Biont Integration via Chat
Open the ASI Biont chat and describe your setup:
"Connect to MQTT broker at 192.168.1.100, subscribe to topic home/airquality. Read the ppm value. If ppm exceeds 200, send a Telegram alert to chat ID 123456789 using bot token ABCDEF. Also log all readings to a CSV file every minute."
ASI Biont will generate and execute a Python script using paho-mqtt and telegram-send (or requests to Telegram API). Here's a simplified version of what the AI produces:
import paho.mqtt.client as mqtt
import json
import csv
import os
from datetime import datetime
# Telegram config
TELEGRAM_BOT_TOKEN = "YOUR_BOT_TOKEN"
TELEGRAM_CHAT_ID = "123456789"
# CSV logging
CSV_FILE = "air_quality_log.csv"
if not os.path.exists(CSV_FILE):
with open(CSV_FILE, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(["timestamp", "raw", "voltage", "ppm"])
def send_telegram_alert(message):
import requests
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {"chat_id": TELEGRAM_CHAT_ID, "text": message}
requests.post(url, json=payload)
def on_message(client, userdata, msg):
try:
data = json.loads(msg.payload)
ppm = data["ppm"]
print(f"Received: {data}")
# Log to CSV
with open(CSV_FILE, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([datetime.now(), data["raw"], data["voltage"], ppm])
# Threshold check
if ppm > 200:
alert = f"⚠️ Air quality alert! PPM = {ppm} (threshold: 200)"
send_telegram_alert(alert)
print("Alert sent!")
except Exception as e:
print(f"Error: {e}")
client = mqtt.Client()
client.on_message = on_message
client.connect("192.168.1.100", 1883, 60)
client.subscribe("home/airquality")
print("Listening for sensor data...")
client.loop_forever()
The AI runs this script in the sandbox (with a 30-second timeout for initial testing). It immediately subscribes, processes incoming data, writes to CSV, and sends alerts—all without you writing a single line of integration code.
Step 3: Testing and Results
Once the script is running, you can see live output in the chat:
Listening for sensor data...
Received: {'raw': 2048, 'voltage': 1.65, 'ppm': 165.0}
Received: {'raw': 2100, 'voltage': 1.70, 'ppm': 170.0}
...
Received: {'raw': 2800, 'voltage': 2.26, 'ppm': 226.0}
Alert sent! Telegram notification delivered.
The Telegram message arrives within seconds:
⚠️ Air quality alert! PPM = 226.0 (threshold: 200)
Why This Approach Wins
- Zero boilerplate: No need to learn MQTT libraries or Telegram API details—the AI writes the glue code.
- Fast iteration: Change thresholds, add new sensors, or switch notification channels by simply chatting.
- Scalable: The same pattern works for thousands of sensors across multiple locations.
- Open standards: MQTT is vendor-neutral; you can swap the ESP32 for any MQTT-capable device.
Beyond MQTT: Other Integration Paths
ASI Biont isn't limited to MQTT. Depending on your hardware, you can use:
| Connection Method | Typical Use Case | Library Used |
|---|---|---|
| COM port | Arduino with MQ-2 sensor connected via USB | pyserial via Hardware Bridge |
| SSH | Raspberry Pi reading MQ-7 via GPIO | paramiko + RPi.GPIO |
| HTTP API | Smart home hub with gas sensor REST endpoint | aiohttp |
| Modbus TCP | Industrial gas detector with Modbus interface | pymodbus |
For example, if you have an Arduino Uno with an MQ-7 sensor connected via USB, you'd run bridge.py on your PC (downloaded from the ASI Biont dashboard), specify --ports=COM3 --baud 115200, and then tell the AI: "Connect to COM3 via bridge, read sensor data every 5 seconds, and send an email if CO level exceeds 100 ppm." The AI handles the serial protocol and email integration.
Practical Tips for Production
- Calibration: MQ sensors need a warm-up period (24-48 hours for initial burn-in). Use the AI to log baseline data and automatically calibrate thresholds.
- Redundancy: Use multiple sensors and let the AI average readings or detect faulty sensors by comparing outliers.
- Data Persistence: The AI can write to PostgreSQL, MongoDB, or simply append to a CSV file—just ask.
- Alerts: Combine Telegram with email or Slack for failover. The AI can manage multiple notification channels.
Conclusion
Connecting MQ gas sensors to an AI agent transforms them from simple voltage generators into intelligent safety sentinels. With ASI Biont, the integration is conversational: you describe your hardware, define the logic, and the AI writes and runs the code—all within minutes. Whether you're building a home air quality monitor, an industrial gas leak detector, or a research-grade environmental station, ASI Biont eliminates the coding overhead and lets you focus on what matters: the data and the decisions.
Ready to make your sensors smart? Try the integration today at asibiont.com. Describe your setup in the chat, and watch the AI connect, control, and alert—instantly.
Comments