11:08:19 AM NPT Arduino, Robotics & IoT tutorials for Nepal
Beginner

Water Tank Level Monitor with ESP32 and Ultrasonic Sensor (Leak Alert)

Build a rooftop water tank level monitor with ESP32 and a JSN-SR04T or HC-SR04: level % formula, median filter, phone page, night leak alert and moisture tips.

On this page
Water Tank Level Monitor with ESP32 and Ultrasonic Sensor (Leak Alert)

In many Nepali homes, the water tank sits on the roof. Nobody knows how full it is until the tap runs dry or water starts pouring over the side. So someone climbs the stairs to check, again and again.

This project puts an ultrasonic sensor on the tank lid and an ESP32 nearby. The ESP32 measures the distance to the water, turns it into a level percentage and shows it on a page you open on your phone over home Wi-Fi. As a final twist, it watches the level overnight and warns you if water drops when nobody should be using it, which may mean a leak. It is a practical home build and a solid base for a BE or BSc CSIT project.

Safety first: this guide stays on low voltage (5 V USB power). Water pumps run on mains electricity. If you want the system to control a pump, that wiring must be done by a qualified electrician using a proper contactor or pump controller. Do not connect mains to a relay module on a breadboard.

What you need

Scroll sideways to see all columns.

Item Qty Notes
ESP32 DevKit (ESP32-WROOM-32) 1 Wi-Fi built in
Waterproof ultrasonic sensor (JSN-SR04T style) 1 Recommended for tanks. An HC-SR04 works for a bench test
1 kΩ and 2 kΩ resistors 1 each Voltage divider for the echo signal
5 V active buzzer, NPN transistor and 1 kΩ base resistor 1 Optional local alarm
Weatherproof enclosure with a cable gland 1 For the electronics
5 V USB adapter and cable 1 Kept indoors or in a dry, covered spot
Jumper wires, multi-core cable 1 set Cable long enough to reach from the lid to the box

JSN-SR04T vs HC-SR04

The HC-SR04 is the cheap blue sensor from our distance meter tutorial. It works on the bench, but inside a tank the air is humid and condensation forms on everything. The open transducers corrode and give wrong readings.

A JSN-SR04T style sensor has a sealed, waterproof probe on a cable, with a separate control board. The probe goes in the lid; the board stays in the dry enclosure. One important difference: it has a larger blind zone, a minimum distance below which it cannot measure. On many modules this is around 20 cm to 25 cm, but versions differ, so check your module's datasheet. Mount the probe so the water at "full" is still further away than the blind zone.

Wiring

Both sensors are usually powered at 5 V, and their echo output is then a 5 V signal. The ESP32 is a 3.3 V chip, so the echo pin must go through a voltage divider.

Scroll sideways to see all columns.

Sensor pin Connects to
VCC ESP32 5V (VIN) pin, from USB
GND ESP32 GND
TRIG ESP32 GPIO 26
ECHO 1 kΩ resistor to GPIO 27; 2 kΩ resistor from GPIO 27 to GND
Buzzer (optional) 5 V active buzzer through an NPN low-side driver. GPIO 25 → 1 kΩ → base, emitter → GND, collector → buzzer −, buzzer + → 5 V

Share grounds. If using an inductive buzzer, add a flyback diode across its terminals with the cathode at +5 V. GPIO 26, 27 and 25 are safe general-purpose pins, away from the ESP32's strapping and flash pins. Some JSN-SR04T versions also run from 3.3 V; if your datasheet says so and you power it from 3V3, the divider is not needed.

The level formula

The sensor measures the distance from the lid down to the water, not the water level. So we measure two distances on your own tank first:

  • EMPTY_CM: distance from the sensor to the water when the tank is at your "empty" point (the outlet pipe level, not the very bottom).
  • FULL_CM: distance from the sensor to the water when the tank is full (just below the overflow).

Then:

  • Water height above empty = EMPTY_CM − reading
  • Level % = (EMPTY_CM − reading) ÷ (EMPTY_CM − FULL_CM) × 100

Worked example with made-up tank numbers: if EMPTY_CM is 120 and FULL_CM is 30, and the sensor reads 55, the level is (120 − 55) ÷ (120 − 30) × 100, about 72 percent. Clamp the result between 0 and 100 so small errors do not show 103 percent.

Measure your tank with a tape when it is near full and near empty. Every tank is different, and the outlet height matters.

Why a median filter

Ultrasonic readings in a tank jump around: ripples from the inlet, echoes off the tank walls, the odd missed echo. Instead of trusting one reading, take five attempts, discard missed echoes, and use the median of the valid readings. With fewer than three valid echoes, show a sensor error. A median ignores a single wild value far better than an average does.

Complete code

sketch-1.inoDownload code
// ESP32 tank level monitor with night leak check - not compiled yet
#include <WiFi.h>
#include <WebServer.h>
#include <time.h>

const char* WIFI_SSID = "YourWiFi";
const char* WIFI_PASS = "YourPassword";

const int TRIG_PIN = 26;
const int ECHO_PIN = 27;       // through 1k/2k divider
const int BUZZER_PIN = 25;     // via NPN transistor

const float EMPTY_CM = 120.0;  // measure on YOUR tank
const float FULL_CM  = 30.0;   // must be beyond the blind zone
const float LEAK_DROP_PERCENT = 5.0;
const int   QUIET_START_HOUR = 1;   // 1 AM
const int   QUIET_END_HOUR   = 4;   // 4 AM

WebServer server(80);
float levelPercent = -1;
float quietStartLevel = -1;
bool  leakSuspected = false;

float readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000);  // timeout about 5 m
  if (us == 0) return -1;                             // no echo
  return us * 0.0343 / 2.0;
}

float medianDistance() {
  float v[5];
  int count = 0;
  for (int i = 0; i < 5; i++) {
    float distance = readDistanceCm();
    if (distance >= 0) v[count++] = distance;
    delay(60);
  }
  if (count < 3) return -1;                 // too few valid echoes
  for (int i = 0; i < count - 1; i++)
    for (int j = i + 1; j < count; j++)
      if (v[j] < v[i]) { float t = v[i]; v[i] = v[j]; v[j] = t; }
  return (v[(count - 1) / 2] + v[count / 2]) / 2.0;
}

float toPercent(float d) {
  float p = (EMPTY_CM - d) / (EMPTY_CM - FULL_CM) * 100.0;
  return constrain(p, 0, 100);
}

void handleRoot() {
  String html = "<html><head><meta name='viewport' content='width=device-width'>"
                "<meta http-equiv='refresh' content='10'></head><body style='font-family:sans-serif'>"
                "<h2>Water tank</h2>";
  if (levelPercent < 0) html += "<p>Sensor error</p>";
  else html += "<p style='font-size:48px'>" + String(levelPercent, 0) + "%</p>";
  if (leakSuspected) html += "<p style='color:red'>Possible leak: level dropped overnight</p>";
  html += "</body></html>";
  server.send(200, "text/html", html);
}

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);

  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.print("\nOpen http://"); Serial.println(WiFi.localIP());

  configTime(5 * 3600 + 45 * 60, 0, "pool.ntp.org");   // Nepal time, UTC+5:45
  server.on("/", handleRoot);
  server.begin();
}

unsigned long lastRead = 0;

void loop() {
  server.handleClient();
  if (millis() - lastRead < 5000) return;
  lastRead = millis();

  float d = medianDistance();
  levelPercent = (d < 0) ? -1 : toPercent(d);
  Serial.printf("distance=%.1f cm level=%.0f%%\n", d, levelPercent);

  struct tm now;
  if (levelPercent >= 0 && getLocalTime(&now)) {
    if (now.tm_hour == QUIET_START_HOUR && quietStartLevel < 0) {
      quietStartLevel = levelPercent;            // remember level at 1 AM
    }
    if (now.tm_hour == QUIET_END_HOUR && quietStartLevel >= 0) {
      leakSuspected = (quietStartLevel - levelPercent) > LEAK_DROP_PERCENT;
      quietStartLevel = -1;                      // reset for next night
    }
  }
  digitalWrite(BUZZER_PIN, leakSuspected ? HIGH : LOW);
}

Open the IP address from the Serial Monitor on your phone (same Wi-Fi). The page refreshes every 10 seconds. To view the level from outside your home, send the value to a dashboard instead; our ESP32 Blynk dashboard guide shows how.

The leak alert twist

The logic is simple: between 1 AM and 4 AM, most households use little or no water, and the pump is usually off. If the level drops by more than five percentage points during those hours, something may be leaking: a dripping float valve, a cracked pipe or an open tap.

Adjust the quiet hours to suit your home, and expect some false alarms (a night-time bathroom visit, the municipal supply refilling the tank). It is a learning feature, not a certified leak detector. For a final year project, logging the level every few minutes and plotting it over a week makes this twist much stronger.

Keep moisture out of the electronics

Condensation kills boards. A few habits make the build last:

  • Electronics outside the tank. Only the waterproof probe goes in the lid. The ESP32 and sensor board live in a sealed box beside it.
  • Use a cable gland where the cable enters the box, not a hole stuffed with tape.
  • Drip loop: let the cable dip below the box entry before it rises into it, so water runs off instead of following the cable inside.
  • Mount the box under cover, out of direct rain and sun, with the USB adapter indoors.
  • Silica gel sachets inside the box help in the monsoon. Replace them when they become saturated.

Troubleshooting

Scroll sideways to see all columns.

Symptom Likely cause Fix
Page shows "Sensor error" No echo, wrong wiring, divider wrong Check TRIG/ECHO pins and divider; check sensor power
Level stuck at 100% when tank is full Water inside the blind zone Raise the probe or lower FULL_CM point
Readings jump a lot Ripples, echoes off walls or inlet Mount the probe away from the inlet and walls; use the median
Level wrong by a fixed amount EMPTY_CM or FULL_CM not measured on your tank Re-measure with a tape
HC-SR04 stopped working after a week Condensation corroded it Use a waterproof probe
Leak alert never triggers Time not synced Check Wi-Fi and NTP; print the time to Serial
ESP32 resets randomly Weak USB adapter or long thin cable Use a better 5 V adapter and shorter, thicker power cable

FAQ

Can I use this to switch the pump on and off?

Not with a breadboard relay. Pumps run on mains, so automatic control must be designed and wired by a qualified electrician with a proper contactor or pump controller. Read our relay module guide to understand why.

Will this work on an underground tank?

The same idea works, but Wi-Fi range, deeper tanks and wetter air are harder. Check the sensor's maximum range and protect the electronics even more carefully.

Can I run it on a battery?

Yes, by combining it with ESP32 deep sleep and reading every few minutes. The ESP32 Deep Sleep guide on ElectroDai explains how.

Is this good for a final year project?

Yes. Add data logging, a dashboard, multiple tanks, and a proper testing chapter that compares readings with a measuring tape. For more ideas see our ESP32 IoT project ideas.

Related tutorials

See all IoT →