Guides · 11 min read

ESP32 Water Tank Level Monitor: Ultrasonic, Liters and Pump

Build an ESP32 water tank level monitor with an ultrasonic sensor: percent and liters, tank formulas, JSN-SR04T, web dashboard, low-level alert and auto pump.

An ESP32 water tank level monitor shows how much water is left in a tank in percent and liters, and can switch the pump on by itself if you want. The most practical method is to mount an ultrasonic sensor in the lid, pointing down: the sensor measures the distance to the water surface, the ESP32 turns that distance into a fill percentage and liters using the tank's dimensions, and sends the result to your phone over WiFi. The same idea works for a rooftop tank, a rainwater barrel in the garden or an underground cistern.

In this guide we go step by step: working out percent and liters from distance, with formulas for vertical cylinder, rectangular and horizontal cylinder tanks; how the waterproof JSN-SR04T sensor differs and why it survives the humidity inside a tank; a first sketch that measures distance and calibrates the tank; a web dashboard you open on your phone; an alert when the water runs low; and an automatic pump with dry-run protection. The code compiles unchanged on both the 2.x and 3.x versions of the ESP32 Arduino core.

HC-SR04 ultrasonic distance sensor
HC-SR04 ultrasonic sensor: ideal for testing; inside a real, humid tank the waterproof JSN-SR04T lasts much longer.

How does a water tank level monitor work?

The ultrasonic sensor sends a short 40 kHz sound pulse and measures the time until the echo returns. Since sound travels about 343 meters per second in air at 20 °C, distance = time × speed of sound / 2; we divide by two because the sound goes out and back. Because the sensor sits at the top and points down, what it measures is the distance "from the sensor to the water surface". As the water drops, the distance grows; as the tank fills, it shrinks. Once you know the distance with the tank empty and with the tank full, every value in between becomes a percentage with a simple proportion, and liters with the tank's base area.

SensorMeasurement typeRangeWaterproof?When to choose it
HC-SR04Ultrasonic, continuous2–400 cmNoBench tests, dry and enclosed spaces
JSN-SR04T / AJ-SR04MUltrasonic, continuousAbout 20–450 cmThe probe isReal tanks, cisterns and humid spaces
Float switchMechanical, single pointOnly "full / empty"YesBackup safety against overflow or dry running
XKC-Y25 non-contact sensorCapacitive, single pointSenses through a plastic wallNever enters the tankDetecting one level without drilling the tank
Conductive-trace water level sensorAnalog, shortAbout 4 cmNo, it corrodes over timeShort experiments and overflow alarms

For a continuous level reading, ultrasonic sensors are the best choice because they never touch the water and measure the full height of the tank. The HC-SR04 is cheap and accurate, but its circuit board is exposed, so condensation inside the tank can ruin it within weeks or months. That's why we recommend building the prototype with the HC-SR04 and fitting a JSN-SR04T in the real tank; both work with the same code. A float switch isn't for measuring, but it's extremely valuable as a second safety layer for the pump. We cover the other options in detail in Water level sensor and Float level switch.

From distance to percent and liters: formulas

The calculation has two constants: D_FULL, the distance from the sensor to the water when the tank is full, and D_EMPTY, the distance from the sensor to the bottom when it's empty. If the measured distance is d, the fill percentage is (D_EMPTY − d) / (D_EMPTY − D_FULL) × 100. The water height is h = D_EMPTY − d, and the volume comes from the formulas below depending on the tank shape. If you enter all dimensions in centimeters the result is in cm³; dividing by 1000 gives liters. The example values in our code are for a 110 cm diameter cylindrical tank of about 1100 liters: when full the water is 30 cm below the sensor, when empty 150 cm. A 120 cm water column gives π × 55² × 120 / 1000 ≈ 1140 liters.

