Siddhant Kumar
Project 043 · Environment

Flood Level Sensor.

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.

Intermediate 10–16 hours 35 min read UltrasonicAlertsSafety
Jump to source Bill of materials
Flood Level Sensor — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Intermediate
Build time
10–16 hours
Indicative cost
₹4,500 – ₹6,500
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Environment
Last updated
28 July 2026
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.

An HC-SR04 ultrasonic distance sensor with its two transducers
A non-contact ultrasonic/radar sensor reads the water surface from a bridge without anything in the flood's path. Photograph sourced from Wikimedia Commons — HC-SR04.jpg. Reused under the licence stated on that page; please check it before republishing.

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

SettingHow it is used
Community flash-flood warningProtecting downstream villages and low crossings with staged alerts and real lead time as a flood front travels down the river.
Urban stormwater and culvertsWatching drains, culverts and urban streams that flood streets and underpasses in intense rain.
Low-water crossings and causewaysAutomatically warning (and gating) at fords and causeways that become deadly when the water rises.
Reservoir and canal monitoringTracking 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

AttributeValue
Difficulty levelIntermediate
Estimated completion time10–16 hours
Indicative build cost₹4,500 – ₹6,500
Primary disciplineEnvironment
Reference platformESP32 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.

ComponentKey specificationQtyApprox. 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 DAC1₹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° beam1₹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 output1₹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 ID1₹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–SF121₹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 frame1₹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 protection1₹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 discharge1₹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 / bracketAims the sensor straight down at the water, above max flood, rigid against wind1₹350
Cellular modem (optional)
LoRa preferred where a gateway exists
For sites without LoRa gateway coverage1₹900
Local siren/beacon (optional)On-site audible/visual warning at a crossing1₹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

PartSpecificationSupplyInterfaceReference
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 DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
JSN-SR04T waterproof ultrasonic sensor25–450 cm, ±1 cm, IP67 sealed transducer, 45° beam5 VTrigger/Echo or UARTDatasheet
Rain / water-level board (FC-37)Interdigitated PCB electrode, analogue + digital comparator output3.3–5 VAnalogue + digitalDatasheet
DS18B20 waterproof temperature probe−55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID3.0–5.5 V1-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–SF123.3 VSPIDatasheet
20 W 12 V polycrystalline solar panelVmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 × 290 mm, aluminium frame12 V nominalMC4 / screw terminalsDatasheet
TP4056 Li-ion charger + DW01 protection1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection4.5–5.5 V inmicro-USB / padsDatasheet
18650 Li-ion cell 3400 mAh + holder3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge3.0–4.2 VHolder / spot-welded tabsDatasheet

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.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
JSN-SR04T waterproof ultrasonic sensor5 V30The 25 cm blind zone matters — mount it above the maximum expected water level.
Rain / water-level board (FC-37)3.3–5 V15Drive the electrode with AC or duty-cycle its power to slow electrolytic corrosion.
DS18B20 waterproof temperature probe3.0–5.5 V1.5Dozens can share one GPIO — you address them by ROM code.
SX1278 LoRa 433 MHz module (Ra-02)3.3 V120Never power the radio without an antenna — the PA will destroy itself.
20 W 12 V polycrystalline solar panel12 V nominal1140Rated watts assume 1000 W/m² — plan for 60–70 % of nameplate in real installs.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy 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.json under 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 dialout group: sudo usermod -aG dialout $USER and 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

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager → "PubSubClient" by Nick O'Leary
OneWire + DallasTemperature 2.3.x / 3.9.xBus enumeration and conversion commands for DS18B20 probes.Library Manager → "DallasTemperature" (pulls OneWire)
Adafruit Unified Sensor 1.1.xCommon sensor event abstraction; a dependency of most Adafruit drivers.Library Manager → "Adafruit Unified Sensor"
LoRa (sandeepmistry) 0.8.0SX127x radio configuration, packet TX/RX and callbacks.Library Manager → "LoRa" by Sandeep Mistry
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core
NTPClient / configTime bundledWall-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.

Flood Level Sensor — system block diagramFunctional block diagram of the Flood Level Sensor system. MeasureLevel (non-contact)ultrasonic/radarRain (opt)attributionAir tempsound-speedAssessESP32level + rateStaged alertswatch/warn/dangerLinkLoRa/cellular+ local logWarnDownstreamlead-time alertSiren (opt)on-siterightrightnone
Flood Level Sensor — system block diagram

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.

Flood Level Sensor — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBLevel sensorGPIO 26/25Distance down towaterRain sensorGPIO 34 / 27Local rainfall(optional)DS18B20GPIO 4Air temp(sound-speedcorrection)LoRa/cellularSPI / UARTTelemetry uplinkSiren/beaconGPIO 13Local warning(optional)TP4056VIN / 3V3 regSolar-charged supplySolar panelTP4056 IN6 V panel → charger
Flood Level Sensor — wiring schematic
PeripheralPeripheral pinController pinSignal
Level sensorTRIG/ECHOGPIO 26/25Distance down to water
Rain sensorAOUT/DOUTGPIO 34 / 27Local rainfall (optional)
DS18B20DQGPIO 4Air temp (sound-speed correction)
LoRa/cellularbusSPI / UARTTelemetry uplink
Siren/beaconINGPIO 13Local warning (optional)
TP4056OUTVIN / 3V3 regSolar-charged supply
Solar panel+/–TP4056 IN6 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.
A LoRa radio transceiver module
A LoRa (or cellular) radio carries level, rate and stage from the riverbank to the warning system. Photograph sourced from Wikimedia Commons — LoRa module.jpg. Reused under the licence stated on that page; please check it before republishing.

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.

