MQ-* Gas Sensors + ASI Biont: Real-Time Air Quality Monitoring and Automated Response

Every year, millions of homes and factories install gas sensors to detect smoke, carbon monoxide, or volatile organic compounds. Yet a raw analog voltage from an MQ-135 tells you nothing: is 1.2V dangerous? Should you open a window or trigger a shutdown? In a standalone system, you'd need to write custom thresholds, calibration curves, and notification logic. Integrating the sensor with an AI agent like ASI Biont transforms those raw readings into a context-aware response — and the integration takes seconds, not weeks.

In this guide, I'll show you exactly how to connect MQ-2, MQ-135, and MQ-7 sensors to ASI Biont, using both a direct serial (COM) setup and an MQTT-based IoT architecture. We'll walk through a complete example: an MQ-135 monitoring indoor CO2 that controls an exhaust fan and sends Telegram alerts. You'll see the actual Python and MicroPython code, plus how you can set up the whole thing by simply describing your hardware in ASI Biont's chat.

Why MQ-* Sensors Need an AI Layer

MQ-series sensors are analog electrochemical or semiconductor devices. They are cheap, robust, and widely used. However, their output is a voltage that depends on the gas concentration, temperature, and humidity. Calibration is often done by comparing readings in clean air and then applying a logarithmic curve. This is exactly the kind of repetitive, error-prone work that an AI agent can handle.

More importantly, a sensor alone doesn't protect anyone. The value only becomes useful when it:

  • Is compared against historical baselines
  • Triggers a graded response (alert at level 1, ventilation at level 2, shutdown at level 3)
  • Integrates with other data (occupancy, time of day, weather)

That's the sweet spot for ASI Biont. Instead of hard-coding every rule, you ask the agent to "monitor the air quality and react if it degrades rapidly," and it writes the logic.

Understanding the MQ Family

Let's quickly compare the three most common sensors. This isn't a full datasheet, but enough to choose the right one.

Sensor Target Gases Typical Applications Peak Sensitivity
MQ-2 LPG, i-butane, propane, methane, smoke Home gas leak detection, fire alarm ~200–5000 ppm (LPG)
MQ-135 NH₃, NOₓ, alcohol, benzene, smoke, CO₂ Air quality monitors, ventilation control 10–10000 ppm (NH₃)
MQ-7 Carbon monoxide CO alarms, parking garages, vehicle exhaust monitoring 20–2000 ppm (CO)

All of them have a heater element and an analog output that varies with resistance. The typical interface circuit uses a load resistor (often 1 kΩ to 10 kΩ). The analog voltage goes into an ADC on an Arduino, ESP32, or Raspberry Pi.

How ASI Biont Connects to the Rest of the World

ASI Biont supports a wide range of industrial protocols out of the box: Modbus/TCP, OPC-UA, MQTT, BACnet, CAN bus, and more. For a non-standard device like an MQ-* sensor, you have two solid options:

  1. Hardware Bridge (COM port) – If your Arduino or ESP32 is connected over USB/serial, you can use the bridge.py utility (downloaded from the ASI Biont dashboard) to stream serial data into the AI agent. This is great for lab setups and local testing.

  2. MQTT – If your sensor node is remote or you already have a broker (e.g., Mosquitto), publish readings to a topic and let ASI Biont subscribe. This scales better for multiple rooms or buildings.

Some people use Modbus with an industrial analog-to-digital converter like the ADAM-4117, but MQTT and serial are the most direct for MQ-* sensors.

In addition, ASI Biont has a universal execute_python capability. You don't need to wait for a pre-built driver. You tell the agent which port or broker to use, and it writes a Python script with pyserial, paho-mqtt, or aiohttp on the spot. This is the key to connecting any device, including a custom gas sensor rig.

Case Study: Smart Ventilation with MQ-135 and ASI Biont

Let's say we want to keep the CO2 level in a home office below 1000 ppm. We have an ESP32 with an MQ-135 on ADC pin 34. The ESP32 publishes the raw voltage (or a converted "air quality" index) every 5 seconds to an MQTT broker. ASI Biont runs on a PC or server, subscribes to the topic, applies a rolling average, and when the value exceeds a threshold, it sends a Telegram message to the owner and publishes a command to a smart relay that turns on the ventilation fan.

Step 1 – MicroPython on the ESP32

Here's the node code:

# main.py on ESP32 (MicroPython)
from machine import ADC, Pin, Timer
import ubinascii, network, ujson
from umqtt.simple import MQTTClient

adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)  # 0-3.3V range

WIFI_SSID = 'home'
WIFI_PASS = 'password'
MQTT_BROKER = '192.168.1.50'
TOPIC = 'sensors/mq135/raw'

# ... connect wifi ...
client = MQTTClient('mq135', MQTT_BROKER)
client.connect()

def read_and_publish(timer):
    raw = adc.read()  # 12-bit value 0-4095
    voltage = raw / 4095 * 3.3
    payload = ujson.dumps({'v': round(voltage, 3), 'raw': raw})
    client.publish(TOPIC, payload)

tim = Timer(0)
tim.init(period=5000, mode=Timer.PERIODIC, callback=read_and_publish)

Don't worry about the exact calibration curve here. The point is that the data is now flowing.

Step 2 – The ASI Biont Integration

On the ASI Biont side, you would say (in chat):

