How to Build a River Flood Warning System with OpenClaw on Raspberry Pi
A Raspberry Pi with an ultrasonic distance sensor can measure river water levels continuously. But raw distance readings alone do not tell you whether a flood is coming. This guide covers wiring a waterproof JSN-SR04T sensor to a Pi, installing OpenClaw as the reasoning layer, and building an agent that correlates water level trends with weather forecast data to issue early warnings before water reaches dangerous levels.
Why Threshold Alerts Fail for Flood Monitoring
Flash flooding is the deadliest type of flooding in the United States. NOAA classifies it as the number one weather-related killer, and a 2021 analysis published in the journal Water found that flash floods account for roughly 42% of all recorded flood fatalities where flood type was documented. A monitoring station that catches rising water 30 minutes earlier can be the difference between an orderly evacuation and a disaster.
Most Raspberry Pi water level tutorials follow the same approach: mount a sensor above the water, poll the distance, and trigger an alert when the level crosses a threshold. That catches the flood that is already happening. It does not catch the flood that is about to happen.
A static threshold also generates false alarms. Tidal rivers rise and fall twice daily. Snowmelt runoff raises creek levels every spring afternoon without posing flood risk. Heavy rain upstream can push a river up 30 cm for a few hours before draining safely. A threshold script treats all of these the same way: alarm. After a few false alerts, you stop checking notifications. Then a real flood arrives and the warning goes unread.
OpenClaw changes this by adding a reasoning layer between the sensor and the alert. Running on the same Raspberry Pi, an OpenClaw agent evaluates water level trends over time, correlates them with precipitation forecasts and upstream conditions, and decides whether the current rise is routine or dangerous. Instead of "water is at 1.5 meters, send alert," the agent reasons: "water rose 20 cm in the past hour, the forecast shows 40 mm of rain in the next 6 hours, and the historical data shows this creek floods at 2.1 meters. Current level is 1.5 meters with an upward trend. Issue a warning now."
That contextual reasoning is what separates a flood warning system from a water level alarm.
Bill of Materials and Site Cost
A Pi-based flood monitoring station costs under $150 for the mains-powered version, including the weatherproof enclosure. Adding solar power and a cellular modem for remote deployment pushes the total closer to $200-230.
Waterproof ultrasonic sensor, JSN-SR04T ($5-12): This is the outdoor-rated version of the popular HC-SR04 ultrasonic sensor. The key difference is that the JSN-SR04T separates the waterproof transducer probe from the control board with a flexible cable. The probe mounts outdoors pointing down at the water surface, while the control board stays dry inside the enclosure with the Pi. The v3.0 model measures distances from 20 cm to 600 cm with accuracy around 1 cm, which is more than sufficient for tracking river levels.
Do not use the HC-SR04 for outdoor flood monitoring. Its transducers are exposed on an open PCB with no water resistance. One rainstorm will destroy it.
Wiring the JSN-SR04T to GPIO: The sensor needs four connections: VCC to the Pi's 5V pin (pin 2), GND to a ground pin (pin 6), TRIG to GPIO 23 (pin 16), and ECHO to GPIO 24 (pin 18). Unlike the HC-SR04, the JSN-SR04T's ECHO pin outputs a 3.3V-compatible signal on most v2.0 and v3.0 boards, so you do not need a voltage divider. Verify this with a multimeter on your specific board before connecting. If the ECHO pin outputs 5V, add a voltage divider with a 1K and 2K resistor to drop it to 3.3V before it reaches the GPIO.
Mounting the sensor probe: The transducer probe mounts at a fixed, known height above the water surface, pointing straight down. A bridge railing, culvert wall, or a dedicated post driven into the bank all work. Record the exact mounting height (distance from the probe face to the channel bottom or to a reference datum). Water level equals mounting height minus the measured distance. Secure the cable run from the probe back to the enclosure with UV-resistant cable ties or conduit. Leave a drip loop before the cable enters the enclosure so rainwater runs off rather than following the cable inside.
Temperature sensor, DS18B20 ($3-5): Sound travels faster in warm air than cold air. An uncorrected ultrasonic reading drifts by roughly 0.6 cm per degree Celsius over a 2-meter measurement range. A DS18B20 one-wire temperature sensor mounted near the ultrasonic probe lets your reading script compensate for air temperature. Wire it to the Pi's 3.3V, GND, and GPIO 4 (the default one-wire bus pin) with a 4.7K pull-up resistor between the data line and 3.3V.
Weatherproof enclosure ($15-25): An IP67-rated junction box or an outdoor electrical enclosure protects the Pi and control board from rain, humidity, and temperature swings. Mount it above the expected high-water mark with enough margin for extreme events. Drill cable gland holes for the sensor cable, power cable, and antenna cables. Seal each penetration with a compression cable gland, not silicone caulk, since glands maintain their seal over years of thermal cycling. Add silica gel desiccant packs inside to absorb residual moisture.
Power options: For sites with mains power, a standard 5V/3A USB-C power supply runs the Pi continuously. For remote sites without power, a 20W solar panel, 12V/7Ah lead-acid or LiFePO4 battery, and a charge controller provide reliable off-grid power. The Pi 4 draws about 3-4W at idle, so a 20W panel with 4-5 hours of average daily sun provides comfortable margin. A low-voltage cutoff module protects the battery from deep discharge.
Installing OpenClaw and Configuring Sensor Scripts
OpenClaw runs on Raspberry Pi 4 or 5 with at least 2 GB of RAM (4 GB recommended). The Pi acts as a gateway, not an inference engine. LLM reasoning happens via API calls to cloud providers like Anthropic (Claude), OpenAI, or Google (Gemini), so the Pi's own processing power is not the bottleneck.
Installation: Flash 64-bit Raspberry Pi OS Lite using the official Raspberry Pi Imager. SSH into the Pi, install Node.js 24 via NodeSource, add a 2 GB swap file if your Pi has 2 GB of RAM or less, then run the OpenClaw installer. The onboarding command installs the daemon as a systemd user service so it starts automatically on boot. Enable user lingering with sudo loginctl enable-linger <username> so the service runs even when no user is logged in. The full installation process takes about 30 minutes.
Storage: Use a USB SSD instead of an SD card. A flood monitor that logs readings every few minutes generates thousands of small writes daily. SD cards degrade under sustained write loads. A 16 GB USB SSD costs $10-15 and lasts far longer. Set gpu_mem=16 in the Pi's config to free RAM, since this is a headless deployment with no display.
Sensor reading script: OpenClaw agents interact with hardware through Python scripts that the agent calls as system commands. The water level reading script triggers the ultrasonic sensor, measures the echo return time, calculates the distance, and prints the result to stdout. Use the hcsr04sensor Python library from PyPI, which works with both the HC-SR04 and JSN-SR04T. The script triggers GPIO 23 (TRIG), listens on GPIO 24 (ECHO), measures the pulse width, and converts it to centimeters using the speed of sound. If you installed a DS18B20 temperature sensor, the script reads the current air temperature from the one-wire bus and adjusts the speed-of-sound constant accordingly.
Take multiple readings per measurement cycle (5 readings with 60 ms spacing is typical) and discard outliers before averaging. Ultrasonic sensors occasionally return garbage readings from wave reflections, wind gusts on the water surface, or debris passing through the beam. A median-of-five approach filters these out.
Reading frequency: For routine monitoring, one reading every 5 minutes is sufficient. During rising water conditions, the agent can increase the polling frequency to every 30-60 seconds. OpenClaw's built-in cron scheduling handles the baseline polling interval. The agent can override this dynamically based on conditions.
Notification channels: Configure Telegram as the primary alert channel. It works reliably on headless Pi deployments and delivers notifications to your phone with no additional infrastructure. The OpenClaw setup guide covers Telegram bot configuration. For critical flood warnings, consider adding a secondary channel (SMS via a GSM module or email) so you receive alerts even if one channel is down.
Store and Search Your Flood Monitoring Data from Every Station
Fast.io gives your OpenClaw agents 50 GB of free cloud storage with built-in search and AI indexing. Upload water level logs from every station, query historical trends through AI chat, and share monitoring dashboards with emergency coordinators. No credit card required.
Building the Flood Reasoning Agent
Raw water level readings become useful only when the agent can interpret trends and correlate them with external data. This is where OpenClaw's reasoning layer turns distance measurements into flood predictions.
Data inputs the agent evaluates:
- Current water level and distance reading from the ultrasonic sensor
- Rate of change: how fast is the water rising or falling, measured over 15-minute and 1-hour windows?
- Weather forecast: precipitation amounts and timing from a weather API for the monitoring location and upstream watershed
- Active weather alerts: flood watches, flash flood warnings, and severe thunderstorm warnings issued by national weather services
- Historical baseline: what is the normal water level range for this location at this time of year?
- Seasonal context: is this spring snowmelt season, monsoon season, or a dry period?
Weather API integration: OpenWeatherMap provides a free tier with current conditions, 5-day/3-hour forecasts, and government-issued weather alerts. The agent queries the API once per hour during normal conditions and every 15 minutes when water levels are elevated. A Python script handles the API call and returns structured JSON with precipitation forecast totals and any active flood-related alerts. NOAA's Weather API (api.weather.gov) is another free option for US locations, providing direct access to National Weather Service flood watches and warnings without an API key.
Reasoning scenarios:
The creek level rises 15 cm over 2 hours. The agent checks the weather forecast: clear skies, no rain expected for 48 hours. It checks the calendar: early April, daytime temperatures above freezing. The agent classifies this as snowmelt runoff, logs the elevated reading, and continues monitoring at the normal interval. No alert sent.
The river level rises 10 cm in 30 minutes. The agent checks the forecast: 35 mm of rain expected in the next 6 hours, with a severe thunderstorm warning active for the upstream watershed. Historical data shows this river floods its banks at 2.1 meters. Current level is 1.4 meters and rising. The agent calculates a projected level based on the rate of rise and incoming precipitation. It sends a warning: "River level at 1.4 m and rising 20 cm/hour. 35 mm rain forecast in next 6 hours. Flood stage is 2.1 m. Estimated time to flood stage: 3-4 hours at current rate. Recommend preparation now." The agent increases polling to every 60 seconds.
The water level has been stable at 0.8 meters for a week. A sudden 25 cm spike occurs in under 10 minutes with no rain at the monitoring site. The agent checks upstream weather data: heavy rain 20 km upstream two hours ago. This pattern matches a flash flood surge traveling downstream. The agent sends an immediate high-priority alert: "Flash flood warning. Water level spiked 25 cm in 10 minutes. No local rain. Upstream rainfall detected. Evacuate low-lying areas."
Escalation tiers:
- Tier 1 (routine): Water level within seasonal norms, rate of change under 5 cm/hour. Log readings at 5-minute intervals. No notification.
- Tier 2 (elevated): Water level rising faster than 5 cm/hour, or above the 75th percentile for the current season. Increase polling to every 2 minutes. Send an advisory notification.
- Tier 3 (warning): Water level rising faster than 15 cm/hour, or within 50 cm of known flood stage. Poll every 60 seconds. Send urgent alerts to all channels. Include projected time to flood stage.
- Tier 4 (critical): Water level at or above flood stage, or rate of rise exceeds 30 cm/hour regardless of current level. Continuous polling. Trigger any connected sirens or relays. Send emergency alerts with evacuation recommendation.
These thresholds are starting points. Every river, creek, and drainage channel has different characteristics. A steep mountain stream rises and falls in hours. A wide lowland river rises slowly over days. Calibrate the tiers to your specific waterway by reviewing a few weeks of baseline data before relying on the alerts.
Logging Sensor Data and Long-Term Analysis
Flood monitoring generates a continuous stream of data that becomes more valuable over time. Last year's water level records help the agent predict this year's flood risk. Decision logs show whether the agent's reasoning was sound or needs tuning.
Structured logging: Every reading and every decision the agent makes should be logged with full context. Use JSON lines format: one JSON object per line, each timestamped, with fields for water_level_cm, distance_cm, rate_of_change_cm_per_hour, air_temp_c, forecast_precip_mm, active_alerts, agent_decision, and reasoning_summary. This format is easy to parse, append-only, and works with standard log analysis tools.
Local storage: The Pi's USB SSD stores the raw log files. At one reading every 5 minutes, a year of data is roughly 100,000 readings. Even with full context fields, that fits comfortably in under 500 MB. Keep local logs as the primary data store for the agent's immediate reasoning.
Cloud backup on Fast.io: For long-term retention and multi-site oversight, upload daily log summaries to a Fast.io workspace. Fast.io provides 50 GB of free storage with no credit card required, and its MCP server lets agents upload files directly through API calls. This serves two purposes: if the Pi's storage fails or the monitoring station is damaged in a flood (which is the exact scenario you are monitoring for), your historical data survives in the cloud. And if you monitor multiple waterways across a region, all the data lands in one searchable workspace.
Fast.io's Intelligence Mode auto-indexes uploaded files, so you can ask questions about your sensor history through the workspace's AI chat: "What was the highest water level at the creek station last spring?" or "How many times did the river exceed 1.8 meters in the past year?" No separate database or analytics setup needed. The workspace handles indexing and retrieval.
Other storage options work too. S3, Google Drive, or a local NAS can hold log files. Fast.io is convenient for agent deployments because the workspace supports agent-to-human handoff: the agent builds the monitoring archive, and property owners or emergency coordinators review it through the same interface.
Building a historical baseline: The agent's reasoning improves with historical data. After a few months of continuous monitoring, the agent has a baseline for what normal water levels look like at different times of year, after different amounts of rain, and during different weather patterns. This baseline is what separates a system that alerts on every rainstorm from one that alerts only when conditions deviate from the expected pattern.
Upload weekly summary reports (min, max, mean water level; number of elevated readings; any alerts triggered) to the Fast.io workspace. Over a full year, these summaries create a seasonal profile that makes the agent's predictions increasingly accurate.
Deployment, Maintenance, and Scaling
An outdoor monitoring station faces environmental challenges that indoor Pi projects do not. Plan for them during installation, not after the first failure.
Site selection: Mount the sensor where it has a clear line of sight to the water surface with no overhanging vegetation, bridge debris, or structural elements in the ultrasonic beam path. The JSN-SR04T has a roughly 15-degree beam angle, so at 3 meters above the water, the beam covers an area about 80 cm in diameter. Turbulent whitewater can scatter ultrasonic pulses and produce erratic readings. Calm pool sections of a stream give more reliable measurements than rapids or spillways.
Weatherproofing checklist: Seal all cable entry points with IP68-rated compression glands. Apply a bead of outdoor-rated silicone around the enclosure lid gasket if it shows signs of age. Point the cable glands downward so water cannot pool around the seals. Add a small vent with a hydrophobic membrane (Gore-Vent or similar) to equalize air pressure inside the enclosure without admitting moisture. Without a vent, temperature swings cause the enclosure to "breathe" condensation in through any imperfect seal.
Connectivity for remote sites: If the monitoring site has no Wi-Fi or wired internet, a 4G/LTE USB modem or HAT provides cellular connectivity. For remote locations where cellular coverage is marginal, LoRa radio modules can transmit readings to a gateway Pi up to several kilometers away in line-of-sight conditions. The gateway Pi handles the internet connection and OpenClaw reasoning, while the remote unit handles only sensor reading and LoRa transmission.
Power management for solar deployments: The Pi 4 draws 3-4W at idle. A 20W solar panel with a 12V/7Ah battery provides roughly 2-3 days of autonomy during overcast weather. Reduce power draw by disabling HDMI output, USB ports you are not using, Bluetooth, and Wi-Fi (if using ethernet or cellular). The agent can implement a low-power schedule: reduce polling frequency to once every 15 minutes during overnight hours when flood risk from convective storms is lower, and resume 5-minute intervals at dawn.
Daily health checks: Configure the agent to send a daily "station OK" message at a consistent time. Include the current water level, battery voltage (if solar-powered), SSD health (SMART data), and uplink status. A missing health check is itself an alert worth investigating immediately. A monitoring station that fails silently during the one storm that matters defeats the purpose of the entire system.
Sensor validation: Ultrasonic sensors can degrade from spider webs across the transducer face, mud dauber wasp nests, mineral deposits from spray, or aging transducer elements. The agent can detect degraded sensor health by watching for increasing reading variance, more frequent outlier readings, or readings that drift slowly in one direction without corresponding weather changes. Flag degraded sensors for physical inspection.
Common issues:
- Erratic readings in wind: Wind-driven waves and spray cause the ultrasonic beam to scatter. Increase the number of readings per measurement cycle from 5 to 15 and use a trimmed mean (discard highest and lowest 20%) to filter noise.
- Readings stuck at maximum range: The transducer face may be obstructed, or the water level may have dropped below the sensor's minimum range (20 cm for JSN-SR04T v3.0). Check for physical obstructions and verify the water is within range.
- Temperature compensation drift: If readings shift consistently between morning and afternoon, verify that the DS18B20 temperature sensor is reading correctly and is mounted in ambient air, not in direct sunlight, which would overstate the temperature correction.
- Cellular modem drops connection: Configure the modem to reconnect automatically. The agent can monitor connection status and power-cycle the modem via a GPIO-controlled relay if the connection is down for more than 5 minutes.
Scaling across a watershed: For regional flood monitoring, deploy multiple stations along a waterway and upstream tributaries. Each station runs its own OpenClaw agent on a local Pi, uploading readings and alerts to a shared Fast.io workspace. The workspace gives emergency coordinators a single view of water levels across the entire monitored area. An upstream station that reports rapid rise gives a downstream station advance warning even before its own sensors detect a change. The free agent tier covers 5 workspaces with 50 GB of storage, enough for a multi-station watershed network with years of historical data.
Frequently Asked Questions
How do you monitor river water levels with Raspberry Pi?
Mount a waterproof ultrasonic sensor (JSN-SR04T) at a known height above the water surface, pointing downward. Wire it to the Pi's GPIO pins and use a Python script to trigger the sensor, measure the echo return time, and calculate the distance to the water. Water level equals the mounting height minus the measured distance. Take multiple readings per cycle and average them to filter noise from wind and waves.
Can Raspberry Pi run outdoor flood detection?
Yes, with proper weatherproofing. House the Pi and sensor control board in an IP67-rated enclosure mounted above the expected high-water line. Use a JSN-SR04T sensor with its waterproof transducer probe mounted externally. Power options include mains power, solar panels with battery backup, or PoE. Add a cellular modem or LoRa radio for connectivity at remote sites without Wi-Fi.
How do I build a DIY flood warning system?
Start with a Raspberry Pi 4 or 5, a JSN-SR04T waterproof ultrasonic sensor, and a weatherproof enclosure. Wire the sensor to the Pi's GPIO, install OpenClaw as the reasoning agent, and configure it to poll the sensor at regular intervals. Add a weather API integration so the agent can correlate rising water levels with precipitation forecasts. Set escalation tiers based on rate of rise and proximity to known flood stages. The total hardware cost runs under $150 for a mains-powered station.
What sensors measure water level for flood monitoring?
Ultrasonic distance sensors (JSN-SR04T) are the most practical choice for Raspberry Pi flood monitors. They measure the distance from a fixed point to the water surface without contacting the water. Alternatives include pressure transducers submerged in the water (more accurate but harder to maintain), radar level sensors (expensive but unaffected by temperature), and capacitive probes (good for shallow channels). For most DIY installations, the JSN-SR04T offers the best balance of cost, accuracy, and durability.
How does OpenClaw predict floods instead of just detecting them?
OpenClaw correlates multiple data streams rather than relying on a single water level threshold. The agent tracks the rate of water level change over time, queries weather APIs for precipitation forecasts and active flood alerts, and compares current conditions against historical baselines for the monitored waterway. By combining a rising water trend with incoming storm data, the agent can project when water will reach flood stage and issue warnings hours before it happens.
Can I monitor multiple flood stations from one location?
Yes. Each monitoring station runs its own Pi with sensors and an OpenClaw agent. All agents upload their readings and alerts to a shared cloud workspace. Fast.io provides free agent-tier storage (50 GB, no credit card) where you can review water level data across all stations from one interface. Upstream stations that report rapid rises give downstream stations advance warning through the shared data.
Related Resources
Store and Search Your Flood Monitoring Data from Every Station
Fast.io gives your OpenClaw agents 50 GB of free cloud storage with built-in search and AI indexing. Upload water level logs from every station, query historical trends through AI chat, and share monitoring dashboards with emergency coordinators. No credit card required.