AI & Agents

How to Build a Lightning Storm Detector Agent with OpenClaw, Raspberry Pi, and the AS3935 Sensor

The AS3935 lightning sensor detects electromagnetic signatures from storms up to 40km away, but its raw interrupt output requires interpretation. By pairing it with OpenClaw on a Raspberry Pi, you can build an agent that tracks storm distance over time, predicts approach trajectories, and sends human-readable safety alerts through any messaging platform.

Fast.io Editorial Team 9 min read
An OpenClaw agent turns raw lightning data into actionable safety notifications.

What the AS3935 Lightning Sensor Actually Detects

The AS3935, manufactured by ScioSense (formerly ams), is a single-chip lightning sensor designed for weather station applications. It detects electromagnetic radiation in the 500kHz band, which is the characteristic frequency of lightning discharge events. The chip distinguishes between genuine lightning signatures and man-made RF noise using an embedded validation algorithm.

Detection range covers up to 40km from the sensor, with distance estimation reported in 15 discrete steps at 1-4km resolution. The sensor reports distance to the storm front rather than distance to individual strikes. This distinction matters for tracking: as a storm approaches, the reported distance decreases in steps, giving you a time series that reveals the storm's movement.

The sensor communicates over I2C or SPI. For Raspberry Pi projects, I2C requires only two data lines (SDA and SCL) plus an interrupt pin. When the AS3935 detects a qualifying event, it pulls the IRQ line high, triggering your code without continuous polling. SparkFun recommends SPI for new projects due to the AS3935's non-standard I2C implementation, though both interfaces work with the Pi's GPIO.

Lightning causes over $1 billion in US homeowners insurance claims annually. In 2024, payouts totaled $1.04 billion across roughly 56,000 claims, with individual claims averaging $18,641. A sensor that provides advance warning of approaching storms has practical value beyond hobbyist interest.

Neural network processing sensor signals

Why Raw Sensor Output Falls Short

Most Raspberry Pi lightning detector guides end at the same point: a Python script that prints "Lightning detected at 15km" whenever the interrupt fires. This is useful as a proof of concept, but it leaves several problems unsolved.

No trajectory analysis. A single distance reading tells you nothing about whether the storm is approaching or receding. You need to compare readings over time and apply basic reasoning about rate of change.

No contextual alerting. Getting a notification that says "Lightning at 22km" requires the recipient to decide what that means. Is 22km dangerous? Should they bring in outdoor equipment? The raw data demands interpretation every time.

No multi-channel delivery. A terminal printout is only visible if you're watching. Real safety alerts need to reach phones, group chats, or home automation systems regardless of whether anyone is monitoring the Pi.

No historical logging. Individual readings disappear after display. Without persistent storage, you cannot review storm patterns, validate sensor accuracy against weather service data, or share records with others.

This is where an AI agent adds genuine value. Rather than writing complex conditional logic for every scenario, you give the agent access to sensor data and let it reason about what the readings mean in context.

OpenClaw on Raspberry Pi: Edge Execution with Cloud Inference

OpenClaw is an open-source autonomous AI agent that runs on commodity hardware and connects to cloud LLMs for reasoning. The Raspberry Pi handles task orchestration, sensor data collection, and command execution while API calls to Claude, GPT-4, or Gemini handle the natural language understanding and decision-making.

The minimum hardware requirement is 1GB RAM, one CPU core, and 500MB free disk on a 64-bit OS. A Raspberry Pi 4 with 4GB RAM is the practical sweet spot, and the Pi 5 with 8GB provides comfortable headroom. The Pi never runs model inference locally. It acts as the execution layer: reading sensors, running scripts, sending messages, and persisting data.

OpenClaw's skill system is what makes hardware integration work. A skill is a folder containing a SKILL.md file with YAML frontmatter and markdown instructions. The frontmatter defines metadata (name, description, OS requirements), and the markdown body tells the agent how and when to use available tools. Skills can bundle scripts, configuration files, and MCP server definitions alongside the instruction document.

For a lightning detector, the skill instructs the agent to periodically read sensor data, maintain a rolling window of distance measurements, reason about storm trajectory, and send alerts when conditions warrant human attention. The agent's LLM backend handles the reasoning; the skill provides structure and context.

