AI & Agents

How to Build a Smoke and Fire Detection Agent with OpenClaw on Raspberry Pi

Standard Raspberry Pi smoke detector projects fire an alarm whenever sensor voltage crosses a threshold, which means your kitchen toast can trigger the same response as an actual fire. This guide covers wiring an MQ-2 gas sensor to a Pi, then running an OpenClaw agent that interprets readings in context, distinguishes cooking smoke from dangerous conditions, and sends targeted emergency notifications when they actually matter.

Fast.io Editorial Team 16 min read
AI agent orchestrating automated detection and alert workflows from a cloud workspace

Why Threshold-Based Smoke Detection Falls Short

Home fires caused an estimated $11.4 billion in property damage across 329,500 incidents in the US in 2024, according to the Insurance Information Institute. Most of those fires started small and could have been caught earlier with better detection. The problem is not a lack of sensors. It is a lack of interpretation.

The typical Raspberry Pi smoke detector project wires an MQ-2 gas sensor to a GPIO pin, reads the analog voltage through an ADC, and trips an alarm when the value exceeds a fixed number. That works in a controlled demo. In a real home, cooking dinner, lighting a candle, or running a gas stove all push the MQ-2's readings past common threshold values. After a few false alarms at 2 AM because someone made popcorn, most people disconnect the project or raise the threshold so high that it misses actual smoke.

Commercial smart smoke detectors solve this with proprietary algorithms and multi-sensor fusion, but they cost $100 to $250 per unit and lock you into a vendor's app ecosystem. An MQ-2 sensor module costs under $3. The gap between a $3 sensor and a $200 smart detector is not hardware. It is software that can reason about what the sensor is actually detecting.

An OpenClaw agent running on the same Raspberry Pi fills that gap. Instead of a hardcoded threshold, the agent evaluates sensor readings against context: time of day, rate of change, duration, and correlation with other data points. Smoke from pan-frying at 6 PM gets a different response than the same reading at 3 AM when nobody should be cooking. The sensor hardware stays cheap. The intelligence layer is what makes it useful.

This guide covers the full build: selecting and wiring the MQ-2 sensor, adding an analog-to-digital converter, configuring OpenClaw for contextual smoke detection, and setting up tiered alert responses.

What to check before scaling openclaw raspberry pi smoke fire alarm detection agent

The MQ-2 is the most common gas sensor for Raspberry Pi smoke detection projects, and for good reason. It detects smoke particles, methane, butane, LPG, and hydrogen using a tin dioxide (SnO2) sensing element whose conductivity increases in the presence of combustible gases. Breakout modules with built-in comparator circuits are available from SparkFun, Adafruit, and dozens of vendors for $2-5 each.

MQ-2 module options

Most MQ-2 breakout boards expose two outputs: an analog voltage (A0) that varies proportionally with gas concentration, and a digital output (D0) that goes LOW when concentration exceeds a threshold set by an onboard potentiometer. For an OpenClaw agent build, you want the analog output. The digital output reduces everything to a binary yes/no, which is exactly the dumb-threshold approach you are trying to improve on.

Why you need an ADC

The Raspberry Pi's GPIO pins are digital-only. They cannot read the MQ-2's analog voltage directly. You need an analog-to-digital converter (ADC) chip between the sensor and the Pi. The MCP3008 is the standard choice: 8 channels, 10-bit resolution, SPI interface, and costs $3-5. The MCP3002 is a cheaper 2-channel alternative if you only need one or two analog sensors. Both communicate over SPI, which the Pi supports natively.

Optional: adding a temperature sensor

A DHT22 or BME280 temperature and humidity sensor ($3-8) gives the agent additional context for reasoning. A sudden spike in temperature alongside rising smoke readings strongly suggests fire rather than cooking. The BME280 communicates over I2C and provides temperature, humidity, and barometric pressure. The DHT22 uses a single-wire protocol on any GPIO pin.

Optional: adding a flame sensor

An IR flame sensor module ($2-3) detects infrared radiation in the 760-1100nm wavelength range, which is characteristic of open flames. Adding this to the MQ-2 gives the agent two independent signals. Smoke plus IR detection is a much stronger indicator of actual fire than either signal alone.

Complete parts list

  • Raspberry Pi 5 (8GB) or Pi 4 (4GB minimum)
  • MQ-2 gas sensor module
  • MCP3008 or MCP3002 ADC chip
  • BME280 temperature/humidity sensor (optional but recommended)
  • IR flame sensor module (optional)
  • Buzzer module or relay for audible alarm
  • Jumper wires, breadboard
  • 5V power supply for the Pi

Total sensor cost: under $15 for the core setup, under $25 with all optional sensors. Compare that to $100-250 for a single commercial smart smoke detector.