Tank shapeVolume formula (cm → liters)Example
Vertical cylinder (plastic tank, barrel)V = π × r² × h / 1000Ø110 cm, h = 100 cm → 950 L
Rectangular or cube (concrete tank, IBC tote)V = a × b × h / 1000120 × 100 cm base, h = 80 cm → 960 L
Horizontal cylinder (tank lying on its side)V = L × [r² × acos((r − h) / r) − (r − h) × √(2rh − h²)] / 1000Ø100 cm, L = 200 cm, h = 50 cm → 785 L
Cone-bottom or irregular tankCalibration table: add known amounts of water and record the distanceTake a reading every 50 L and fill in between proportionally

The formulas give a practical result: in a 110 cm diameter tank, every 1 cm of water is about 9.5 liters. An ultrasonic sensor's typical ±0.5–1 cm accuracy means ±5–10 liters of uncertainty in that tank, more than enough for home use. The biggest source of error is temperature. The speed of sound changes roughly as c = 331.3 + 0.606 × T (m/s). In a rooftop tank in the summer sun, when the air reaches 35 °C, sound travels at 352 m/s and code tuned for 20 °C measures the distance about 2.6% short. At 1 meter that's 2.6 cm, or roughly 25 liters. Set the TEMP_C constant to the tank's average temperature or, better still, measure the temperature with a DS18B20 and feed it into the formula.

Parts and wiring

ConnectionESP32Note
Sensor VCCVIN (5V)The HC-SR04 and JSN-SR04T v2 need 5 V
Sensor GNDGNDCommon ground
Sensor TRIGGPIO 26A 3.3 V trigger signal is enough
Sensor ECHOGPIO 27 (via divider)ECHO → 1 kΩ → GPIO 27; GPIO 27 → 2 kΩ → GND
Relay module INGPIO 33Most modules switch on LOW (RELAY_ACTIVE_LOW)
Relay module VCC / GNDVIN (5V) / GNDThe coil current comes from the 5V line, not the ESP32 pin
PumpRelay COM and NO terminalsSwitches the live wire only; be careful on the mains side
The sensor's ECHO output is 5 V, while ESP32 pins tolerate 3.3 V. The 1 kΩ and 2 kΩ divider brings 5 V down to 3.3 V (see the voltage divider calculator). If you connect a 120 V or 230 V pump, make sure the relay's contact rating comfortably handles the pump's start-up current, wire the mains side with screw terminals inside a closed box, and if you're not sure, have an electrician do that part. Don't put the ESP32 or the relay inside the tank; keep them in a waterproof box outside.

The JSN-SR04T is a waterproof ultrasonic sensor that moves the transducer away from the board on a cable. The probe is a sealed head like the ones on car parking sensors and connects to the control board with about 2.5 m of cable, so the board and the ESP32 can stay outside the tank. There are three differences to know. First, its blind zone is about 20–25 cm: the sensor can't see water closer than that, so mount the probe at least 25 cm above the highest water level. Second, it needs a longer trigger pulse than the HC-SR04's 10 µs; our code uses 20 µs, which suits both. Third, its beam is wider; in narrow, tall tanks mount it as close to the center as possible to reduce echoes from the walls. The v3 board runs on 3.0–5.5 V and has several operating modes; the default mode uses the same TRIG/ECHO logic as the HC-SR04.

Step-by-step build

  1. Install the ESP32 board package and test the code on the bench first, pointing the sensor at a wall or the ceiling.
  2. Wire the sensor, the ECHO divider and the relay as in the table; don't connect the pump to the relay yet.
  3. Upload the first sketch and check in the Serial Monitor that the distance matches what you measure with a tape measure.
  4. Drill a hole in the tank lid for the sensor and fix the probe perpendicular to the surface, higher above the maximum water level than its blind zone.
  5. Find D_EMPTY with the tank empty (or by measuring to the bottom) and D_FULL at the highest level.
  6. Enter the diameter or side dimensions in the main sketch, add your WiFi name and password, and upload it.
  7. Open the address shown in the Serial Monitor in your phone's browser and check the gauge and the pump status.
  8. Connect a lamp to the relay first to test the thresholds; if everything is right, connect the pump.