AI agent analyzing data patterns and generating summaries
Fastio features

Store and query your lightning detection logs from anywhere

Free 50GB workspace with built-in AI search. Upload storm data from your OpenClaw agent, ask questions about historical patterns, and share alert records with your team. No credit card required.

Hardware Wiring and Sensor Configuration

The AS3935 connects to the Raspberry Pi's GPIO header with five wires. The sensor operates at 3.3V, which matches the Pi's logic levels directly.

I2C wiring (four pins plus interrupt):

  • 3.3V power to the sensor's VCC pin (never use 5V, it will damage the module)
  • Ground to GND
  • Pi's SCL (GPIO 3) to the sensor's SCL pin
  • Pi's SDA (GPIO 2) to the sensor's SDA pin
  • Sensor's IRQ pin to a free GPIO (GPIO 17 is a common choice)

Before running any code, enable I2C through Raspberry Pi Configuration under the Interfaces tab. The DFRobot_AS3935 Python library provides a tested interface for reading distance, intensity, and event type from the sensor. Install it from GitHub and copy the library file into your project directory.

Antenna tuning is critical for accurate detection. The AS3935's internal antenna must resonate at 500kHz with no more than 3.5% deviation. Most breakout boards include a tuning capacitor, but if detection seems unreliable, use the calibration registers to adjust. The SparkFun and DFRobot breakout boards include documentation for their specific tuning procedures.

The sensor distinguishes three interrupt types: noise floor too high (reduce sensitivity or relocate the sensor), disturber detected (man-made RF rejected by the algorithm), and lightning detected (a validated strike with distance estimation). Your agent skill should handle all three, using noise and disturber events as diagnostic signals rather than discarding them.

Building the Lightning Detection Skill

The OpenClaw skill for lightning detection lives in the workspace at ~/.openclaw/workspace/skills/lightning-detector/. The SKILL.md file instructs the agent on how to interpret sensor data, when to alert, and what context to include in messages.

The skill's markdown body defines the agent's behavior in natural language. You describe what the sensor readings mean, what constitutes an approaching storm (consecutive readings with decreasing distance), what thresholds warrant alerts (storm within 10km and closing), and what information to include in notifications (current distance, rate of approach, estimated arrival time based on observed speed).

A companion Python script handles the hardware layer: initializing the I2C bus, configuring sensor registers, listening for interrupts, and writing readings to a local JSON log. The agent calls this script through OpenClaw's shell execution capability, reads the output, and applies reasoning.

Storm trajectory tracking works by maintaining a time-stamped sequence of distance readings. If the sensor reports 35km, then 28km three minutes later, then 22km after another four minutes, the agent can estimate the storm is approaching at roughly 8-10km per three minutes. That calculation is straightforward arithmetic, but the agent adds value by contextualizing it: "Storm approaching from the west at approximately 3km per minute. At current speed, the storm front will reach your location in roughly 7 minutes. Consider moving to shelter."

Alert routing uses OpenClaw's multi-channel messaging. The agent can push notifications through WhatsApp, Telegram, Slack, Discord, Signal, or any other configured channel. You specify alert recipients and severity thresholds in the skill configuration. A storm at 30km might log silently. A storm at 15km and closing triggers an informational message. A storm under 5km sends an urgent alert to all configured channels.

False positive handling improves over time. The agent logs every event including disturber rejections and noise floor warnings. If the sensor generates frequent disturber events, the agent can note the pattern and suggest relocating the antenna or adjusting the noise floor threshold, rather than flooding recipients with non-lightning alerts.

Persisting Storm Data and Sharing Alert History

A lightning detection agent generates data worth keeping: timestamp-distance pairs, alert messages sent, storm duration records, and sensor health metrics. Local storage on the Pi's SD card works for short-term buffering, but SD cards fail under sustained write loads, and the data stays trapped on one device.

For teams managing outdoor assets, construction sites, event venues, or agricultural operations, storm history needs to be accessible to multiple people and systems. S3 or Google Drive can store log files, but they lack the contextual layer that makes raw data useful after the fact.