Layered hardware architecture showing sensor connections to a central controller

Wiring and Circuit Setup

The MQ-2 needs 5V to power its heater element, and the MCP3008 ADC bridges the analog output to the Pi's SPI bus. Here is the wiring for each component.

MCP3008 ADC connections (SPI)

The MCP3008 has 16 pins. The left side (CH0-CH7) accepts analog inputs. The right side connects to the Pi's SPI interface:

  • VDD to 3.3V (pin 1)
  • VREF to 3.3V (pin 1)
  • AGND to GND (pin 6)
  • CLK to GPIO 11 / SCLK (pin 23)
  • DOUT to GPIO 9 / MISO (pin 21)
  • DIN to GPIO 10 / MOSI (pin 19)
  • CS to GPIO 8 / CE0 (pin 24)
  • DGND to GND (pin 6)

MQ-2 sensor connections

  • VCC to 5V (pin 2)
  • GND to GND (pin 6)
  • A0 (analog out) to MCP3008 CH0

The MQ-2 runs on 5V but its analog output voltage stays within the 0-3.3V range at typical smoke concentrations, so connecting A0 directly to the MCP3008 (referenced to 3.3V) works without a voltage divider for most modules. If your specific module outputs above 3.3V at high concentrations, add a simple resistor voltage divider between A0 and CH0.

BME280 connections (I2C)

  • SDA to GPIO 2 (pin 3)
  • SCL to GPIO 3 (pin 5)
  • VIN to 3.3V (pin 1)
  • GND to GND (pin 9)

The BME280 defaults to I2C address 0x76. Run i2cdetect -y 1 after wiring to confirm the device is visible.

IR flame sensor (digital GPIO)

  • VCC to 3.3V (pin 1)
  • GND to GND (pin 14)
  • D0 to GPIO 17 (pin 11)

The digital output goes LOW when flame is detected.

Buzzer or relay

  • Signal to GPIO 27 (pin 13)
  • VCC to 5V (pin 4)
  • GND to GND (pin 20)

Enabling SPI and I2C

Run raspi-config, navigate to Interface Options, and enable both SPI and I2C. Reboot after making changes. Install the Python libraries for hardware access: the spidev library for SPI communication with the MCP3008, the adafruit-circuitpython-bme280 library for the temperature sensor, and RPi.GPIO for the flame sensor and buzzer control.

MQ-2 warm-up period

The MQ-2 sensor requires a burn-in period of 24-48 hours on first use and a warm-up period of 2-3 minutes on each subsequent power-on before its readings stabilize. During warm-up, the analog output drifts and should not be used for detection decisions. Build this into your startup sequence: power on the sensor, wait for readings to stabilize, then begin monitoring.

Fastio features

Store Smoke Detection Logs Where Any Agent Can Search Them

Upload sensor readings and agent decision logs to a Fast.io workspace. Intelligence Mode indexes everything for natural language queries across months of detection history. 50GB free, no credit card required. Built for openclaw raspberry smoke fire alarm detection agent workflows.

Configuring the OpenClaw Agent for Contextual Smoke Detection

OpenClaw runs on Raspberry Pi 5 (8GB recommended) or Pi 4 with at least 4GB RAM. The official installer handles dependencies and service setup. Once running, the agent needs sensor polling scripts, a reasoning framework, and output actions.

Sensor polling scripts

Create Python scripts that return structured JSON from each sensor. A read_smoke.py script initializes the MCP3008 over SPI, reads channel 0, converts the raw 10-bit value (0-1023) to a voltage, and outputs a JSON object with the raw ADC value, calculated voltage, and a rough gas concentration estimate. A read_environment.py script queries the BME280 and returns temperature, humidity, and pressure. A read_flame.py script checks GPIO 17 and returns whether the IR sensor has detected flame radiation.

The agent calls these scripts as system commands and receives the structured data for reasoning. Poll every 5-10 seconds during active monitoring. Smoke conditions can escalate fast, so the interval needs to be tighter than an air quality monitor that polls every minute.

Contextual reasoning framework

This is where an OpenClaw agent outperforms a threshold script. Instead of firing an alarm at a fixed ADC value, the agent evaluates multiple factors:

  • Is the smoke reading rising, stable, or falling? A brief spike that drops back to baseline within 30 seconds is likely toast or a match. A reading that climbs steadily over 2 minutes suggests a growing problem.
  • What is the rate of change? A slow drift from 200 to 350 over 10 minutes is different from a jump from 200 to 600 in 30 seconds. Rapid acceleration suggests combustion, not cooking.
  • What time is it? Elevated smoke readings during typical cooking hours (6-8 AM, 11 AM-1 PM, 5-8 PM) get a higher tolerance before alerting. The same readings at 3 AM trigger immediate response.
  • What does the temperature sensor show? If the BME280 registers a rapid temperature increase alongside rising smoke, the probability of actual fire increases . Cooking smoke without a corresponding temperature spike near the sensor is less alarming.
  • Is the flame sensor triggered? Smoke plus flame detection from the IR sensor should bypass all tolerance windows and trigger an immediate alert.