First sketch: measure the distance and calibrate the tank

This sketch only measures the distance and prints it to the Serial Monitor; the goal is to confirm the sensor works and to find the two constants for your tank. The readings aren't used as they come: the code takes seven readings in a row, discards the ones with no echo, sorts the rest and picks the middle value (the median). That way a ripple on the surface, drops splashed by the float valve or a single false echo from the wall don't spoil the result. That's also why we use the median instead of the average: one bad 30 cm value among 120 cm readings shifts the average by 15 cm but doesn't move the median at all.

C++ (Arduino IDE)
1// Mesafe ölçümü ve kalibrasyon (HC-SR04 ya da JSN-SR04T) / distance reading and calibration
2const int TRIG = 26;                  // tetik / trigger
3const int ECHO = 27;                  // yankı, 1k/2k bölücüyle / echo, through a 1k/2k divider
4const float TEMP_C = 25.0;            // depo içindeki hava sıcaklığı / air temperature in the tank
5
6float readDistanceCm() {
7  digitalWrite(TRIG, LOW);
8  delayMicroseconds(4);
9  digitalWrite(TRIG, HIGH);
10  delayMicroseconds(20);              // JSN-SR04T uzun tetik ister / JSN-SR04T needs a longer trigger
11  digitalWrite(TRIG, LOW);
12  unsigned long us = pulseIn(ECHO, HIGH, 30000UL);   // 30 ms ≈ 5 m
13  if (us == 0) return -1;             // yankı yok / no echo
14  float c = 331.3 + 0.606 * TEMP_C;   // ses hızı (m/s) / speed of sound (m/s)
15  return us * c / 20000.0;            // gidiş-dönüş → cm / round trip → cm
16}
17
18float medianDistance() {              // 7 ölçümün ortancası / median of 7 readings
19  float v[7];
20  int n = 0;
21  for (int i = 0; i < 7; i++) {
22    float d = readDistanceCm();
23    if (d > 0) v[n++] = d;
24    delay(70);                        // yankılar sönsün / let echoes die out
25  }
26  if (n < 3) return -1;               // sensör arızası / sensor fault
27  for (int i = 1; i < n; i++) {       // küçükten büyüğe sırala / sort ascending
28    float k = v[i];
29    int j = i - 1;
30    while (j >= 0 && v[j] > k) { v[j + 1] = v[j]; j--; }
31    v[j + 1] = k;
32  }
33  return v[n / 2];
34}
35
36void setup() {
37  Serial.begin(115200);
38  pinMode(TRIG, OUTPUT);
39  pinMode(ECHO, INPUT);
40}
41
42void loop() {
43  float d = medianDistance();
44  if (d < 0) Serial.println("Yanki yok / no echo");
45  else {
46    Serial.print("Mesafe / distance: ");
47    Serial.print(d, 1);
48    Serial.println(" cm");
49  }
50  delay(1000);
51}

There are two ways to calibrate. The most accurate is measuring with the sensor: with the tank empty, or with a rod reaching the bottom placed under the sensor, take the measured distance as D_EMPTY, and when the water reaches the overflow level write down the distance as D_FULL. If you can't empty the tank, use a tape measure: the distance from the sensor face to the bottom is D_EMPTY, and from the sensor to the lower edge of the overflow pipe is D_FULL. Then add a known amount of water, say 100 liters, and check that the liters shown go up by the same amount.

Main sketch: web dashboard and automatic pump

The main sketch connects to your home WiFi and starts a web server. When you open the ESP32's address on your phone, a page appears with a drawing of the tank that rises and falls with the level, the percentage, the liters, the measured distance and the pump status. The page refreshes itself every two seconds by fetching a small JSON packet from /data. In the same loop the ESP32 also runs the pump: it switches the relay on when the level drops below 25% and releases it above 95%. No extra libraries are needed; only WiFi and WebServer, which ship with the ESP32 package, are used.

