Introduction
Gas sensors from the MQ-* family (MQ-2, MQ-3, MQ-4, MQ-5, MQ-6, MQ-7, MQ-8, MQ-9, MQ-135, MQ-136, MQ-137, etc.) are among the most widely used analog gas detectors in IoT projects. They can detect a range of gases: LPG, methane, carbon monoxide, hydrogen, ammonia, alcohol, smoke, and air quality indicators like CO₂ and NOx. However, raw analog readings from these sensors are noisy, drift over time, and require calibration and context-aware logic to be useful. Connecting them to an AI agent like ASI Biont transforms them from simple threshold triggers into intelligent environmental monitors that can learn patterns, predict hazardous conditions, and automate responses — all without manual coding of complex rules.
Why Integrate MQ-* Sensors with an AI Agent?
Traditional MQ sensor setups rely on fixed thresholds: if the analog value exceeds X, trigger an alarm. This approach suffers from false positives due to temperature/humidity drift, sensor aging, and transient spikes. An AI agent can:
- Apply dynamic calibration using baseline drift compensation.
- Correlate readings with other sensors (temperature, humidity, time of day) to reduce false alarms.
- Use historical data to predict gas concentration trends and preemptively trigger ventilation.
- Send targeted alerts via Telegram, email, or SMS only when patterns indicate real danger.
ASI Biont connects to your MQ sensor system via MQTT — the most suitable protocol for IoT edge devices like ESP32. The sensor data flows from the microcontroller to an MQTT broker (e.g., Mosquitto), and ASI Biont subscribes to the topic, analyzes the data in real time using Python scripts, and publishes control commands back to the broker.
Connection Architecture
[MQ-135 Sensor] --(analog)--> [ESP32] --(WiFi/MQTT)--> [Mosquitto Broker] --(MQTT)--> [ASI Biont AI Agent]
|
v
[Telegram Bot / Relay / Ventilation]
The user describes the setup in natural language chat: "Connect to my MQ-135 sensor via MQTT on broker at 192.168.1.100:1883, topic 'home/air/gas', username 'sensor', password 'mqttpass'. Read every 10 seconds and send alert if CO2 exceeds 1000 ppm." ASI Biont then writes and executes the Python integration script using paho-mqtt.
Step-by-Step Integration
1. Hardware Setup
| Component | Example | Notes |
|---|---|---|
| MQ-* sensor | MQ-135 (air quality) | Analog output, requires ADC |
| Microcontroller | ESP32 | Built-in WiFi, 12-bit ADC |
| MQTT Broker | Mosquitto on Raspberry Pi or cloud | Lightweight, open-source |
| Actuator (optional) | 5V relay for fan | Controlled via GPIO |
Wiring for MQ-135:
- VCC → 5V (ESP32 Vin)
- GND → GND
- AO → GPIO34 (ADC)
- DO → (optional digital threshold, not used here)
2. Microcontroller Firmware (MicroPython)
Save the following as main.py on ESP32. It reads the analog voltage, converts to PPM using the sensor's characteristic curve (simplified), and publishes via MQTT every 10 seconds.
import network
import time
from machine import Pin, ADC
from umqtt.simple import MQTTClient
# WiFi credentials
WIFI_SSID = "YourSSID"
WIFI_PASS = "YourPassword"
# MQTT broker
BROKER = "192.168.1.100"
PORT = 1883
USER = "sensor"
PASS = "mqttpass"
TOPIC_GAS = "home/air/gas"
# Sensor config
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB) # 0-3.6V range
# Connect WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print("WiFi connected")
# MQTT connect
client = MQTTClient("esp32_gas", BROKER, port=PORT, user=USER, password=PASS)
client.connect()
print("MQTT connected")
# Simplified conversion: raw ADC to approx PPM (needs calibration)
def read_gas_ppm():
raw = adc.read() # 0-4095
voltage = raw / 4095 * 3.3
# For MQ-135, approximate CO2 PPM = 116.602 * (voltage/0.5)^(-2.769)
# This is a rough curve from datasheet; calibrate with known gas
if voltage < 0.1:
return 400 # ambient CO2 baseline
ppm = 116.602 * (voltage / 0.5) ** (-2.769)
return round(ppm, 1)
while True:
ppm = read_gas_ppm()
msg = f'{{"co2_ppm": {ppm}, "device": "esp32_mq135"}}'
client.publish(TOPIC_GAS, msg)
print("Published:", msg)
time.sleep(10)
3. ASI Biont Integration (User Describes in Chat)
The user opens chat with ASI Biont and says:
Connect to MQTT broker at 192.168.1.100:1883, topic 'home/air/gas', username 'sensor', password 'mqttpass'. Subscribe and parse JSON with co2_ppm field. If value exceeds 1000 ppm, publish to topic 'home/air/vent' message 'ON'. Also send me a Telegram alert with current ppm value. Run continuously.
ASI Biont writes and executes a Python script using paho-mqtt:
import paho.mqtt.client as mqtt
import json
import time
BROKER = "192.168.1.100"
PORT = 1883
USER = "sensor"
PASS = "mqttpass"
TOPIC_GAS = "home/air/gas"
TOPIC_VENT = "home/air/vent"
# Telegram alert via bot (user provides token/chat_id)
TELEGRAM_TOKEN = "your_bot_token"
TELEGRAM_CHAT_ID = "your_chat_id"
def send_telegram(text):
import requests
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
requests.post(url, json={"chat_id": TELEGRAM_CHAT_ID, "text": text})
def on_message(client, userdata, msg):
try:
data = json.loads(msg.payload.decode())
ppm = data.get("co2_ppm", 0)
if ppm > 1000:
# Publish vent ON
client.publish(TOPIC_VENT, "ON")
alert = f"⚠️ CO2 high: {ppm} ppm. Ventilation activated."
send_telegram(alert)
print(alert)
else:
print(f"CO2 = {ppm} ppm - normal")
except Exception as e:
print("Parse error:", e)
client = mqtt.Client()
client.username_pw_set(USER, PASS)
client.on_message = on_message
client.connect(BROKER, PORT, 60)
client.subscribe(TOPIC_GAS)
print(f"Subscribed to {TOPIC_GAS}")
client.loop_forever()
The script runs inside ASI Biont's sandbox (execute_python) with a 30-second timeout per cycle. To keep it running continuously, ASI Biont uses a scheduling mechanism (the user can say "run this every 10 seconds"). The sandbox environment includes paho-mqtt, requests, and all standard libraries.
4. No-Code Configuration via Chat
The user does not write a single line of Python manually. They simply describe:
- Broker address, port, credentials
- Subscribe topic
- Threshold value
- Action: publish command or send Telegram alert
ASI Biont generates the correct code, tests it, and runs it. If the sensor needs calibration, the user can say: "Calibrate MQ-135 by reading baseline for 5 minutes and adjust the PPM formula" — ASI Biont will modify the MicroPython code or adjust the conversion in the cloud script.
Real Business Use Cases
| Scenario | Sensor | Action |
|---|---|---|
| Smart home | MQ-2 (LPG/methane) | Detect gas leak → shut off gas valve via relay + notify owner |
| Office air quality | MQ-135 (CO2) | CO2 > 1000 ppm → enable HRV fan, send Slack alert to facility manager |
| Greenhouse | MQ-136 (H2S) | H2S > 5 ppm → open exhaust windows, alert via Telegram |
| Industrial safety | MQ-7 (CO) | CO > 50 ppm → alarm + emergency stop of combustion equipment |
| Parking garage | MQ-9 (CO, LPG) | High CO → start extraction fans, log to database |
Advantages of AI-Powered Integration
- Zero manual coding: The AI writes both the microcontroller firmware and the backend logic based on natural language description.
- Adaptive thresholds: Instead of static limits, the AI can adjust thresholds based on time of day, historical baselines, or weather data.
- Multi-sensor fusion: Combine MQ-2, MQ-135, and DHT22 to distinguish between real gas leak and cooking fumes.
- Predictive alerts: The AI can detect rising trends before they hit the threshold and warn proactively.
- Easy updates: Change any parameter by simply telling the AI in chat — no firmware reflash needed for cloud-side logic.
Conclusion
Integrating MQ-* gas sensors with ASI Biont turns a basic analog sensor into an intelligent environmental guardian. The AI agent handles the entire integration — from writing the ESP32 firmware to deploying the MQTT subscriber and triggering automated actions via Telegram, relays, or other IoT devices. You don't need to be a programmer; just describe your hardware and requirements in plain English. Try it today at asibiont.com and experience the future of AI-driven IoT automation.
Comments