OpenClaw supports cloud LLM providers (Claude, GPT-4, Gemini) for stronger reasoning and local models through Ollama for zero-latency, offline operation. For smoke detection, local models are worth considering seriously. A house fire is not the time for your safety system to fail because of an internet outage or API rate limit. Running a small local model through Ollama means the agent reasons about sensor data even when the network is down.

Tiered alert responses

Not every elevated reading needs the same response. Configure the agent with escalating actions:

  • Level 1 (elevated, possibly cooking): Log the event. If readings persist beyond 5 minutes, send a low-priority push notification asking if everything is okay.
  • Level 2 (sustained and rising): Activate the buzzer for a short burst. Send a push notification to all household members via Telegram, Slack, or Pushover webhook.
  • Level 3 (rapid rise, high concentration, or flame detected): Continuous buzzer. Send emergency notifications to all contacts. Log detailed sensor data and agent reasoning for review.

The agent can also de-escalate. If someone acknowledges a Level 1 alert and readings drop within a few minutes, the agent returns to normal monitoring without further notifications.

AI system analyzing data patterns with structured audit capabilities

Logging Detection Events and Sensor Data to Fast.io

A smoke detection system needs reliable logging for two reasons: reviewing what happened after an incident, and establishing baseline patterns that improve future detection accuracy. Local logging to SQLite or CSV files on the Pi works for single-device setups, but creates data you can only access by SSHing into the device. For shared households or multi-room deployments, centralized storage with search capabilities is more practical.

Standard options like InfluxDB with Grafana handle numeric time-series data well. You get dashboards showing smoke levels over time, and threshold alerts on the Grafana side. The limitation is that InfluxDB stores numbers, not the agent's reasoning. You can see that smoke readings spiked at 2:47 AM, but not why the agent decided it was a false alarm from a candle versus an actual hazard.

Fast.io workspaces store both the sensor readings and the agent's decision logs in a format that is searchable by meaning. Upload a JSON log after each detection event, and Intelligence Mode indexes the content for natural language queries. Six months later, you can ask "how many times did cooking trigger a smoke alert in the kitchen" or "show me every time the agent escalated to Level 3" and get answers drawn from the full history.

The Fast.io MCP server gives the OpenClaw agent direct workspace access for uploads, queries, and file management. The free agent plan includes 50GB storage and 5,000 monthly credits with no credit card required. At roughly 1KB per detection event log, 50GB stores years of continuous monitoring data.

Practical logging workflow

After each decision cycle, the agent writes a structured log entry: timestamp, all sensor readings, the assessment (normal, elevated, alert), actions taken, and reasoning. During normal operation, batch these entries and upload once per hour. During alert conditions, upload immediately so the event record is preserved even if the Pi loses power.

This also supports ownership transfer. If you build a smoke detection system for someone else, you can configure the workspace, train the baseline, and then transfer ownership to the homeowner. They get the workspace with all historical data and ongoing uploads. You keep admin access for remote troubleshooting.

Safety Considerations and Practical Limits

This is a supplementary monitor, not a primary safety device. A Raspberry Pi with an MQ-2 sensor is not a substitute for a UL-listed, code-compliant smoke detector. Building codes in most US jurisdictions require photoelectric or ionization smoke alarms that meet UL 217 or EN 14604 standards. These devices have battery backup, standardized alarm volume, and decades of testing behind them. Your Pi project has none of that. Install proper smoke detectors first. Use the OpenClaw agent as a smart overlay that adds contextual awareness and remote notifications on top of code-compliant hardware.

MQ-2 sensor limitations. The MQ-2 is a metal oxide semiconductor sensor designed for gas leak detection, not precision smoke analysis. It responds to a broad range of gases including methane, propane, butane, hydrogen, and alcohol vapor, in addition to smoke. High humidity can affect readings. The sensor degrades over time and should be replaced annually for any safety-adjacent application. It has no certification for life safety use.

Network dependency for cloud models. If your agent uses a cloud LLM for reasoning, an internet outage disables the intelligence layer. For safety applications, always configure a local fallback. A simple Python script that monitors the MQ-2 independently and triggers the buzzer if readings exceed a high threshold (well above cooking levels) provides basic protection when the agent is offline. This fallback should run as a separate systemd service that starts on boot regardless of OpenClaw's status.