C++ (Arduino IDE)
1#include <WiFi.h>
2#include <WebServer.h>
3
4const char* WIFI_SSID = "EvAgim";             // ev ağının adı / your Wi-Fi name
5const char* WIFI_PASS = "sifre123";           // ev ağının şifresi / your Wi-Fi password
6
7const int TRIG = 26, ECHO = 27;               // ECHO 1k/2k bölücüyle / ECHO through a 1k/2k divider
8const int RELAY = 33;                         // pompa rölesi / pump relay
9const bool RELAY_ACTIVE_LOW = true;           // çoğu röle modülü LOW ile çeker / most relay modules switch on LOW
10
11// Depo ölçüleri (cm) / tank dimensions (cm)
12const float D_FULL = 30.0;                    // depo doluyken sensör-su mesafesi / sensor-to-water distance when full
13const float D_EMPTY = 150.0;                  // depo boşken (dibe) mesafe / distance to the bottom when empty
14const float DIAMETER_CM = 110.0;              // silindir depo çapı / cylinder tank diameter
15const float TEMP_C = 25.0;                    // depo içi hava sıcaklığı / air temperature in the tank
16
17// Pompa ayarları / pump settings
18const float PUMP_ON_PCT = 25.0;               // bu yüzdenin altında çalış / start below this percent
19const float PUMP_OFF_PCT = 95.0;              // bu yüzdenin üstünde dur / stop above this percent
20const unsigned long PUMP_MAX_MS = 20UL * 60UL * 1000UL;   // en uzun çalışma 20 dk / max run time 20 min
21const unsigned long RISE_CHECK_MS = 5UL * 60UL * 1000UL;  // 5 dk'da seviye artmalı / level must rise within 5 min
22
23WebServer server(80);
24float distanceCm = -1, percent = 0, litersNow = 0, startPercent = 0;
25bool sensorOk = false, pumpOn = false, pumpLock = false;
26unsigned long pumpStart = 0, lastMeasure = 0;
27
28const char PAGE[] PROGMEM = R"rawliteral(
29<!DOCTYPE html><html><head><meta charset="utf-8">
30<meta name="viewport" content="width=device-width,initial-scale=1"><title>BlueGrays Tank</title>
31<style>
32body{margin:0;font-family:sans-serif;background:#0f172a;color:#e2e8f0;text-align:center}
33#tank{width:140px;height:220px;margin:20px auto;border:3px solid #94a3b8;border-radius:12px;position:relative;overflow:hidden}
34#water{position:absolute;bottom:0;width:100%;height:0;background:#38bdf8;transition:height 1s}
35#pct{font-size:2.4em;margin:0}.alarm{color:#f87171}
36button{padding:8px 18px;font-size:1em}
37</style></head><body>
38<h3>BlueGrays Tank</h3>
39<div id="tank"><div id="water"></div></div>
40<p id="pct">--</p><p id="info"></p><p id="st"></p>
41<button onclick="fetch('/reset')">Reset</button>
42<script>
43async function upd(){try{
44 const j=await (await fetch('/data')).json();
45 document.getElementById('water').style.height=j.pct+'%';
46 document.getElementById('pct').textContent=Math.round(j.pct)+'%';
47 document.getElementById('info').textContent=j.l+' L | '+j.d+' cm';
48 const s=document.getElementById('st');
49 s.textContent=!j.ok?'SENSOR ERROR':(j.lock?'PUMP LOCKED':(j.pump?'Pump ON':'Pump OFF'));
50 s.className=(!j.ok||j.lock||j.pct<20)?'alarm':'';
51}catch(e){}}
52setInterval(upd,2000);upd();
53</script></body></html>
54)rawliteral";
55
56float readDistanceCm() {
57  digitalWrite(TRIG, LOW);
58  delayMicroseconds(4);
59  digitalWrite(TRIG, HIGH);
60  delayMicroseconds(20);                      // JSN-SR04T uzun tetik ister / JSN-SR04T needs a longer trigger
61  digitalWrite(TRIG, LOW);
62  unsigned long us = pulseIn(ECHO, HIGH, 30000UL);
63  if (us == 0) return -1;
64  float c = 331.3 + 0.606 * TEMP_C;           // ses hızı (m/s) / speed of sound (m/s)
65  return us * c / 20000.0;
66}
67
68float medianDistance() {                      // 7 ölçümün ortancası / median of 7 readings
69  float v[7];
70  int n = 0;
71  for (int i = 0; i < 7; i++) {
72    float d = readDistanceCm();
73    if (d > 0) v[n++] = d;
74    delay(70);
75  }
76  if (n < 3) return -1;
77  for (int i = 1; i < n; i++) {
78    float k = v[i];
79    int j = i - 1;
80    while (j >= 0 && v[j] > k) { v[j + 1] = v[j]; j--; }
81    v[j + 1] = k;
82  }
83  return v[n / 2];
84}
85
86float levelPercent(float d) {                 // mesafeden doluluk yüzdesi / fill percent from distance
87  float p = (D_EMPTY - d) / (D_EMPTY - D_FULL) * 100.0;
88  return constrain(p, 0.0, 100.0);
89}
90
91float tankLiters(float d) {                   // silindir: π·r²·h / cylinder: π·r²·h
92  float h = constrain(D_EMPTY - d, 0.0, D_EMPTY - D_FULL);
93  float r = DIAMETER_CM / 2.0;
94  return PI * r * r * h / 1000.0;             // cm³ → litre / cm³ → liters
95}
96
97void setPump(bool on) {
98  if (on && !pumpOn) { pumpStart = millis(); startPercent = percent; }
99  pumpOn = on;
100  digitalWrite(RELAY, (on != RELAY_ACTIVE_LOW) ? HIGH : LOW);
101}
102
103void controlPump() {
104  if (!sensorOk || pumpLock) { setPump(false); return; }        // arıza ya da kilit: kapalı / fault or lock: off
105  if (!pumpOn && percent <= PUMP_ON_PCT) setPump(true);
106  else if (pumpOn && percent >= PUMP_OFF_PCT) setPump(false);
107  if (pumpOn) {
108    unsigned long run = millis() - pumpStart;
109    bool noRise = run > RISE_CHECK_MS && percent < startPercent + 2.0;
110    if (run > PUMP_MAX_MS || noRise) {        // kuru çalışma ya da arıza / dry run or fault
111      pumpLock = true;
112      setPump(false);
113    }
114  }
115}
116
117void handleData() {
118  char json[128];
119  snprintf(json, sizeof(json), "{\"pct\":%.1f,\"l\":%.0f,\"d\":%.1f,\"pump\":%d,\"ok\":%d,\"lock\":%d}",
120           percent, litersNow, distanceCm, pumpOn, sensorOk, pumpLock);
121  server.send(200, "application/json", json);
122}
123
124void setup() {
125  Serial.begin(115200);
126  pinMode(TRIG, OUTPUT);
127  pinMode(ECHO, INPUT);
128  pinMode(RELAY, OUTPUT);
129  setPump(false);
130
131  WiFi.mode(WIFI_STA);
132  WiFi.begin(WIFI_SSID, WIFI_PASS);
133  while (WiFi.status() != WL_CONNECTED) delay(300);
134  Serial.print("Gosterge / dashboard: http://");
135  Serial.println(WiFi.localIP());
136
137  server.on("/", []() { server.send(200, "text/html", PAGE); });
138  server.on("/data", handleData);
139  server.on("/reset", []() { pumpLock = false; server.send(200, "text/plain", "ok"); });
140  server.begin();
141}
142
143void loop() {
144  server.handleClient();
145  if (millis() - lastMeasure >= 2000) {       // her 2 saniyede ölç / measure every 2 seconds
146    lastMeasure = millis();
147    float d = medianDistance();
148    sensorOk = (d > 0);
149    if (sensorOk) {
150      distanceCm = d;
151      percent = levelPercent(d);
152      litersNow = tankLiters(d);
153    }
154    controlPump();
155  }
156}
PartWhat it does
medianDistance()Takes the median of seven readings; returns -1 if fewer than three are valid (sensor fault)
levelPercent() and tankLiters()Convert the distance into percent and, with the cylinder formula, liters; for a rectangular tank write a × b × h / 1000
PUMP_ON_PCT / PUMP_OFF_PCTHysteresis: the pump starts at 25% and stops at 95%; in between it keeps its state
PUMP_MAX_MS and RISE_CHECK_MSThe pump locks out if it runs more than 20 minutes or the level doesn't rise 2% in 5 minutes
/data and /resetServe the JSON to the dashboard and release a locked pump with the Reset button
RELAY_ACTIVE_LOWSet it to false if your relay module switches on HIGH