Fast.io workspaces provide persistent storage with built-in intelligence. Your OpenClaw agent can upload storm logs and alert records to a Fast.io workspace using the MCP server, making them searchable and queryable. With Intelligence Mode enabled, you can ask questions like "How many storms approached within 10km last month?" or "Show me all alerts sent to the construction team channel" and get answers with citations pointing to specific log entries.

The ownership transfer pattern fits well here. An agent builds and maintains the lightning monitoring workspace, populating it with structured data over time. When a site manager or safety officer needs access, the agent transfers workspace ownership while retaining admin access for continued logging. The human gets a complete, organized record without having to configure anything.

Alternative approaches include writing to a local SQLite database (simple but not shareable), pushing to InfluxDB for time-series visualization (good for dashboards, but requires separate infrastructure), or syncing to a team Dropbox folder (accessible but not searchable by meaning). Fast.io's free agent tier provides 50GB storage, 5,000 AI credits per month, and MCP-native access with no credit card required.

Practical Considerations and Limitations

The AS3935 is not a precision instrument. Distance estimation works in coarse steps, and the sensor can miss strikes that occur without strong RF signatures. Indoor placement reduces sensitivity significantly due to building materials attenuating the 500kHz signal. For best results, mount the sensor outdoors or near a window, away from switching power supplies and other RF noise sources.

OpenClaw's cloud dependency means alert latency includes network round-trip time. For a safety-critical system, this delay (typically 1-3 seconds) is acceptable since storms move at speeds where seconds matter less than minutes. However, if your Pi loses internet connectivity during a storm, the agent cannot reason about new readings until the connection recovers. Consider adding a local fallback rule in the sensor script: if the internet is down and distance drops below 5km, trigger a local alarm (buzzer, LED, or local network broadcast) without waiting for LLM inference.

Power reliability matters for weather monitoring. A UPS or battery backup keeps the Pi running during the power fluctuations that often accompany thunderstorms. Without backup power, your detector goes offline exactly when it is most needed.

The agent's reasoning quality depends on prompt engineering in the SKILL.md. Vague instructions produce vague alerts. Specify exactly what data points to include, what units to use, and what actions to recommend at each distance threshold. Test with simulated data before relying on it for real safety decisions.

Frequently Asked Questions

How does the AS3935 lightning detector work?

The AS3935 detects electromagnetic radiation in the 500kHz band, which is characteristic of lightning discharge events. An internal algorithm validates incoming signals against known lightning patterns and rejects man-made disturbances. When a genuine strike is confirmed, the chip estimates distance to the storm front in 15 discrete steps from 1km to 40km, then signals via an interrupt pin.

Can a Raspberry Pi detect lightning?

A Raspberry Pi cannot detect lightning on its own, but paired with the AS3935 sensor connected via I2C or SPI, it can read lightning events, log distance measurements, and run software that interprets the data. The Pi handles orchestration and network communication while the AS3935 handles the actual RF detection.

How far can the AS3935 detect lightning?

The AS3935 detects lightning activity up to 40km from the sensor. Distance estimation is reported in 15 steps with 1-4km resolution. The sensor reports distance to the storm front rather than to individual lightning strikes, which makes it useful for tracking whether a storm is approaching or receding.

What does OpenClaw add to a lightning detector project?

OpenClaw provides the reasoning layer. Instead of writing complex conditional logic to interpret sensor data, you write natural language instructions in a skill file. The agent reads sensor output, tracks distance changes over time, calculates storm approach speed, and generates human-readable alerts delivered through WhatsApp, Telegram, Slack, or other messaging platforms.

Does OpenClaw run AI models locally on the Raspberry Pi?

No. OpenClaw uses cloud-hosted LLMs (Claude, GPT-4, Gemini) via API for reasoning. The Raspberry Pi handles task orchestration, sensor reading, script execution, and message delivery. This edge-execution-plus-cloud-inference architecture keeps hardware costs low while providing full LLM capabilities.

Related Resources

Fastio features

Store and query your lightning detection logs from anywhere

Free 50GB workspace with built-in AI search. Upload storm data from your OpenClaw agent, ask questions about historical patterns, and share alert records with your team. No credit card required.