Flood Level Sensor — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · JSN-SR04T waterproof ultrasonic sensor ·DS18B20 waterproof temperature probeDriver layerwifi · pubsub · onewire · unifiedApplication logicsampling loop · filtering · thresholds · state machineTransport layerLoRa/cellular → gateway → flood warning system · TLS · retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Flood Level Sensor — architecture stack

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

plainLevel 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

plainRate 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)

plainStaged 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.

Flood Level Sensor — firmware flowchartControl flow through the main program loop. Wake on scheduleMeasure distance; filterechoesConvert to level; compute rateof riseLevel or rate over a stagethreshold?Escalate stage; alert + local sirenLog trendEscalate stage; alert + localsirenLog trendTransmit + local logSleep (shorter if rising)
Flood Level Sensor — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

  1. 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.

  2. 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.

  3. 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.

  1. 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.
  2. 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.

  3. 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.

cppflood-level-sensor.ino
/* ═══════════════════════════════════════════════════════════════
   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()
RTC_DATA_ATTR float prevLevelThe previous level, timestamp and smoothed rate persist across deep sleep, so the rate of rise is computed correctly between wakes rather than lost each cycle.
int stageOf(float level, float rate)Maps both level and rate to a stage and takes the worse of the two, so a fast rise can raise "danger" while the water is still only moderately high — the flash-flood case.
if (newStage < stage && level >Hysteresis prevents the alert stage from flickering downward on wave noise; it only de-escalates once the level has clearly dropped below the stage boundary.
digitalWrite(PIN_SIREN, stage >= 3On "danger" the local siren sounds directly from the node, independent of the network — the on-site warning cannot depend on a link a flood may have knocked out.
uint32_t sleep_s = (rateS > R1 || stage >= 1)The node samples every fifteen minutes when calm but drops to two-minute intervals the moment the water is rising or elevated, tracking a developing flood at high resolution.

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.

  1. 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.

  2. Echo filtering

    Confirm the median filter rejects wave/spray outliers by watching raw vs filtered distance during choppy conditions.

  3. 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

Flood Level Sensor — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsRiver nodeESP32 + levelUpstream nodesriver chainLoRa / cellularArea gatewayor direct cellularMQTT 1883Warning systemstages + lead timeAuthoritiesstaged alertsPublic/SMSevacuation
Flood Level Sensor — network topology

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 / endpointDirectionPayload
flood/node/1/levelnode → brokerlevel, rate of rise, stage
flood/node/1/stagenode → brokerstage change (watch/warning/danger)
flood/node/1/statusnode → brokerbattery, 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.

TestWhat you should see
Raise a target toward the sensorMeasured level increases correctly; median rejects a single spurious ping
Simulate a fast rise between readsRate of rise climbs; stage can reach danger before the level threshold
Hold a high but steady levelStage set by level; no flicker thanks to hysteresis
Drop the link during a rising eventReadings 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 cycleBattery 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.

jsonflood-packet.json
{
  "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.

A city skyline at night
Chained along a river, the nodes warn downstream communities with real lead time as a flood travels. Photograph sourced from Wikimedia Commons — Smart city.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Level jumps around wildly

Likely cause. Wave/spray/debris echoes, or a swaying mount

Fix. Increase pings and keep the median filter; make the mount rigid; aim straight down

Level slowly wrong by a fixed amount

Likely cause. Sensor height/datum miscalibrated

Fix. Recalibrate H_SENSOR_CM against a staff gauge or known water mark

Distance drifts with day/night temperature

Likely cause. No sound-speed correction (ultrasonic)

Fix. Apply the air-temperature correction; consider a radar sensor for large drops

Alerts flicker between stages

Likely cause. No/insufficient hysteresis

Fix. Increase the de-escalation margins so noise cannot bounce the stage

No data during the flood

Likely cause. Network failed and no local logging

Fix. Ensure local logging and the on-site siren work independently of the link

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device — check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

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 a millis() 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_t where 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

Why is rate of rise more important than the level?

The level tells you the danger now; the rate tells you the danger soon — and gives you time. A fast climb can warrant a danger alert while the water is still moderate, which is how you get people out before a flash flood peaks.

Why non-contact measurement?

Anything in the water — floats, bed sensors — is destroyed by the debris and current of a flood, exactly when you need the reading. Looking down at the surface from above keeps the sensor out of harm.

How does a chain of nodes give lead time?

Water takes real time to travel downstream. An upstream node reaching "danger" is an early warning for everyone below, with a lead time you can estimate from the travel time between stations.

What if the network fails in the storm?

It often does — which is why the node logs locally and sounds any on-site siren independent of the link, and forwards its backlog once connectivity returns. The warning never depends solely on the network.

Can it stop a flood?

No — it warns of one. Its job is to convert a fast rise into staged alerts with real lead time so people and assets can be moved, turning a disaster into an evacuation.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. Flood warning systems — overviewReference
  2. Flash floods and rate of rise — hydrologyReference
  3. Ultrasonic and radar water-level sensingUSGS
  4. Speed of sound and temperatureReference
  5. Community-based flood early warning (guidance)UNDRR