Running the pump safely: hysteresis and dry-run protection

Using a single threshold, "run below 50%, stop above it", looks sensible at first. But as the surface moves, the reading bounces between 49 and 51 and the pump switches on and off every second, which quickly burns out both the motor and the relay. The fix is hysteresis: the pump starts at the low threshold and doesn't stop until the high one. The real danger, though, is the pump running dry. In a typical house the pump lifts water from a lower cistern to the rooftop tank; if the cistern runs empty, the pump spins on air, overheats and can fail within minutes. Our code catches this in two ways: if the level hasn't risen at least 2% after 5 minutes of running, or if the total run time exceeds 20 minutes, it switches the pump off and locks it out. The lock stays until you press the Reset button on the page, so the pump doesn't keep retrying before the problem is fixed. If the sensor fails, meaning no echo, the pump also stays off. To fit these times to your setup, time once how many minutes your pump needs to fill the tank and adjust the limits. Relay details are in Relay module.

Before connecting the real pump, test the code with a bucket and a lamp: hold the sensor over the bucket and, adding and removing water, check that the lamp switches at the thresholds. If you also put a float switch in the cistern, wired in series with the pump's power, the pump stops electrically when the water runs out no matter what the software says; this second layer is cheap and very reliable.

Low-level alert (Telegram)

