Water tank level sensor (ultrasonic)

A JSN-SR04T waterproof sensor measures the distance to the water surface, converts it to percent and serves it on the web.

Level: Intermediate Board: ESP32 DevKit V1 (WROOM-32) Water & garden

⚠ Safety

ECHO is 5 V logic: use a 1 k / 2 k divider. Do not submerge the electronics.

What you need

Buy the parts kit · Estimated total: $10.50

ESP32 DevKit V1 (30 pin, WROOM-32) × 1
$4.00
Buy at AliExpress Buy at Amazon.com
JSN-SR04T waterproof ultrasonic sensor × 1
$5.00
Buy at AliExpress Buy at Amazon.com
Resistor kit 1/4W (1k, 2k, 4.7k, 10k, 22k, 100k) × 1
$1.50
Buy at AliExpress Buy at Amazon.com
🇺🇦 Ukraine🌍 Other countries

Other countries: order these parts on AliExpress with the links below.

Some links are affiliate links: we may earn a commission at no extra cost to you.

Wiring

ModuleModule pinESP32 pinNote
JSN-SR04T VCC / GND5V / GND
JSN-SR04T TRIGoutGPIO5
JSN-SR04T ECHOinGPIO18 via 1k/2k dividerEcho is 5 V

Code

tank-level-sensor.ino
#include <WiFi.h>

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";

bool connectWiFi(uint32_t timeoutMs = 20000) {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  uint32_t t0 = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t0 < timeoutMs) {
    delay(250);
    Serial.print(".");
  }
  Serial.println();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("IP: ");
    Serial.println(WiFi.localIP());
    return true;
  }
  return false;
}
#include <WebServer.h>

WebServer server(80);
String buildJson();   // implemented in the project below

String num(float v, int d = 1) { return isnan(v) ? String("null") : String(v, d); }

const char PAGE_HTML[] PROGMEM = R"rawliteral(
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32</title>
<style>body{font-family:system-ui;background:#0b0f14;color:#e6edf3;margin:20px}table{border-collapse:collapse}td{padding:6px 14px;border-bottom:1px solid #223}button,input{font-size:16px;padding:8px 14px;margin:4px;border-radius:6px;border:1px solid #345;background:#16202b;color:#e6edf3}</style>
</head><body><h2>ESP32</h2><table id="t"></table>
<script>
function load(){fetch('/json').then(r=>r.json()).then(d=>{let h='';for(const k in d){h+='<tr><td>'+k+'</td><td>'+d[k]+'</td></tr>';}document.getElementById('t').innerHTML=h;});}
load();setInterval(load,2000);
</script></body></html>
)rawliteral";

void startWeb() {
  server.on("/", []() { server.send_P(200, "text/html", PAGE_HTML); });
  server.on("/json", []() { server.send(200, "application/json", buildJson()); });
  server.begin();
}
const int TRIG = 5, ECHO = 18;
float TANK_EMPTY_CM = 150, TANK_FULL_CM = 20;   // distance from the sensor to the bottom / to the full level
float distCm = NAN; int pct = -1;
float measure() {
  float s[5]; int n = 0;
  for (int i = 0; i < 5; i++) {
    digitalWrite(TRIG, LOW); delayMicroseconds(4); digitalWrite(TRIG, HIGH); delayMicroseconds(12); digitalWrite(TRIG, LOW);
    long us = pulseIn(ECHO, HIGH, 40000);
    if (us > 0) s[n++] = us * 0.0343 / 2.0;
    delay(60);
  }
  if (!n) return NAN;
  for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (s[j] < s[i]) { float x = s[i]; s[i] = s[j]; s[j] = x; }
  return s[n / 2];                               // median
}
String buildJson() { return String("{\"distance_cm\":") + num(distCm) + ",\"level_%\":" + pct + "}"; }
void setup() {
  pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT);
  Serial.begin(115200);
  connectWiFi();
  startWeb();
}
void loop() {
  server.handleClient();
  static uint32_t t = 0;
  if (millis() - t > 5000) { t = millis(); distCm = measure(); pct = isnan(distCm) ? -1 : constrain((int)((TANK_EMPTY_CM - distCm) * 100.0 / (TANK_EMPTY_CM - TANK_FULL_CM)), 0, 100); }
}

Flash a ready firmware from the browser Paste your error into the AI Error Doctor

Build tips

  • Mount the sensor at least 25 cm above the maximum water level.
  • Take the median of several readings to filter splashes.

← ← All projects

Related ideas

⚠ Caution

A hobby gas sensor is not a certified alarm and does not replace a real gas or smoke detector.

Gas / smoke alarm (hobby)

MQ-2 sensor with a buzzer and a web page. A hobby add-on, not a certified detector.

  • Board ESP32 DevKit V1 (WROOM-32)
  • Level ●●○ Intermediate
  • Build time 1–2 h
Pick parts / kit

Freezer / fridge alarm

A DS18B20 probe inside the freezer; a buzzer and a message if the temperature rises or the door stays open.

  • Board ESP32 DevKit V1 (WROOM-32)
  • Level ●○○ Beginner
  • Build time 1–2 h
Pick parts / kit
⚠ Caution

A hobby gas sensor is not a certified alarm and does not replace a real gas or smoke detector.

Carbon monoxide (CO) guard (hobby)

An MQ-7 sensor with a buzzer and display for a garage, boiler room or generator shed. A hobby add-on, not a certified CO alarm.

  • Board ESP32 DevKit V1 (WROOM-32)
  • Level ●●○ Intermediate
  • Build time 1–2 h
Pick parts / kit

Comments

No comments yet. Share your experience or ask a question.

Comments are moderated.