Sensor placement. Install the MQ-2 at ceiling height or high on a wall, since smoke rises. Keep it away from kitchens, bathrooms, and garages where normal activities produce combustible gases. For kitchen monitoring specifically, consider the MQ-135 (better for air quality gases) or a photoelectric smoke sensor module instead of the MQ-2. If you do monitor the kitchen, set the agent's cooking-hours tolerance accordingly.

Power reliability. The Pi needs continuous power to monitor. A UPS HAT (battery backup board, $20-30) keeps the system running during brief power outages and provides clean shutdown during extended outages. Without battery backup, a power outage means no monitoring, which is the opposite of what you want during conditions that might cause electrical fires.

Multi-room deployment. For whole-house coverage, run sensor nodes in each room using Pi Zero 2 W boards or ESP32 microcontrollers that publish readings over MQTT. A central Pi 5 running OpenClaw subscribes to all topics and reasons about the house as a whole. Cross-room correlation is valuable: smoke detected in the living room plus rising temperature in the adjacent hallway paints a different picture than a single-room reading. The central agent can coordinate which alarms to trigger and in what order.

Regular testing. Test the sensor monthly by holding a lit match near it (after extinguishing it) and confirming the agent detects and responds to the smoke. Check that notification webhooks still deliver. Replace the MQ-2 sensor element annually. Treat this with the same discipline as testing a conventional smoke alarm.

Frequently Asked Questions

Can Raspberry Pi detect smoke?

Yes. A Raspberry Pi can detect smoke using an MQ-2 gas sensor module connected through an analog-to-digital converter like the MCP3008. The MQ-2 detects smoke particles and combustible gases by measuring changes in conductivity of its tin dioxide sensing element. The sensor costs under $5 and connects to the Pi's SPI bus through the ADC. Combined with an OpenClaw agent, the Pi can go beyond raw threshold detection to contextual analysis that reduces false alarms.

How does AI reduce false alarms in smoke detection?

An AI agent like OpenClaw evaluates smoke sensor readings against context rather than comparing to a fixed threshold. It considers time of day (cooking hours vs. overnight), rate of change (gradual drift vs. sudden spike), duration (brief puff vs. sustained rise), correlation with temperature data, and historical baselines for the space. A reading that would trigger a traditional alarm during dinner prep gets logged as expected cooking activity, while the same reading at 3 AM triggers an immediate alert.

What gas sensor works best with Raspberry Pi for fire detection?

The MQ-2 is the most widely used gas sensor for Raspberry Pi fire detection projects. It detects smoke, methane, butane, LPG, and hydrogen for $2-5 per module. For improved accuracy, pair it with a BME280 temperature sensor (rapid temperature rise confirms fire) and an IR flame sensor module (detects infrared radiation from open flames). The combination of three cheap sensors gives better detection confidence than any single expensive sensor.

Does the MQ-2 sensor need calibration?

The MQ-2 requires a 24-48 hour burn-in period on first use and a 2-3 minute warm-up on each power cycle before readings stabilize. For threshold-based projects, you calibrate by adjusting the onboard potentiometer or your software threshold based on clean-air baseline readings. For an OpenClaw agent build, exact calibration is less critical because the agent reasons about relative changes and patterns rather than absolute values, but establishing a clean-air baseline helps the agent set appropriate reference points.

Is a Raspberry Pi smoke detector safe to rely on?

No, not as your primary smoke detector. A Raspberry Pi with an MQ-2 sensor is not UL-listed, has no battery backup by default, and uses a sensor designed for gas leak detection rather than life safety. Always install code-compliant smoke alarms that meet UL 217 or EN 14604 standards. Use the Pi and OpenClaw agent as a supplementary system that adds contextual intelligence, remote notifications, and historical logging on top of proper safety hardware.

Does OpenClaw run on Raspberry Pi for sensor monitoring?

OpenClaw runs on Raspberry Pi 5 (8GB recommended) or Pi 4 with at least 4GB RAM. It installs through a single command and supports cloud LLM providers (Claude, GPT-4, Gemini) and local models through Ollama. For sensor monitoring, OpenClaw calls Python scripts that read hardware sensors and returns structured data. The agent then reasons about the readings, considering patterns and context rather than just comparing numbers to thresholds.

Related Resources

Fastio features

Store Smoke Detection Logs Where Any Agent Can Search Them

Upload sensor readings and agent decision logs to a Fast.io workspace. Intelligence Mode indexes everything for natural language queries across months of detection history. 50GB free, no credit card required. Built for openclaw raspberry smoke fire alarm detection agent workflows.