To know when the water is getting low, the ESP32 can send you a Telegram message. The snippet below is added to the main sketch: it sends a message once when the level drops below 20% and doesn't send again until the level goes back above 30%. This small hysteresis keeps hundreds of messages from flooding your phone while the level hovers between 19 and 21. We explain creating the bot and getting the token and chat ID from start to finish in ESP32 Telegram bot; you just need the UniversalTelegramBot and ArduinoJson libraries installed.

C++ (Arduino IDE)
1// Ana koda ekle: düşük seviye Telegram bildirimi / add to the main sketch: low-level Telegram alert
2#include <WiFiClientSecure.h>
3#include <UniversalTelegramBot.h>
4
5#define BOT_TOKEN "1234567890:AAExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"   // BotFather'dan / from BotFather
6#define CHAT_ID   "123456789"                 // kendi Telegram ID'n / your Telegram ID
7
8WiFiClientSecure tlsClient;
9UniversalTelegramBot bot(BOT_TOKEN, tlsClient);
10bool lowSent = false;
11
12// setup() içinde, Wi-Fi bağlandıktan sonra / in setup(), after Wi-Fi connects:
13//   tlsClient.setCACert(TELEGRAM_CERTIFICATE_ROOT);
14
15void checkLowLevel() {                        // loop() içinde controlPump()'tan sonra çağır / call after controlPump() in loop()
16  if (!sensorOk) return;
17  if (!lowSent && percent < 20) {
18    String msg = "Su deposu / water tank: %" + String(percent, 0) + " (" + String(litersNow, 0) + " L)";
19    if (bot.sendMessage(CHAT_ID, msg, "")) lowSent = true;
20  } else if (lowSent && percent > 30) {
21    lowSent = false;                          // seviye yükseldi, yeniden kur / level recovered, re-arm
22  }
23}