"Subscribe to MQTT broker 192.168.1.50, topic sensors/mq135/raw. Compute 5-minute rolling average. If voltage > 1.5V, send Telegram alert to my chat and publish 'on' to topic relay/fan."

ASI Biont then writes and executes a Python script internally. A simplified version of what it generates looks like this:

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

TELEGRAM_BOT_TOKEN = '123456:ABC...'
TELEGRAM_CHAT_ID = '987654321'
BROKER = '192.168.1.50'
SUB_TOPIC = 'sensors/mq135/raw'
CTRL_TOPIC = 'relay/fan'

window = []

def on_message(client, userdata, msg):
    global window
    value = float(dict(eval(msg.payload))['v'])
    window.append(value)
    if len(window) > 60:  # 5 minutes at 5s
        window.pop(0)
    avg = sum(window) / len(window)
    if avg > 1.5:
        client.publish(CTRL_TOPIC, 'on')
        requests.post(
            f'https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage',
            json={'chat_id': TELEGRAM_CHAT_ID, 'text': f'High CO2: {avg:.2f} V'}
        )
    else:
        client.publish(CTRL_TOPIC, 'off')

client = mqtt.Client()
client.on_message = on_message
client.connect(BROKER)
client.subscribe(SUB_TOPIC)
client.loop_forever()

Of course, the actual generated code is more robust — with error handling, reconnect logic, and the calibration formula. But this gives you the idea. The AI handles the MQTT details, the Telegram API, and the threshold logic.

Step 3 – Direct Serial Connection via Hardware Bridge

If you don't want to set up an MQTT broker, you can connect your Arduino directly to the machine running ASI Biont using a COM port. First, download bridge.py from the ASI Biont dashboard (it's not on GitHub). Then run:

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

On the Arduino side, you'd print a JSON line like {"sensor":"mq7","value":1.23} over UART. In ASI Biont's chat, you'd say:

"Read data from COM4, parse JSON, monitor CO levels."

The AI then uses industrial_command(protocol='com', command='get_data', ...) to talk to the bridge. Here's a minimal example of how the AI might use that API:

# Generated by ASI Biont
from asibiont_agent import industrial_command

response = industrial_command(
    protocol='com',
    command='read_line',
    port='COM4',
    timeout=2
)

Note: the bridge.py tool does not have an HTTP API — it's a serial bridge, so the AI uses industrial_command() directly.

Calibrating MQ-* Sensors

One of the trickiest parts of working with MQ-* sensors is calibration. The datasheet (e.g., from Hanwei Electronics, available at www.hanwei-electronics.com) provides a sensitivity curve based on the ratio of the sensor resistance in clean air (Ro) to the resistance in target gas (Rs). The general relationship is:

Rs/Ro = A * concentratiion^(-B)

where A and B are characteristic constants for each gas. In practice, you can calibrate by measuring the voltage in clean air and setting Ro to that value. ASI Biont can automate this process: you describe a known clean-air environment, and the AI writes a Python script that collects data for 10 minutes and computes Ro. Then it converts future readings to ppm or a simple air-quality index.

Choosing the Right Sensor for Your Case

Let's be concrete:

  • MQ-2 is the go-to for LPG / natural gas detection in kitchens. Connect it to a relay that cuts off the gas valve when a threshold is exceeded.
  • MQ-135 is a general air quality sensor. In our case study, it's perfect for triggering ventilation because it's sensitive to CO2, smoke, and VOCs.
  • MQ-7 is specifically for carbon monoxide. It's often used in parking garages to control exhaust fans.

A strong setup uses more than one sensor. For example, an MQ-7 for CO and an MQ-135 for CO2 in a car park. ASI Biont can fuse both data streams and decide whether to turn on one fan or two.

Beyond Thresholds: AI-Powered Analysis

The real advantage of ASI Biont is that you're not limited to static thresholds. You can ask for:

  • Trend detection: "I noticed that CO2 rises sharply every day at 16:00. Find out why."
  • Anomaly detection: "Send an alert if the sensor readings jump by more than 2% within a minute."
  • Predictive maintenance: "If the sensor response time becomes slower, it might be contaminated. Calibrate it?"

These tasks are trivial to describe, and the AI turns them into code loops, statistical tests, and periodic tasks — all through the chat interface.

How to Get Started

  1. Connect your MQ-* sensor to a microcontroller (ESP32/Arduino) or an industrial ADC.
  2. Decide on a transport: MQTT, COM port via bridge, or even Modbus if you have a converter.
  3. Open ASI Biont chat and describe your device: "I have an ESP32 publishing MQ-2 values to mqtt://192.168.1.5/topic/gas. Please trigger a relay if smoke is detected."
  4. Let the AI generate and execute the integration. If something doesn't work, feed the error back and it will fix the script.

Because ASI Biont uses execute_python, you can connect devices that aren't in any official list. If you can read from it with Python, ASI Biont can interface with it. There's no need to wait for a vendor plugin.

References

Final Thoughts

The days of writing thousands of lines of firmware glue for a single sensor are over. With ASI Biont, an MQ-* sensor goes from a vague voltage signal to an active, communicating safety device in minutes. Whether it's a home gas alarm, an industrial ventilation system, or an environmental monitoring station, the process is the same: describe, deploy, refine.

If you have an MQ-2 or MQ-135 sitting in your drawer, now is the time to bring it to life.

Try the integration yourself at asibiont.com — no dashboards, just a chat.

← All posts

Comments