Quick answer: mount an HC-SR04 at the top of the tank facing down, power it from 5 V, connect TRIG to D1 and ECHO to D2 through a 1 kΩ / 2 kΩ divider (the ESP8266 is 3.3 V only), and convert the measured air gap to a level: level % = (tank depth − distance) ÷ (tank depth − full distance) × 100. Calibrate both distances on your own tank. This build adds an OLED readout, a buzzer at 90 % and a JSON endpoint, and keeps working even when Wi-Fi is down.
What You Will Build
An overflowing tank wastes water and electricity, and a dry tank can burn out a pump. AquaWatch solves both with a small, self-hosted monitor you can build in an afternoon. An ESP8266 measures the water level with an HC-SR04 ultrasonic sensor, shows the result on a 128×64 OLED screen, sounds a buzzer when the tank is nearly full, and publishes live data as JSON on your local network. There is no cloud account, no subscription and no internet needed.
What it does:
- Measures the distance from the top of the tank to the water surface and converts it to depth and percentage
- Shows depth, percentage, a progress bar, status and the device's IP address on the OLED
- Sounds a repeating beep when the level reaches 90%
- Serves a human-readable status page at
/and machine-readable JSON at/data - Runs a non-blocking loop, so the screen, buzzer and web server all stay responsive
Time: about two hours. Skill level: beginner, with careful wiring.
How It Measures Water Level
The HC-SR04 is mounted at the top of the tank, facing down. It sends a short burst of ultrasound and times how long the echo takes to return from the water surface. Sound travels at about 0.0343 cm per microsecond at room temperature, and the pulse has to travel there and back, so:
distance (cm) = echo time (µs) × 0.0343 / 2The sensor measures the air gap, so a smaller distance means more water. The sketch converts it with two numbers you set for your own tank:
TANK_DEPTH_CM: the distance from the sensor face to the bottom of the empty tank.FULL_CM: the distance at which you consider the tank full. Keep it a few centimetres below the sensor, because the HC-SR04 cannot measure closer than about 2 cm.
From those, the code computes:
water depth (cm) = TANK_DEPTH_CM − distance
level (%) = (TANK_DEPTH_CM − distance) ÷ (TANK_DEPTH_CM − FULL_CM) × 100With the default demo values (14 cm and 5 cm), a reading of 8 cm gives a depth of 6 cm and a level of 66%. The buzzer alert at 90% triggers when the distance falls to 5.9 cm or less.
Which Level Sensor Should You Use?
Ultrasonic sensing is not the only option. Each method suits different tanks:
| Method | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Ultrasonic (HC-SR04, this project) | Echo time to the surface | Non-contact, continuous reading, cheap | Needs clear air above water, ignores below 2 cm, suffers in steam and condensation |
| Conductive probes (e.g. HS-S37P strip) | Water bridges exposed copper traces | Very cheap, simple analog steps | Only a few levels, corrodes with prolonged immersion |
| Float switch | A float flips a switch | Reliable, no calibration | Single fixed level per switch |
| Pressure sensor | Pressure at the bottom grows with depth | Works in closed or turbulent tanks | More costly, needs calibration |
For a household tank where you want a continuous percentage without touching the water, ultrasonic is a very good first choice.
Components
8 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
Wiring
| Part | Pin | ESP8266 pin |
|---|---|---|
| HC-SR04 | VCC | VIN / 5V |
| HC-SR04 | GND | GND |
| HC-SR04 | TRIG | D1 (GPIO5) |
| HC-SR04 | ECHO | D2 (GPIO4) through a voltage divider |
| OLED | VCC | 3V3 |
| OLED | GND | GND |
| OLED | SDA | D6 (GPIO12) |
| OLED | SCL | D7 (GPIO13) |
| Buzzer | + | D5 (GPIO14) |
| Buzzer | − | GND |
The voltage divider on ECHO. The HC-SR04 runs on 5 V, so its ECHO pin outputs a 5 V pulse, but ESP8266 pins tolerate only 3.3 V. Connect ECHO to a 1 kΩ resistor, join the other end of that resistor to D2, and connect a 2 kΩ resistor from that junction to GND. The two resistors scale 5 V down to about 3.3 V. TRIG is driven by the ESP8266's 3.3 V output, which the HC-SR04 reads as a valid HIGH.
Why the OLED is on D6 and D7. The default I2C pins on many ESP8266 boards are D1 and D2, but the sensor uses those. The sketch therefore starts I2C on other pins with Wire.begin(12, 13).
🚨 Danger
Never connect the HC-SR04 ECHO pin directly to an ESP8266 GPIO. It outputs 5 V, and the ESP8266 is only rated for 3.3 V. A direct connection can damage the pin or the chip. Always use the 1 kΩ and 2 kΩ divider, or a level shifter.
Software Setup
- In File → Preferences, add
http://arduino.esp8266.com/stable/package_esp8266com_index.jsonto Additional boards manager URLs. - In Boards Manager, install esp8266 by ESP8266 Community.
- Choose NodeMCU 1.0 (ESP-12E Module), or LOLIN(WEMOS) D1 R2 & mini for a D1 mini.
- In Library Manager, install Adafruit SSD1306 and Adafruit GFX Library. Accept any dependency prompt such as Adafruit BusIO.
ESP8266WiFiandESP8266WebServership with the board package.
Then put your own Wi-Fi name and password in the two lines near the top of the sketch.
💡 Tip
Never publish your real Wi-Fi name and password in code you share. The sketch below uses placeholders. If you copy a sketch from a repository or article, replace them with your own before uploading, and change your Wi-Fi password if you ever posted it by mistake.
The Complete Sketch
/*
=====================================================
AquaWatch — ESP8266 + HC-SR04 + SSD1306 OLED
=====================================================
HC-SR04 mounted at the TOP of the tank facing down.
Shorter distance = more water (higher level).
WIRING:
─────────────────────────────────────────────────────
HC-SR04 VCC → 5V
HC-SR04 GND → GND
HC-SR04 TRIG → D1 (GPIO5)
HC-SR04 ECHO → D2 (GPIO4) ← 1kΩ+2kΩ voltage divider!
Buzzer (+) → D5 (GPIO14)
Buzzer (–) → GND
OLED VCC → 3.3V
OLED GND → GND
OLED SDA → D6 (GPIO12) ← custom I2C (D1/D2 taken by HC-SR04)
OLED SCL → D7 (GPIO13)
NOTE: Default I2C (D1=SCL, D2=SDA) conflicts with HC-SR04,
so we use Wire.begin(12, 13) for software I2C.
CALIBRATION:
─────────────────────────────────────────────────────
Set TANK_DEPTH_CM = distance from sensor to EMPTY tank bottom.
Set FULL_CM = distance at which tank is considered FULL.
=====================================================
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// ── WiFi ──────────────────────────────────────────────────
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
// ── Pins ──────────────────────────────────────────────────
#define TRIG_PIN 5 // D1 = GPIO5
#define ECHO_PIN 4 // D2 = GPIO4
#define BUZZER_PIN 14 // D5 = GPIO14
#define OLED_SDA 12 // D6 = GPIO12 (custom I2C)
#define OLED_SCL 13 // D7 = GPIO13 (custom I2C)
// ── OLED ──────────────────────────────────────────────────
#define SCREEN_W 128
#define SCREEN_H 64
#define OLED_ADDR 0x3C // most SSD1306 modules use 0x3C; try 0x3D if blank
Adafruit_SSD1306 display(SCREEN_W, SCREEN_H, &Wire, -1);
// ── Tank configuration ────────────────────────────────────
#define TANK_DEPTH_CM 14.0 // cm — sensor to empty tank bottom
#define FULL_CM 5.0 // cm — considered FULL (headroom)
#define ALERT_PERCENT 90 // % — buzzer triggers here
// ── Buzzer timing ─────────────────────────────────────────
#define BEEP_ON_MS 250
#define BEEP_OFF_MS 300
// ── Globals ───────────────────────────────────────────────
ESP8266WebServer server(80);
float distanceCm = 0.0; // raw sensor reading (sensor → water surface)
float waterDepthCm = 0.0; // actual water depth in container
int levelPct = 0;
bool isAlert = false;
unsigned long lastReadTime = 0;
unsigned long lastBeepTime = 0;
unsigned long lastOledTime = 0;
bool beepOn = false;
// ── Measure distance via HC-SR04 ─────────────────────────
float measureDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long dur = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (dur == 0) return -1.0;
return (dur * 0.0343f) / 2.0f;
}
// ── Distance → percent ────────────────────────────────────
int distanceToPct(float d) {
if (d < 0) return -1;
if (d <= FULL_CM) return 100;
if (d >= TANK_DEPTH_CM) return 0;
float fillable = TANK_DEPTH_CM - FULL_CM;
float water = TANK_DEPTH_CM - d;
return (int)((water / fillable) * 100.0f);
}
// ── Sensor read ───────────────────────────────────────────
void readSensor() {
distanceCm = measureDistance();
int pct = distanceToPct(distanceCm);
levelPct = (pct < 0) ? 0 : pct;
// Hysteresis: alert at ALERT_PERCENT, clear only 5 % lower, so ripples don't make it chatter
if (distanceCm < 0) isAlert = false;
else if (levelPct >= ALERT_PERCENT) isAlert = true;
else if (levelPct < ALERT_PERCENT - 5) isAlert = false;
// Water depth = tank height minus air gap above water
if (distanceCm < 0) {
waterDepthCm = -1.0; // sensor error
} else if (distanceCm >= TANK_DEPTH_CM) {
waterDepthCm = 0.0; // empty
} else {
waterDepthCm = TANK_DEPTH_CM - distanceCm;
if (waterDepthCm < 0) waterDepthCm = 0;
}
Serial.print("Water depth: ");
if (waterDepthCm < 0) Serial.print("ERR");
else { Serial.print(waterDepthCm, 1); Serial.print(" cm"); }
Serial.print(" Level: "); Serial.print(levelPct); Serial.print("%");
Serial.print(" ");
if (distanceCm < 0) Serial.println("SENSOR ERROR");
else if (isAlert) Serial.println("ALERT ***");
else if (levelPct < 10) Serial.println("LOW");
else Serial.println("OK");
}
// ── Non-blocking buzzer ───────────────────────────────────
void handleBuzzer() {
if (!isAlert) { digitalWrite(BUZZER_PIN, LOW); beepOn = false; return; }
unsigned long now = millis();
if (beepOn && (now - lastBeepTime >= BEEP_ON_MS)) {
digitalWrite(BUZZER_PIN, LOW); beepOn = false; lastBeepTime = now;
} else if (!beepOn && (now - lastBeepTime >= BEEP_OFF_MS)) {
digitalWrite(BUZZER_PIN, HIGH); beepOn = true; lastBeepTime = now;
}
}
// ── OLED draw ─────────────────────────────────────────────
void updateOled() {
display.clearDisplay();
// ── Header bar ──────────────────────────────
display.fillRect(0, 0, SCREEN_W, 13, SSD1306_WHITE);
display.setTextColor(SSD1306_BLACK);
display.setTextSize(1);
display.setCursor(2, 3);
display.print("AquaWatch");
// WiFi dot (right side of header)
bool wifiOk = (WiFi.status() == WL_CONNECTED);
display.fillCircle(120, 6, 4, wifiOk ? SSD1306_BLACK : SSD1306_WHITE);
if (!wifiOk) display.drawCircle(120, 6, 4, SSD1306_BLACK);
display.setTextColor(SSD1306_WHITE);
// ── Water depth row ─────────────────────────
display.setTextSize(1);
display.setCursor(0, 17);
display.print("Depth:");
display.setCursor(38, 17);
if (waterDepthCm < 0) display.print("--.- cm");
else { display.print(waterDepthCm, 1); display.print(" cm"); }
// ── Level row ───────────────────────────────
display.setCursor(0, 28);
display.print("Level:");
display.setCursor(40, 28);
display.print(levelPct);
display.print("%");
// ── Progress bar ────────────────────────────
display.drawRect(0, 38, SCREEN_W, 10, SSD1306_WHITE);
int fillW = (int)((levelPct / 100.0f) * (SCREEN_W - 2));
if (fillW > 0) display.fillRect(1, 39, fillW, 8, SSD1306_WHITE);
// Stripe overlay when alert (danger pattern)
if (isAlert) {
for (int x = 1; x < SCREEN_W - 1; x += 6)
display.drawFastVLine(x, 39, 8, SSD1306_BLACK);
}
// ── Status row ──────────────────────────────
display.setCursor(0, 51);
if (distanceCm < 0) display.print("! SENSOR ERROR");
else if (isAlert) display.print("!! ALERT - FULL");
else if (levelPct >= 70) display.print("HIGH");
else if (levelPct < 10) display.print("LOW");
else display.print("NORMAL");
// IP (right-aligned in status row)
if (wifiOk) {
String ip = WiFi.localIP().toString();
int ipX = SCREEN_W - (ip.length() * 6);
display.setCursor(ipX, 51);
display.print(ip);
} else {
display.setCursor(72, 51);
display.print("No WiFi");
}
display.display();
}
// ── /data JSON endpoint ───────────────────────────────────
void handleData() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Cache-Control", "no-cache");
String status = "DRY";
if (distanceCm < 0) status = "ERROR";
else if (isAlert) status = "FULL";
else if (levelPct >= 70) status = "HIGH";
else if (levelPct >= 10) status = "NORMAL";
else status = "LOW";
String json = "{";
json += "\"waterDepth\":" + String(waterDepthCm < 0 ? 0 : waterDepthCm, 1) + ",";
json += "\"distance\":" + String(distanceCm, 1) + ",";
json += "\"percent\":" + String(levelPct) + ",";
json += "\"tankDepth\":" + String(TANK_DEPTH_CM, 1) + ",";
json += "\"fullCm\":" + String(FULL_CM, 1) + ",";
json += "\"alertPct\":" + String(ALERT_PERCENT) + ",";
json += "\"isAlert\":" + String(isAlert ? "true" : "false") + ",";
json += "\"status\":\"" + status + "\"";
json += "}";
server.send(200, "application/json", json);
}
void handleOptions() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
server.sendHeader("Access-Control-Allow-Headers", "Content-Type");
server.send(204);
}
void handleRoot() {
String html = "<html><body style='font-family:monospace;padding:20px;"
"background:#0a0e14;color:#e8f4fd'>";
html += "<h2>AquaWatch — Ultrasonic + OLED</h2>";
html += "<p>IP: " + WiFi.localIP().toString() + "</p>";
html += "<p>Distance: " + String(distanceCm, 1) + " cm</p>";
html += "<p>Water level: " + String(levelPct) + "%</p>";
html += "<p>Alert: " + String(isAlert ? "YES" : "no") + "</p>";
html += "<p><a href='/data' style='color:#00e5ff'>→ /data (JSON)</a></p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
// ── Setup ─────────────────────────────────────────────────
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
// Init I2C on custom pins for OLED
Wire.begin(OLED_SDA, OLED_SCL); // SDA=D6(GPIO12), SCL=D7(GPIO13)
// Init OLED
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("SSD1306 not found! Check wiring & I2C address (0x3C or 0x3D).");
} else {
display.clearDisplay();
// Splash screen
display.fillRect(0, 0, SCREEN_W, 13, SSD1306_WHITE);
display.setTextColor(SSD1306_BLACK);
display.setCursor(18, 3);
display.print("AquaWatch v2.0");
display.setTextColor(SSD1306_WHITE);
display.setCursor(10, 20);
display.print("HC-SR04 Ultrasonic");
display.setCursor(22, 32);
display.print("+ SSD1306 OLED");
display.setCursor(28, 48);
display.print("Initializing...");
display.display();
delay(2000);
}
// Startup beep
digitalWrite(BUZZER_PIN, HIGH); delay(120);
digitalWrite(BUZZER_PIN, LOW);
Serial.println("\nAquaWatch — HC-SR04 + OLED Build");
Serial.println("──────────────────────────────────");
Serial.print("Tank depth : "); Serial.print(TANK_DEPTH_CM); Serial.println(" cm");
Serial.print("Full mark : "); Serial.print(FULL_CM); Serial.println(" cm");
Serial.print("Alert level : "); Serial.print(ALERT_PERCENT); Serial.println("%");
Serial.print("OLED I2C : SDA=D6(GPIO12) SCL=D7(GPIO13) Addr=0x");
Serial.println(OLED_ADDR, HEX);
Serial.println("──────────────────────────────────");
// Connecting screen on OLED
display.clearDisplay();
display.fillRect(0, 0, SCREEN_W, 13, SSD1306_WHITE);
display.setTextColor(SSD1306_BLACK);
display.setCursor(20, 3);
display.print("Connecting WiFi");
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 22);
display.print(ssid);
display.display();
WiFi.begin(ssid, password);
Serial.print("Connecting WiFi");
int dots = 0;
unsigned long wifiStart = millis();
while (WiFi.status() != WL_CONNECTED && millis() - wifiStart < 20000) { // give up after 20 s
delay(500);
Serial.print(".");
display.fillRect(0, 36, SCREEN_W, 10, SSD1306_BLACK);
display.setCursor(0, 36);
for (int i = 0; i <= dots % 6; i++) display.print(".");
display.display();
dots++;
}
if (WiFi.status() == WL_CONNECTED) Serial.println("\nConnected!");
else Serial.println("\nNo Wi-Fi yet: monitoring offline, the ESP8266 keeps retrying in the background");
Serial.print("IP: "); Serial.println(WiFi.localIP());
// Connected screen on OLED
display.clearDisplay();
display.fillRect(0, 0, SCREEN_W, 13, SSD1306_WHITE);
display.setTextColor(SSD1306_BLACK);
display.setCursor(28, 3);
display.print("WiFi Ready!");
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 20);
display.print("IP:");
display.setCursor(0, 32);
display.print(WiFi.localIP());
display.display();
delay(1500);
server.on("/", HTTP_GET, handleRoot);
server.on("/data", HTTP_GET, handleData);
server.on("/data", HTTP_OPTIONS, handleOptions);
server.onNotFound([](){ server.send(404, "text/plain", "Not found"); });
server.begin();
Serial.println("Server ready.\n");
}
// ── Loop ──────────────────────────────────────────────────
void loop() {
server.handleClient();
handleBuzzer();
unsigned long now = millis();
// Read sensor every 1 second
if (now - lastReadTime >= 1000) {
lastReadTime = now;
readSensor();
}
// Refresh OLED every 500 ms
if (now - lastOledTime >= 500) {
lastOledTime = now;
updateOled();
}
}How the Code Works
Configuration
All the values you are likely to change sit near the top: Wi-Fi credentials, pins, the OLED address, TANK_DEPTH_CM, FULL_CM, ALERT_PERCENT and the buzzer timings. You should not need to touch the functions below to adapt the project to your tank.
measureDistance()
The function sends a clean 10 µs trigger pulse, then pulseIn() measures how long ECHO stays HIGH. The 30,000 µs timeout stops it waiting forever when no echo returns, in which case it returns -1 to signal an error. Otherwise it applies the speed-of-sound formula. A 30 ms timeout corresponds to roughly 5 m, comfortably beyond the sensor's range.
distanceToPct()
This maps distance to a percentage with clamping at both ends. At or closer than FULL_CM the level is 100%. At or beyond TANK_DEPTH_CM it is 0%. In between it scales linearly. Notice that the percentage is relative to the usable range (TANK_DEPTH_CM - FULL_CM), while the depth is a real physical value. With the defaults, the maximum depth shown is 9 cm, which equals 100%.
readSensor()
Once a second this function takes a reading, converts it to percentage and depth, sets the alert flag, and prints a status line to the Serial Monitor. The alert uses hysteresis: it switches on at 90 % but only switches off below 85 %, so a surface rippling around 90 % doesn't make the buzzer start and stop every second. An error reading (-1) forces the level to 0, sets depth to -1, and shows "SENSOR ERROR" on the display.
handleBuzzer()
The buzzer uses millis() instead of delay(), so it beeps 250 ms on and 300 ms off without freezing the screen or the web server. When the alert clears, the pin is forced LOW immediately.
updateOled()
The function redraws the screen from scratch twice a second: a header bar with a Wi-Fi indicator, depth, level, a progress bar with a striped warning pattern in alert, a status word (LOW, NORMAL, HIGH, FULL, or an error) and the device IP.
Web endpoints
/ shows a plain status page. /data returns JSON, with Access-Control-Allow-Origin: * so web pages from other addresses can read it. The handleOptions() function answers the browser's pre-flight check.
setup() and loop()
setup() initialises pins, the OLED and Wi-Fi, showing progress on the screen. It waits up to 20 seconds for Wi-Fi and then carries on regardless, so the level display and buzzer work even when the router is off; the ESP8266 reconnects on its own once the network returns. loop() runs three independent timers: the web server runs continuously, the sensor is read every second, and the OLED refreshes every 500 ms. Nothing blocks, so all three stay responsive.
Calibrating Your Tank
Steps
- 1Mount the HC-SR04 at the top of the empty tank, facing straight down, with the sensor face level.
- 2Put your own Wi-Fi name and password into the sketch, select your board and upload.
- 3Watch the OLED. It shows "Connecting WiFi" and then the device IP address. Note the IP.
- 4On a phone or computer on the same network, open http://<device-ip>/ . The page shows the live Distance in centimetres.
- 5With the tank empty, read the Distance. That is your TANK_DEPTH_CM. Confirm it with a ruler.
- 6Fill the tank to the highest level you want to use and read the Distance again. That is your FULL_CM. Keep it at 5 cm or more from the sensor for a margin.
- 7Edit TANK_DEPTH_CM and FULL_CM in the sketch, and re-upload.
- 8Add water in stages and check that the level rises smoothly to 100%.
- 9Confirm the buzzer starts at 90% and stops when the level drops below it.
Using the /data JSON
Open http://<device-ip>/data and you will see a response like this:
{
"waterDepth": 6.0,
"distance": 8.0,
"percent": 66,
"tankDepth": 14.0,
"fullCm": 5.0,
"alertPct": 90,
"isAlert": false,
"status": "NORMAL"
}| Field | Meaning |
|---|---|
waterDepth | Water depth in cm (0 if the sensor has an error) |
distance | Raw distance from sensor to water surface, in cm |
percent | Level from 0 to 100, relative to the usable range |
tankDepth, fullCm, alertPct | The calibration values compiled into the sketch |
isAlert | true when the level has reached the alert percentage |
status | ERROR, LOW, NORMAL, HIGH or FULL |
Because the data is JSON with CORS enabled, you can read it from your own web dashboard. A minimal example:
async function refresh() {
const res = await fetch("http://192.168.1.105/data"); // your device IP
const d = await res.json();
console.log(d.percent + "% - " + d.waterDepth + " cm - " + d.status);
}
setInterval(refresh, 1000);A page served over https:// cannot call an http:// address because browsers block mixed content, so open your dashboard from a local file or a plain-HTTP address.
Installing It in a Real Tank
A bench demo is forgiving. A real tank is not. These details decide whether the monitor keeps working:
- Keep the beam clear. The HC-SR04 sends a cone of about 15 degrees. Pipes, ladders, float arms or the tank wall inside that cone create false echoes. Aim for a clear vertical path.
- Mount it level. A tilted sensor sends the echo away from the sensor and gives erratic readings or errors.
- Respect the blind zone. Anything closer than about 2 cm cannot be measured, so mount the sensor at least a few centimetres above the highest water level you want to read.
- Fight condensation. The standard HC-SR04 is not waterproof, and moisture corrodes its pins and degrades readings. Mount it under a lid or shade, seal the board, and consider a waterproof ultrasonic probe (such as the JSN-SR04T) for humid tanks. Waterproof probes usually have a larger blind zone of about 20 cm, so adjust
FULL_CM. - Calm the water. Ripples, foam and incoming water scatter the echo. A vertical PVC "stilling pipe" with the sensor looking down inside it smooths the readings.
- Temperature matters. The speed of sound changes by about 0.17% per °C. For better accuracy in a tank that swings in temperature, add a temperature sensor and correct the formula.
- Keep electronics safe. Mount the ESP8266, OLED and wiring outside the water, in a ventilated, dry enclosure.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| OLED stays blank | Wrong I2C address or wiring | Confirm SDA on D6 and SCL on D7. Try OLED_ADDR 0x3D. Check the Serial Monitor for "SSD1306 not found". |
| "SENSOR ERROR" or no distance | No echo received | Check VCC at 5 V, TRIG on D1, the ECHO divider, and that the sensor faces open space. |
| Distance reads 0 or a tiny value | Target inside the blind zone or noise | Move the sensor higher, or increase the gap above the water. |
| Readings jump around | Ripples, side echoes, loose wires | Clear the beam path, use a stilling pipe, and average several readings. |
| Level never reaches 100% | FULL_CM set too low, or tank not filled enough | Re-measure the distance when the tank is full and update FULL_CM. |
| Never connects to Wi-Fi | Wrong credentials or a 5 GHz network | The ESP8266 supports only 2.4 GHz. Re-check the SSID and password. |
Compile error: D2 not declared | Wrong board selected | Select a NodeMCU or Wemos board, or use raw GPIO numbers as the sketch does. |
| Buzzer sounds constantly at power-up | Intentional startup beep | A single short beep confirms the buzzer works. A repeating beep means the level is above 90%. |
/data not reachable from a web page | Mixed content or wrong IP | Use plain HTTP, and confirm the current IP from the OLED. |
Upgrades
Smoother readings with a median filter
Single ultrasonic readings can spike. Replace measureDistance() in the call from readSensor() with a median of five readings, which discards one-off glitches:
float measureDistanceMedian() {
float v[5];
for (int i = 0; i < 5; i++) {
v[i] = measureDistance();
delay(30);
}
// simple insertion sort
for (int i = 1; i < 5; i++) {
float key = v[i];
int j = i - 1;
while (j >= 0 && v[j] > key) { v[j + 1] = v[j]; j--; }
v[j + 1] = key;
}
return v[2]; // the median
}
// in readSensor(): distanceCm = measureDistanceMedian();More ideas
- Low-level alert. Add a second alarm when the level is below 10%, to protect a pump from running dry.
- Pump automation. Add a relay module to switch a pump on at low level and off at high level. Mains pumps require proper isolation and qualified wiring.
- Notifications. Send a Telegram message or publish to MQTT when the status changes.
- Fixed IP. Reserve the device's address in your router, or set one in code as in the ESP32 static IP guide (the same
WiFi.config()works on the ESP8266), so dashboards always find it. - Wireless updates. Add ESP8266 OTA updates so you can change the calibration without taking the monitor off the tank.
- History. Log the level every few minutes to a small database or spreadsheet to see usage patterns.
Safety and Security Notes
- Keep all mains wiring, pumps and relays outside this low-voltage build unless you have proper isolation and qualified help.
- The web interface has no password and uses plain HTTP, so use it on your home network only and never forward its port to the internet.
Frequently Asked Questions
Can I use an ESP32 instead? Yes, with changes: different pin numbers, the ESP32 WebServer library, and the ESP32's 3.3 V tolerance rules. The measurement logic is identical.
How accurate is it? The HC-SR04 typically resolves about 3 mm under good conditions, but a real tank, ripples and temperature changes reduce that. Plan for a centimetre or so, and use the median filter.
Does it work with metal tanks? Yes, the sound reflects off the water surface, but inside a metal tank the walls can produce extra echoes, so keep the beam clear of them.
Can I use a JSN-SR04T waterproof sensor? Yes, with the same TRIG/ECHO wiring and divider. Its blind zone is about 20 cm, so mount it at least that far above the full water level and set FULL_CM to match.
What if my tank is much taller? Set TANK_DEPTH_CM to the real distance, up to the sensor's roughly 4 m range. The pulseIn() timeout covers distances up to about 5 m.
Related Guides
- HC-SR04 ultrasonic sensor with Arduino: how the sensor works, accuracy and wiring in depth
- ESP8266 NodeMCU pinout: which pins are safe to use, and why D1/D2 are the default I2C pins
- HC-SR04 parking alert with LCD and buzzer: the same sensor in a different project
- Arduino soil moisture auto watering: pump control with safety limits, if you add a pump
Summary
You built a complete, self-contained water level monitor: ultrasonic sensing, a unit conversion that you calibrate for your tank, an OLED readout, a non-blocking alert buzzer and a JSON API you can plug into any dashboard. You also learned how to protect the ESP8266 from a 5 V echo signal, where this sensor method excels and where it struggles, and how to prepare it for the damp, noisy reality of a real tank.