Mounting the sensor correctly in the tank

  • Point straight down: the sensor must face the water surface exactly perpendicular; even a few degrees of tilt can send the echo to the wall and make the reading jump.
  • Stay away from the inlet: don't put it right above the float valve or the fill pipe; falling water foams the surface and creates false echoes.
  • Stay away from the walls: mount the sensor at least 15–20 cm in from the wall, ideally near the center of the tank; internal ribs and ladders also cause echoes.
  • Respect the blind zone: leave at least 3–5 cm for the HC-SR04 and at least 25 cm for the JSN-SR04T; the overflow level must stay below that distance.
  • Protect it from humidity: condensation is unavoidable in closed tanks; keep the sensor board and the ESP32 outside the tank in a box that's ventilated but sheltered from rain.
  • Stilling pipe: if the surface is very choppy or foamy, try mounting the sensor at the top of a smooth PVC pipe with no joints, at least 10 cm in diameter, reaching down to the bottom; the pipe calms the surface. Since joints in the pipe can also echo, compare the result with a tape-measure reading.

Common problems and fixes

SymptomLikely causeFix
Always 0 cm or "no echo"Wrong ECHO wiring or divider, sensor powered from 3.3 VCheck the divider and power the sensor from 5 V
Values go haywire when the tank is fullThe water has entered the blind zoneRaise the sensor; leave at least 25 cm with the JSN-SR04T
The reading jumps by a few cmRipples, tilted mounting, echo from a wallStraighten the sensor, move it to the center and increase the number of median samples
Liters differ between summer and winterThe speed of sound changes with temperatureAdjust TEMP_C or measure the temperature with a DS18B20
The pump keeps switching on and offThe thresholds are too close togetherLeave at least 30–50% between PUMP_ON_PCT and PUMP_OFF_PCT
The pump locked out (PUMP LOCKED)Empty cistern, faulty pump or pipe, times too shortCheck the water and the pump, extend RISE_CHECK_MS to match your fill rate and press Reset
The sensor died after a few monthsHumidity in the tank corroded the HC-SR04Use a waterproof JSN-SR04T
The dashboard page won't openWrong IP or the phone is on another networkUse the address from the Serial Monitor and make sure you're on the same WiFi

Ideas to extend the project

  • Battery and solar: for a cistern far from an outlet, wake the ESP32 every 10 minutes to measure; with ESP32 deep sleep an 18650 cell lasts for weeks.
  • Smart home: send the level to Home Assistant via MQTT and keep a history graph.
  • Easy WiFi setup: instead of hard-coding the WiFi password, enter it from your phone with WiFiManager.
  • Local display: put an OLED display next to the tank to show the percentage even without internet.
  • Usage tracking: add a water flow sensor to work out how many liters you use per day.
  • Water quality: monitor the conductivity of the water in the tank with a TDS sensor.

An ESP32 water tank level monitor ends the "is there still water?" question with a few cheap parts and runs the pump for you safely. Try it on the bench with an HC-SR04 first, do the calibration, then move it to the real tank with the waterproof sensor. To learn in depth how the sensor measures, read HC-SR04 ultrasonic distance sensor. In the BlueGrays app you'll also find the ESP32 HC-SR04 distance meter, parking sensor, smart plant watering and ESP32 web server projects with step-by-step circuit diagrams and code.

Frequently asked questions

How do you measure the water level in a tank?

The most practical way is to mount an ultrasonic sensor at the top of the tank, pointing down. The sensor measures the distance to the water; using two distances, one with the tank empty and one full, that value becomes a fill percentage, and with the base area, liters. If you only need to know full and empty, a float switch is a simpler solution.

How do I calculate the liters in a cylindrical tank?

Use V = π × r² × h, where h is the water height and r the tank radius; with dimensions in centimeters, divide the result by 1000 to get liters. For example, in a 110 cm diameter tank, 100 cm of water is about 950 liters. Horizontal and cone-bottom tanks need the circular segment formula or a calibration table.

Can I use an HC-SR04 in a water tank?

