Contents — 26 sections
Project Overview
Watches a river's level and — more importantly — its rate of rise from a bridge or bank, turning a fast climb into a staged warning while there is still time to move.
Floods kill and destroy not because water is inherently mysterious but because warnings arrive too late. A river can look benign at dusk and be over its banks by dawn, and the people most exposed — a downstream village, a low bridge, a riverside market — often have no idea the water upstream is already climbing fast. This sensor is a simple, robust early-warning node: mounted on a bridge or a bank, it measures the distance down to the water surface, converts that to a river level, and watches not just whether the level is high but how fast it is rising — because the rate of rise, more than the absolute level, is what tells you a flood is coming and how much time is left.
The measurement is deliberately non-contact. An ultrasonic (or radar) sensor looks down from the structure at the water and times an echo; nothing the sensor needs sits in the water to be swept away, fouled or buried in debris, which is what kills contact float gauges in exactly the flood conditions you care about. From the measured level the node computes the rate of rise and issues staged alerts — watch, warning, danger — each tied to a level and a rate, so a slow seasonal rise is treated differently from a flash flood climbing tens of centimetres an hour. Rain sensing can be added so the node knows whether a rise is being fed by local downpour.
Like the rest of this family, it is built to live where it is needed: solar-powered because riverbanks have no mains, reporting over LoRa or cellular because they have no Wi-Fi, sealed against weather, and logging locally so a dropped link during the storm — the worst possible moment — never loses the record or silences the warning. Multiple nodes along a river become a chain that watches a flood travel: an upstream node crossing "danger" is itself an early warning for everyone downstream, with real lead time measured from how long the water actually takes to arrive. It will not stop a flood, but it can give a village the twenty minutes that turn a disaster into an evacuation.
What this project does
- Measures river level non-contact from a bridge or bank (ultrasonic/radar)
- Computes the rate of rise, the key early-warning signal
- Issues staged alerts (watch / warning / danger) on level and rate
- Optionally senses rain to attribute a rise to local rainfall
- Runs on solar + battery and reports over LoRa or cellular
- Logs locally so a link outage during the storm loses nothing
- Chains along a river so upstream danger warns downstream with real lead time
Real-World Applications
| Setting | How it is used |
|---|---|
| Community flash-flood warning | Protecting downstream villages and low crossings with staged alerts and real lead time as a flood front travels down the river. |
| Urban stormwater and culverts | Watching drains, culverts and urban streams that flood streets and underpasses in intense rain. |
| Low-water crossings and causeways | Automatically warning (and gating) at fords and causeways that become deadly when the water rises. |
| Reservoir and canal monitoring | Tracking levels behind and below control structures for operations and downstream safety. |
Deployment contexts where a build of this kind earns its keep.
Features & Capabilities
- Rate-of-rise focus — flash-flood warning, not just a high-water mark
- Non-contact sensing that survives the debris and current of a flood
- Staged, level-and-rate alerts distinguishing seasonal rise from flash flood
- Local logging + LoRa/cellular for the storm when networks fail
- Solar, sealed, unattended riverbank operation
- Upstream-to-downstream lead time from a chain of nodes
- Optional rainfall attribution
Difficulty, Time & Required Skills
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 10–16 hours |
| Indicative build cost | ₹4,500 – ₹6,500 |
| Primary discipline | Environment |
| Reference platform | ESP32 DevKit V1 (ESP-WROOM-32) |
Skills you should have (or will pick up)
- Non-contact level measurement with an ultrasonic/radar sensor and echo filtering
- Converting distance-to-water into level with a datum
- Computing rate of rise and staged alert logic
- LoRa/cellular telemetry with local-logging fallback
- Solar power design for riverside nodes
Bill of Materials
Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.
| Component | Key specification | Qty | Approx. cost |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 1 | ₹450 |
| JSN-SR04T waterproof ultrasonic sensor The 25 cm blind zone matters — mount it above the maximum expected water level. | 25–450 cm, ±1 cm, IP67 sealed transducer, 45° beam | 1 | ₹450 |
| Rain / water-level board (FC-37) Drive the electrode with AC or duty-cycle its power to slow electrolytic corrosion. | Interdigitated PCB electrode, analogue + digital comparator output | 1 | ₹90 |
| DS18B20 waterproof temperature probe Dozens can share one GPIO — you address them by ROM code. | −55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID | 1 | ₹160 |
| SX1278 LoRa 433 MHz module (Ra-02) Never power the radio without an antenna — the PA will destroy itself. | −148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF12 | 1 | ₹480 |
| 20 W 12 V polycrystalline solar panel Rated watts assume 1000 W/m² — plan for 60–70 % of nameplate in real installs. | Vmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 × 290 mm, aluminium frame | 1 | ₹1,200 |
| TP4056 Li-ion charger + DW01 protection Buy the version *with* protection ICs — the bare charger will over-discharge your cell. | 1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection | 1 | ₹45 |
| 18650 Li-ion cell 3400 mAh + holder Never charge below 0 °C; always use a protected cell or a BMS. | 3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge | 1 | ₹450 |
| Radar/ultrasonic level sensor (long-range) Radar is better over big drops and in spray; ultrasonic suits low bridges | Waterproof, long-range (JSN-SR04T for short spans; radar for large clearance) | 1 | ₹1,200 |
| Rigid downward mount / bracket | Aims the sensor straight down at the water, above max flood, rigid against wind | 1 | ₹350 |
| Cellular modem (optional) LoRa preferred where a gateway exists | For sites without LoRa gateway coverage | 1 | ₹900 |
| Local siren/beacon (optional) | On-site audible/visual warning at a crossing | 1 | ₹500 |
Estimated total: ₹6,275, excluding tools, shipping and consumables.
Tools and consumables
- Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
- Digital multimeter — continuity, DC volts and current ranges
- Wire strippers, flush cutters and a small set of precision screwdrivers
- Heat-shrink tubing and a heat gun (or a lighter, carefully)
- A laptop with a USB port and the toolchain listed above
Hardware Specifications
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 3.3 V logic / 5 V USB | UART, SPI, I²C, I²S, CAN, PWM | Datasheet |
| JSN-SR04T waterproof ultrasonic sensor | 25–450 cm, ±1 cm, IP67 sealed transducer, 45° beam | 5 V | Trigger/Echo or UART | Datasheet |
| Rain / water-level board (FC-37) | Interdigitated PCB electrode, analogue + digital comparator output | 3.3–5 V | Analogue + digital | Datasheet |
| DS18B20 waterproof temperature probe | −55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID | 3.0–5.5 V | 1-Wire (multi-drop) | Datasheet |
| SX1278 LoRa 433 MHz module (Ra-02) | −148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF12 | 3.3 V | SPI | Datasheet |
| 20 W 12 V polycrystalline solar panel | Vmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 × 290 mm, aluminium frame | 12 V nominal | MC4 / screw terminals | Datasheet |
| TP4056 Li-ion charger + DW01 protection | 1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection | 4.5–5.5 V in | micro-USB / pads | Datasheet |
| 18650 Li-ion cell 3400 mAh + holder | 3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge | 3.0–4.2 V | Holder / spot-welded tabs | Datasheet |
Consolidated electrical and interface specifications for every active part in the build.
Power Budget & Supply Sizing
Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. |
| JSN-SR04T waterproof ultrasonic sensor | 5 V | 30 | The 25 cm blind zone matters — mount it above the maximum expected water level. |
| Rain / water-level board (FC-37) | 3.3–5 V | 15 | Drive the electrode with AC or duty-cycle its power to slow electrolytic corrosion. |
| DS18B20 waterproof temperature probe | 3.0–5.5 V | 1.5 | Dozens can share one GPIO — you address them by ROM code. |
| SX1278 LoRa 433 MHz module (Ra-02) | 3.3 V | 120 | Never power the radio without an antenna — the PA will destroy itself. |
| 20 W 12 V polycrystalline solar panel | 12 V nominal | 1140 | Rated watts assume 1000 W/m² — plan for 60–70 % of nameplate in real installs. |
| TP4056 Li-ion charger + DW01 protection | 4.5–5.5 V in | 1000 | Buy the version *with* protection ICs — the bare charger will over-discharge your cell. |
Summed typical draw is 2466.5 mA. With a 1.5× design margin the supply should deliver at least 3700 mA continuously at the stated rail voltage.
Software Requirements & Development Environment
Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.
- Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
- Add
https://espressif.github.io/arduino-esp32/package_esp32_index.jsonunder File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager. - Set the correct port under Tools → Port. On Linux add yourself to the
dialoutgroup:sudo usermod -aG dialout $USERand log out and back in. - Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
- Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.
Required libraries
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| PubSubClient 2.8 | Lightweight MQTT 3.1.1 client for constrained devices. | Library Manager → "PubSubClient" by Nick O'Leary |
| OneWire + DallasTemperature 2.3.x / 3.9.x | Bus enumeration and conversion commands for DS18B20 probes. | Library Manager → "DallasTemperature" (pulls OneWire) |
| Adafruit Unified Sensor 1.1.x | Common sensor event abstraction; a dependency of most Adafruit drivers. | Library Manager → "Adafruit Unified Sensor" |
| LoRa (sandeepmistry) 0.8.0 | SX127x radio configuration, packet TX/RX and callbacks. | Library Manager → "LoRa" by Sandeep Mistry |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager → "ArduinoJson" by Benoit Blanchon |
| Preferences (NVS) bundled | Wear-levelled key/value storage in ESP32 flash for settings. | Bundled with the ESP32 core |
| NTPClient / configTime bundled | Wall-clock time from an NTP server for timestamping. | Bundled (`configTime()` on ESP32) |
Block Diagram
The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.
Circuit Diagram & Wiring
Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| Level sensor | TRIG/ECHO | GPIO 26/25 | Distance down to water |
| Rain sensor | AOUT/DOUT | GPIO 34 / 27 | Local rainfall (optional) |
| DS18B20 | DQ | GPIO 4 | Air temp (sound-speed correction) |
| LoRa/cellular | bus | SPI / UART | Telemetry uplink |
| Siren/beacon | IN | GPIO 13 | Local warning (optional) |
| TP4056 | OUT | VIN / 3V3 reg | Solar-charged supply |
| Solar panel | +/– | TP4056 IN | 6 V panel → charger |
Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.
Wiring explanation
- Mount the level sensor rigidly, aimed straight down at the water, well above the highest expected flood so it is never submerged or hit by debris.
- For ultrasonic sensors, correct the echo time for the speed of sound using air temperature — sound speed varies enough with temperature to matter over a large drop.
- Keep the mount rigid against wind; a swaying sensor changes its aim and its measured distance.
- Route the antenna high and clear; place the electronics box on the structure above flood level.
- If fitting a siren at a crossing, drive it via a relay and ensure its power does not brown out the sensor node.
System Architecture
Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.
Working Principle
The core insight is that rate of rise carries the warning. A river's absolute level tells you the present danger, but its rate of change tells you the future one — and gives you time. Water rising ten centimetres an hour is a seasonal event you watch; water rising a metre an hour is a flash flood, and the difference in the two numbers is the difference between "keep an eye on it" and "move now". By computing the rate from successive level readings, the node converts a passive gauge into an early-warning device: it can be issuing a "danger" alert while the water is still well below the bank, because the trajectory says where it will be in twenty minutes.
Measurement is non-contact by necessity. The sensor looks down from the structure and times an echo off the water surface — ultrasonic for modest clearances, radar for large drops and heavy spray — so nothing the node depends on is in the water. This is not a convenience; it is survival. Contact gauges (floats, pressure transducers on the bed) are exactly what debris, sediment and violent current destroy during a flood, so a node that must survive the flood to warn of it cannot rely on anything submerged. The trade is that surface echoes are noisy — waves, foam, spray and passing debris all scatter the pulse — so the node takes many pings and uses a robust statistic (a median) to reject the spurious returns and track the true surface.
Turning distance into a meaningful level needs a datum: the sensor measures the gap down to the water, which is converted to a level above a reference (say, the riverbed or a defined zero) by subtracting from the known sensor height. Staged thresholds are then set against that level and against the rate — a "watch" at a modest level or gentle rise, a "warning" higher or faster, a "danger" at flood level or a rapid climb. Staging matters because a single alarm level cannot express both "high but stable" and "not yet high but climbing dangerously fast"; two axes (level and rate) mapped to graded stages let the node say the right thing in each case, and hysteresis stops it flickering between stages on noise.
The system's real power appears when nodes are chained along a river. Because water takes real time to travel downstream, an upstream node crossing "danger" is a concrete early warning for every community below it, with a lead time you can actually estimate from the travel time between stations. This is how meaningful flood warning works at low cost: not one perfect gauge, but a line of honest ones, each watching its reach and passing the news downstream faster than the water can flow. And because the network that carries those warnings is most likely to fail in the storm, every node logs locally and keeps sounding any local siren regardless of the link — the warning must not depend on the very connectivity a flood tends to knock out.
The maths behind it
Level from non-contact distance
Sensor at known height H_sensor above the datum measures
distance d down to the water:
water_level = H_sensor − d
Ultrasonic distance from echo time, temperature-corrected:
c = 331.3 + 0.606·T_air (m/s, speed of sound)
d = c · t_echo / 2
Rate of rise
From successive levels L at times t:
rate = (L_now − L_prev) / (t_now − t_prev) [m/h]
Smooth lightly to reject noise but stay responsive:
rate_s ← 0.7·rate_s + 0.3·rate
A high rate can trigger "danger" while the absolute level is
still moderate — the essence of flash-flood warning.
Staged alert logic (level × rate)
stage = max( stage_by_level(L), stage_by_rate(rate_s) )
WATCH : L > L1 OR rate > R1
WARNING : L > L2 OR rate > R2
DANGER : L > L3 OR rate > R3
Hysteresis: require L to fall a margin below a threshold to
de-escalate, so the stage does not flicker on wave noise.
Program Flowchart
The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.
Assembly Instructions
Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.
Mount above the worst-case flood
Fix the level sensor rigidly to the bridge or a bank mast, aimed straight down at the water and positioned above the highest flood ever recorded plus margin, so the sensor itself never goes under or into the debris path.
Measure and record the sensor height above your chosen datum precisely — every level reading depends on it.
Add temperature and rain sensing
Fit the air-temperature sensor for the sound-speed correction (ultrasonic), and optionally a rain sensor so the node can attribute a rise to local rainfall versus upstream flow.
Set up power, link and any siren
Angle the solar panel, mount the LoRa/cellular antenna high, and place the electronics box above flood level. If used, wire a local siren/beacon via a relay for on-site warning at a crossing.
Step-by-Step Implementation Guide
Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.
Measure level robustly
Take many pings, discard outliers with a median, convert the temperature-corrected distance to a level above datum, and reject any reading that implies an impossible jump.
cpplevel-measure.ino#define H_SENSOR_CM 600.0f // sensor height above datum (measured) float soundSpeedCmUs(float tAir) { return (331.3f + 0.606f * tAir) / 10000.0f; // cm per microsecond } // Median of many pings rejects wave/spray/debris echoes. float measureLevel(float tAir) { const int N = 9; float d[N]; for (int i = 0; i < N; i++) { digitalWrite(PIN_TRIG, LOW); delayMicroseconds(2); digitalWrite(PIN_TRIG, HIGH); delayMicroseconds(10); digitalWrite(PIN_TRIG, LOW); long us = pulseIn(PIN_ECHO, HIGH, 60000); d[i] = us ? us * soundSpeedCmUs(tAir) / 2.0f : NAN; delay(50); } // simple insertion sort, take median for (int i = 1; i < N; i++) { float k=d[i]; int j=i-1; while (j>=0 && (isnan(d[j])||d[j]>k)) { d[j+1]=d[j]; j--; } d[j+1]=k; } float dist = d[N/2]; if (isnan(dist)) return NAN; return H_SENSOR_CM - dist; // level above datum (cm) }float soundSpeedCmUs(float tAir)The speed of sound varies with air temperature, so the echo-to-distance conversion is temperature-corrected — important over a large drop where a few percent error is centimetres of level.const int N = 9; float d[N]Nine pings are taken because a water surface scatters the pulse; a single ping off a wave crest or a piece of debris would give a wildly wrong distance.take medianThe median of the nine readings rejects the spurious echoes entirely, tracking the true surface where a simple average would be dragged by outliers.return H_SENSOR_CM - distThe measured gap down to the water is subtracted from the known sensor height to give the level above the datum — the number the alert logic and downstream nodes actually use.Compute rate and stage the alert
Compute a lightly-smoothed rate of rise from successive levels, map both level and rate to a stage (watch/warning/danger) taking the worse of the two, and apply hysteresis so the stage does not flicker.
Log, transmit, warn
Write every reading locally first, transmit level, rate and stage, drive any on-site siren on danger, and forward the backlog when the link returns.
Complete Source Code
The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.
/* ═══════════════════════════════════════════════════════════════
Flood Level Sensor — ESP32, non-contact level, rate-of-rise, LoRa
Measures river level from a structure, computes rate of rise, issues
staged watch/warning/danger alerts, drives an optional local siren,
and reports over LoRa/cellular with local-logging fallback.
══════════════════════════════════════════════════════════════════ */
#include <WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LoRa.h>
#include <SPI.h>
#include <Preferences.h>
#include <math.h>
#define PIN_TRIG 26
#define PIN_ECHO 25
#define OW_PIN 4
#define PIN_SIREN 13
#define LORA_CS 5
#define LORA_RST 14
#define LORA_DIO0 2
#define H_SENSOR_CM 600.0f
// Stage thresholds (level cm above datum, rate cm/h).
#define L1 150.0f
#define L2 300.0f
#define L3 450.0f
#define R1 20.0f
#define R2 60.0f
#define R3 120.0f
OneWire ow(OW_PIN); DallasTemperature airT(&ow);
Preferences prefs;
RTC_DATA_ATTR float prevLevel = NAN; RTC_DATA_ATTR uint32_t prevMs = 0;
RTC_DATA_ATTR float rateS = 0; RTC_DATA_ATTR int stage = 0;
const char *STAGE[] = {"normal","watch","warning","danger"};
float soundSpeedCmUs(float t){ return (331.3f+0.606f*t)/10000.0f; }
float measureLevel(float t) {
const int N = 9; float d[N];
for (int i=0;i<N;i++){
digitalWrite(PIN_TRIG,LOW); delayMicroseconds(2);
digitalWrite(PIN_TRIG,HIGH); delayMicroseconds(10);
digitalWrite(PIN_TRIG,LOW);
long us=pulseIn(PIN_ECHO,HIGH,60000);
d[i]= us? us*soundSpeedCmUs(t)/2.0f : NAN; delay(50);
}
for(int i=1;i<N;i++){float k=d[i];int j=i-1;
while(j>=0&&(isnan(d[j])||d[j]>k)){d[j+1]=d[j];j--;} d[j+1]=k;}
float dist=d[N/2];
return isnan(dist)? NAN : H_SENSOR_CM - dist;
}
int stageOf(float level, float rate) {
int byL = level>L3?3 : level>L2?2 : level>L1?1 : 0;
int byR = rate >R3?3 : rate >R2?2 : rate >R1?1 : 0;
return max(byL, byR); // worse of level or rate
}
void transmit(float level, float rate, int st) {
LoRa.beginPacket();
LoRa.printf("{\"node\":1,\"level\":%.0f,\"rate\":%.0f,"
"\"stage\":\"%s\"}", level, rate, STAGE[st]);
LoRa.endPacket();
}
void logLocal(float level, float rate, int st) { /* append timestamped */ }
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG,OUTPUT); pinMode(PIN_ECHO,INPUT);
pinMode(PIN_SIREN,OUTPUT);
airT.begin();
airT.requestTemperatures();
float tAir = airT.getTempCByIndex(0);
float level = measureLevel(tAir);
uint32_t now = millis();
float rate = 0;
if (!isnan(prevLevel) && prevMs) {
float dtH = (now - prevMs) / 3600000.0f; // ms → hours
if (dtH > 0) rate = (level - prevLevel) / dtH; // cm/h
}
rateS = 0.7f*rateS + 0.3f*rate; // light smoothing
int newStage = stageOf(level, rateS);
// hysteresis: only de-escalate if clearly below the lower stage
if (newStage < stage && level > (stage==3?L3-50: stage==2?L2-50: L1-50))
newStage = stage;
stage = newStage;
digitalWrite(PIN_SIREN, stage >= 3 ? HIGH : LOW); // danger → local siren
logLocal(level, rateS, stage); // record first
SPI.begin();
LoRa.setPins(LORA_CS, LORA_RST, LORA_DIO0);
LoRa.begin(433E6);
LoRa.setSpreadingFactor(10);
transmit(level, rateS, stage);
prevLevel = level; prevMs = now;
// sample faster when rising or already elevated
uint32_t sleep_s = (rateS > R1 || stage >= 1) ? 120 : 900;
esp_sleep_enable_timer_wakeup((uint64_t)sleep_s * 1000000ULL);
esp_deep_sleep_start();
}
void loop() {} // deep sleep restarts setup()
Configuration & Calibration
Configuration steps
- Measure and set H_SENSOR_CM (sensor height above your datum) precisely.
- Set the level thresholds (L1–L3) from local flood history and the rate thresholds (R1–R3) from what a dangerous climb looks like on this river.
- Choose the calm and rising sampling intervals and the hysteresis margins.
- Select LoRa/cellular, configure local logging + backlog forwarding, and wire any siren.
Calibration procedure
An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.
Datum and height
Verify the sensor height by comparing a measured level against a physical staff gauge or a known water mark; correct H_SENSOR_CM until they agree.
Echo filtering
Confirm the median filter rejects wave/spray outliers by watching raw vs filtered distance during choppy conditions.
Rate thresholds
Set the rate stages against historical flood hydrographs for the river so "danger" corresponds to genuinely dangerous climbs, not ordinary rises.
Network Architecture & Connectivity
Communication protocol
Nodes report level, rate and stage on a cadence that shortens while rising; stage changes publish immediately. Local logging is authoritative and forwards backlog on reconnect, so the storm-time record survives network failure.
| Topic / endpoint | Direction | Payload |
|---|---|---|
flood/node/1/level | node → broker | level, rate of rise, stage |
flood/node/1/stage | node → broker | stage change (watch/warning/danger) |
flood/node/1/status | node → broker | battery, RSSI, sensor health |
Message contract between the device and the broker.
Cloud platform configuration
A warning system correlates nodes along a river: an upstream danger stage, combined with the known travel time to downstream communities, produces a concrete lead-time evacuation warning with a map of the advancing front.
Dashboard setup
A river map coloured by stage, per-node level/rate trends, and a chain view estimating when an upstream event reaches each downstream point.
Mobile app integration
Staged push/SMS to authorities and, at danger, to the public and to on-site sirens, timed by the estimated arrival of the flood front.
Security considerations
- Sign node reports so false flood alerts cannot be injected to cause panic or complacency.
- Keep the local siren and logging independent of the network so a lost link cannot silence the warning.
- Alert on a node going silent during rising conditions — a failed node in a storm is itself significant.
Testing Procedure & Expected Output
Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.
| Test | What you should see |
|---|---|
| Raise a target toward the sensor | Measured level increases correctly; median rejects a single spurious ping |
| Simulate a fast rise between reads | Rate of rise climbs; stage can reach danger before the level threshold |
| Hold a high but steady level | Stage set by level; no flicker thanks to hysteresis |
| Drop the link during a rising event | Readings logged locally; siren still sounds on danger; backlog forwards later |
| Cool/warm the air (ultrasonic) | Temperature correction keeps the distance accurate |
| Run a solar day/night cycle | Battery recovers; faster sampling during events is sustainable |
Bench-test checklist. If a row fails, stop and fix it before moving on.
Expected output
The dashboard shows each node's level, rate of rise and current stage on a map, with a river-chain view where an upstream danger stage flags downstream lead time.
{
"node": 1,
"level": 280,
"rate": 95,
"stage": "danger"
}
Here the level (280 cm) is only at the "warning" band, but the rate of rise (95 cm/h) pushes the stage to "danger" — the node warning of a flash flood before the water is physically high, which is exactly the point.
Troubleshooting: Common Errors & Fixes
Performance Optimisation
- Deep-sleep between reads when calm; shorten the interval automatically once the level is rising.
- Median-filter many pings rather than trusting one; the water surface is a noisy target.
- Persist previous level, time and rate in RTC memory so rate-of-rise is correct across sleeps.
- Keep packets tiny; the value is timeliness of the stage, not data volume.
- Replace every
delay()with amillis()comparison — blocking delays are the single most common cause of dropped readings. - Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
- Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
- Use
uint8_t/uint16_twhere the range allows; on an 8-bit AVR a 32-bit add costs four times as much. - Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
- Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
- For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.
Safety Precautions
- Mount above the worst-case flood so the node survives the peak it must warn about.
- Keep the on-site siren and local logging independent of the network — the warning must not depend on connectivity a flood can destroy.
- Install and service on riverbanks and bridges with proper safety; never work near fast water alone.
- This provides early warning to support official decisions; it does not replace an authoritative flood-warning authority.
- Lithium cells vent and burn when abused. Only use protected cells or a proper BMS, never charge below 0 °C, and never leave a charging pack unattended on a wooden desk.
- Never power an RF module without its antenna fitted — the reflected power destroys the output stage. Check your local licence-free band and duty-cycle limits before transmitting.
- Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
- Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
- Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.
Maintenance
- Re-verify the datum/height after any structural work or if the mount is disturbed.
- Clear the sensor's line of sight of nests, cobwebs and vegetation that cause false echoes.
- Test the siren and local logging before each wet season.
- Keep the solar panel clean and check the antenna and seals after storms.
- Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
- Clean the sensing element on a schedule. Optical and electrochemical sensors foul, and a fouled sensor reports plausible nonsense rather than failing outright.
- Log pack voltage. When resting voltage after a full charge drops below about 4.0 V, the cell is near end of life — replace it.
- Wash the panel every few weeks in dusty conditions; a visible dust film costs 15–25 % of the harvest.
- Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
- Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
- Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.
Future Improvements & Upgrades
A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.
- Fuse rainfall and upstream nodes into a simple routing model for better lead-time estimates.
- Add a camera snapshot on danger for visual confirmation to responders.
- Add automatic barrier/gate control at low-water crossings tied to the danger stage.
- Machine-learn river-specific stage thresholds from historical hydrographs.
- Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
- Add over-the-air firmware updates so you never have to physically reach a deployed node again.
- Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
- Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
- Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
- Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.
Frequently Asked Questions
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.