It works for testing but isn't recommended long term. Condensation inside a closed tank can corrode its exposed board and transducers within weeks or months. For real use, a JSN-SR04T or AJ-SR04M with a waterproof probe lasts much longer and works with the same code.

What is the blind zone of the JSN-SR04T?

The JSN-SR04T can't measure objects closer than about 20–25 cm. That's why the probe must sit at least 25 cm above the tank's highest water level. If the water enters that zone, the sensor returns wrong or random values.

Can an ESP32 drive a water pump directly?

No. An ESP32 pin can supply a few tens of milliamps at most; the pump must be driven through a relay module or a solid-state relay. For mains-powered pumps, the relay's contact rating must handle the pump's start-up current and the wiring must be done safely inside a closed box.

How do I stop the pump from running dry?

In software, check that the level rises within a set time while the pump runs and lock the pump out if it doesn't; add a maximum run time too. In hardware, a float switch in the lower cistern, wired in series with the pump's power, cuts the pump electrically when the water runs out.

See all projects
ESP32 HC-SR04 Ultrasonic Distance Sensor
ES-14Intermediate

ESP32 HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 ultrasonic sensor measures distance by timing how long its sound pulse takes to bounce off an object and return (time of flight). In this project the ESP32 sends a 10-microsecond pulse to the TRIG pin and reads the echo time from the ECHO pin with pulseIn(). The distance is shown in cm on a 16x2 I2C LCD. The HC-SR04 runs on 5V, so the ECHO pin needs a voltage divider, or the ESP32's 3.3V GPIO gets damaged.

4.9(29)
48
HC-SR04 Distance Measurement (Serial Display)
AR-27Beginner

HC-SR04 Distance Measurement (Serial Display)

The HC-SR04 sensor works just like a bat finding its way in the dark: it sends out a sound you cannot hear, listens for the echo and measures how far away the object in front of it is.

4.6(50)
82
ESP32 Parking Sensor (HC-SR04 + 5-LED Bar + Buzzer + OLED)
ES-38Advanced
Premium

ESP32 Parking Sensor (HC-SR04 + 5-LED Bar + Buzzer + OLED)

The ESP32 version of a car parking sensor! The HC-SR04 ultrasonic sensor measures the distance to the object in front. As it gets closer, a 5-LED bar fills up (green → yellow → red) and the buzzer beeps faster. Very close (under 10 cm), a continuous alarm sounds and all LEDs light up. The SSD1306 OLED display shows the live distance in cm in large text, plus a status message.

14
Smart Irrigation Station
AR-83Advanced
Premium

Smart Irrigation Station

A gardener that waters your plants on its own, so they don't dry out while you're on vacation.

5.0(42)
57
ESP32 Asynchronous Web Server (with IP Display on LCD)
ES-27Advanced

ESP32 Asynchronous Web Server (with IP Display on LCD)

In this project, we’re turning the ESP32 into an asynchronous web server that you can control from your phone or computer on the same Wi-Fi network. Thanks to the ESPAsyncWebServer library, the server can process multiple requests simultaneously (unlike the classic WebServer.h, which blocks on a single request). You’ll be able to open the ESP32’s IP address in a browser and click the ON/OFF buttons (the /on and /off routes) to turn the LED connected to GPIO 5 on and off.

4.8(16)
26
ESP32 Motion Alarm System (PIR + Buzzer + LED + Telegram)
ES-41Advanced
Premium

ESP32 Motion Alarm System (PIR + Buzzer + LED + Telegram)

A smart security alarm: when the PIR sensor detects motion, it sounds the buzzer, lights the LED and sends the owner an instant Telegram notification. A 30-second cooldown limits how often the alarm repeats; it does not filter out the PIR sensor's false detections. Use it at home, in a garage, a storeroom or a study.

9
ESP32 Wi-Fi STA Connection (with LCD Screen)
ES-25Advanced

ESP32 Wi-Fi STA Connection (with LCD Screen)

In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

4.4(21)
38