Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Bettesworth Construction
Arduino

Water Level Detection System Using ESP32: Circuit, Code, Calibration, and Pump Safety

Learn how to build a safe ESP32 water-level monitor using a waterproof ultrasonic sensor, calibrated percentage calculations, filtered readings, float-switch interlocks, and optional automatic pump control.

By Bettesworth Construction Team 10 min read
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical ESP32 water-level system uses a sensor to measure the air gap above the water, converts that measurement into depth and percentage, and optionally controls a pump. For most household tanks and low-voltage prototypes, a waterproof ultrasonic sensor such as a JSN-SR04T is the most useful primary sensor. For automatic pumping, add an independent float switch: ultrasonic sensing provides continuous level information, while the float switch provides a separate safety interlock.

This design is suitable for monitoring overhead tanks, reservoirs, sumps, rainwater tanks, and similar installations. It is a prototype design, not certified industrial instrumentation. Permanent mains-pump wiring should be installed and tested by a qualified electrician.

As an Amazon Associate I earn from qualifying purchases.

How an ESP32 water-level system works

An ultrasonic sensor does not directly measure “percentage full.” It measures the distance between its transducer and the water surface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Air gap: distance from the sensor to the water.
  • Water depth: tank reference height minus the measured air gap.
  • Level percentage: the usable depth normalized between calibrated empty and full points.
  • Volume percentage: requires the shape of the tank to be considered.

The basic calculation is:

waterDepth = tankHeight - measuredAirGap

For a calibrated system, use:

levelPercent = 100 × (emptyAirGap - airGap) / (emptyAirGap - fullAirGap)

Clamp the result between 0 and 100 percent. A rectangular or vertical cylindrical tank has an approximately constant cross-section, so depth percentage is close to volume percentage. For a horizontal cylinder, cone, irregular tank, or tank with internal obstructions, use a tank-specific lookup table or calibration curve if volume accuracy matters.

#1 Best Overall
DIYables Water Sensor Detector for Arduino, ESP32, ESP8266, Raspberry Pi, 5 Pieces
  • Used to detect the presence of water, water leakage
  • Used to measure the water level
  • Supply voltage: 3.3 - 5V DC. Current consumption: less than 20mA
  • Water sensor for Arduino, ESP32, ESP8266, Raspberry Pi, or any 5V or 3.3V microcontroller.
  • Tutorials for Arduino, ESP32, ESP8266 and Raspberry Pi are provided => search for: DIYables Water Sensor

Recommended system architecture

Monitoring-only version

Waterproof ultrasonic sensor → ESP32 → OLED, serial output, or Wi-Fi dashboard

This version can display the level, send low-level and overflow alerts, and publish readings to a local web page, MQTT broker, Home Assistant installation, or other dashboard. The local measurement should continue even if Wi-Fi is unavailable.

Automatic pump version

Tank ultrasonic sensor ─┐
                       ├→ ESP32 → isolated relay or contactor → pump
Source-tank float ─────┘

Recommended behavior is to start filling below a low threshold, stop at a higher threshold, refuse to start when the source tank is empty, and switch the pump off on an overflow alarm, invalid sensor reading, or excessive runtime.

Choosing the level sensor

Sensor Best use Advantages Limitations
Waterproof ultrasonic Continuous tank monitoring Non-contact and easy to interface Foam, turbulence, condensation, blind zone, and reflections can cause errors
HC-SR04 Dry indoor demonstrations Cheap and widely supported Not waterproof; its echo may require level shifting
Float switch Overflow, low-level, and dry-run protection Simple, independent, and inexpensive Binary measurement; mechanical parts can stick
Conductive probe Low-cost point or multi-level detection Simple analog or digital output Electrolysis, corrosion, deposits, and water-conductivity dependence
Capacitive sensor Sealed or corrosive tanks No exposed electrodes; may work through a tank wall Requires careful calibration and mounting
Pressure sensor Deep, foamy, or turbulent tanks Continuous measurement unaffected by surface echoes Immersed sensor, sealing requirements, drift, and more complex conditioning

JSN-SR04T waterproof ultrasonic sensor

A JSN-SR04T-style module uses a remote waterproof transducer and trigger/echo interface. One published specification gives an approximate range of 25–600 cm, but minimum range, operating mode, and electrical behavior vary between module revisions and suppliers. Check the exact board and datasheet before designing around those numbers: JSN-SR04T wiring and specifications and module timing information.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Mount the transducer perpendicular to the water surface, away from inlet jets, braces, pipes, cables, and tank walls. Foam, steam, condensation, and turbulence may produce missing or false echoes. Leave sufficient clearance above the full-water point because ultrasonic sensors have a blind zone near the transducer.

Some product listings claim 3.0–5.5 V operation, but that claim applies to the particular product, not every JSN-SR04T board. The exact echo-output voltage must be confirmed. A product example is available from Circuit Rocks.

HC-SR04

The HC-SR04 is suitable for a dry indoor prototype, not a damp or splash-prone tank installation. A representative ESP32 example is documented at ESP32 ultrasonic sensor tutorial. If the module is powered at 5 V, do not assume its echo output is safe for an ESP32 GPIO.

Rank #2
EC Buying 20pc Water Level Sensor Detector Rain Drop Depth Detection for Arduino
  • Accurately measure water level and detect rainwater drops with this high-quality Water Level Sensor, designed for easy integration with development boards.
  • Simple to use and cost-effective, this Water Level Sensor features a parallel wire trace design to accurately measure water quantity, providing analog output for easy integration with development boards.
  • With a working voltage of DC3-5V and low power consumption of less than 20mA, this Water Level Sensor is an efficient and reliable choice for water level detection and alarm systems.
  • The sensor's FR4 double-sided tin-spraying and electronic component manufacturing process ensures durability and reliability, making it suitable for a wide range of applications and environments.
  • This Water Level Sensor operates in temperatures ranging from 10°C to 30°C and with a humidity range of 10% to 90% without condensation, providing accurate and consistent water level detection.

Float switches

Use a float switch as an independent source-empty, high-level, or overflow interlock. A normally closed switch is often preferable for fault detection because a broken wire can be treated as an unavailable or unsafe condition, although the final choice depends on the installation and control circuit. Two switches—one for minimum source level and one for maximum destination level—can provide more dependable pump protection than ultrasonic readings alone.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parts required

  • ESP32 development board.
  • Waterproof ultrasonic sensor for humid or outdoor tanks.
  • Regulated 5 V supply for the sensor, if required by the module.
  • Suitable 3.3 V supply for the ESP32.
  • Voltage divider or logic-level shifter for an echo signal above 3.3 V.
  • Optional I2C OLED display.
  • Optional normally closed float switch or switches.
  • Appropriately isolated relay or contactor interface.
  • Fuse, enclosure, cable glands, strain relief, terminal blocks, and suitable wiring.

ESP32 wiring

For a classic ESP32 DevKit-style board, these are example assignments:

JSN-SR04T VCC  → regulated 5 V
JSN-SR04T GND  → ESP32 GND
JSN-SR04T TRIG → GPIO 5
JSN-SR04T ECHO → GPIO 18 through a voltage divider

The pins are examples, not universal requirements. Protect any echo signal that can exceed the ESP32’s GPIO tolerance. Espressif specifies GPIO voltage tolerance of 3.6 V: ESP32 hardware guidance.

For a nominal 5 V echo, an example divider is:

Sensor ECHO ── 1 kΩ ──┬── ESP32 GPIO
                      │
                     2 kΩ
                      │
                     GND

This produces approximately 3.33 V from a 5 V input. Use a proper level shifter where cable length, noise, speed, or product reliability makes it preferable.

Take care with pin selection. GPIO34–GPIO39 on the original ESP32 are input-only and lack software pull-ups and pull-downs. GPIO6–GPIO11 are normally connected to flash. Strapping pins have boot-time restrictions. These details vary across ESP32 families, so consult the relevant Espressif pin guidance before finalizing the PCB.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a float switch, connect one side to ground and the other to a suitable input configured with INPUT_PULLUP, provided that pin supports the required pull-up. The software must define whether an open or closed switch means “safe.”

Rank #3
Sale
YoLink LoRa Water Level Monitoring Sensor Starter Kit: 1 YoLink Hub & Wireless Battery-Powered Float Switch Alarm, Sump Pump Alarm, AC Condensate Overflow, Tank Level, Toilet Leak Sensor, 105dB Siren
  • A SMART START! Everything you need to start your water level monitoring: one Water Level Monitoring Sensor with float switch, and one YoLink hub. The hub supports 300+ devices from our full product line. Two AAA batteries are included!
  • MANY APPLICATIONS! Sump pump alarm, AC condensate pan overflow alarm, runaway toilet/jammed flapper, internal toilet leak alarm, fish tank, pond, fountain, rainwater drum/tank, cistern, water storage tank high or low level detector
  • SPEND LESS, GET MORE! YoLink smart sensors are not only economical but they are part of a growing family of products compatible with your Water Level Monitoring Sensor. Shut off or turn on water on high or low level detection, turn pumps on/off, activate sirens and lights. Automatically.
  • WIRE LESS! The sensor is wireless and battery-powered, with LoRa-based extreme long-range wireless (up to 2,034 feet open-air!), so you can put your sensor where WiFi and older RF technologies can't go. No cables, conduit, raceway, trenching, or electrician required!
  • EASY DIY INSTALLATION with our innovative pendant-mount style float switch. Simply hang or suspend the float switch into the monitoring tank or container. The float switch's stainless steel washers provide ballast for stability against wave action, and also provide edge/sidewall protection. Tie wraps and tie wrap mount included.

Install Arduino-ESP32 support

  1. Install Arduino IDE.
  2. Open Boards Manager.
  3. Install esp32 by Espressif Systems.
  4. Select the board profile matching the actual hardware.
  5. Select the correct serial port.
  6. Upload a simple serial test before connecting pump hardware.

The current Arduino-ESP32 documentation identifies version 3.3.10, based on ESP-IDF 5.5, but installed versions and supported board profiles change. Verify the current documentation when setting up: Arduino-ESP32 documentation and installation guide.

Basic ultrasonic test sketch

const int TRIG_PIN = 5;
const int ECHO_PIN = 18;

float readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(3);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
  if (duration == 0) return NAN;

  return duration * 0.0343f / 2.0f;
}

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

void loop() {
  float distanceCm = readDistanceCm();

  if (isnan(distanceCm)) {
    Serial.println("Sensor timeout");
  } else {
    Serial.print("Air gap: ");
    Serial.print(distanceCm, 1);
    Serial.println(" cm");
  }

  delay(1000);
}

The formula divides by two because the sound travels to the water and back:

distanceCm = echoTimeMicroseconds × 0.0343 / 2

Filtering and percentage conversion

Never let one raw ultrasonic reading switch a pump. Take several readings, reject impossible values, and use a median or trimmed mean when occasional spikes occur.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const int TRIG_PIN = 5;
const int ECHO_PIN = 18;
const float EMPTY_AIR_GAP_CM = 140.0f;
const float FULL_AIR_GAP_CM  = 20.0f;

float readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(3);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
  if (duration == 0) return NAN;
  return duration * 0.0343f / 2.0f;
}

float readFilteredDistanceCm() {
  const int samples = 7;
  float values[samples];
  int valid = 0;

  for (int i = 0; i < samples; i++) {
    float value = readDistanceCm();
    if (!isnan(value) && value > 2.0f && value < 600.0f) {
      values[valid++] = value;
    }
    delay(70);
  }

  if (valid == 0) return NAN;

  float total = 0.0f;
  for (int i = 0; i < valid; i++) total += values[i];
  return total / valid;
}

float distanceToPercent(float airGapCm) {
  float percentage = 100.0f *
    (EMPTY_AIR_GAP_CM - airGapCm) /
    (EMPTY_AIR_GAP_CM - FULL_AIR_GAP_CM);
  return constrain(percentage, 0.0f, 100.0f);
}

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

void loop() {
  float airGap = readFilteredDistanceCm();

  if (isnan(airGap)) {
    Serial.println("FAULT: no valid ultrasonic reading");
    delay(1000);
    return;
  }

  Serial.print("Air gap: ");
  Serial.print(airGap, 1);
  Serial.print(" cm, level: ");
  Serial.print(distanceToPercent(airGap), 1);
  Serial.println("%");
  delay(1000);
}

EMPTY_AIR_GAP_CM and FULL_AIR_GAP_CM are example values only. They must be replaced with measurements from the installed tank.

Calibrate the tank

  1. Mount the sensor in its final position.
  2. Measure from the sensor’s reference point, not merely from the tank lid.
  3. Record the reading at the desired empty cutoff.
  4. Fill the tank to the desired full cutoff and record the second reading.
  5. Store those readings in the firmware.
  6. Check several intermediate levels against a physical measurement.
  7. Create a lookup table if the required result is volume rather than depth.

Do not use nominal tank height blindly. The tank may have a curved bottom, the sensor may sit above the lid, and the pump may need to stop before the physical top. Keep the transducer away from turbulence and ensure the full-level target remains outside the sensor’s blind zone. A stilling tube can help with a moving or foamy surface.

Automatic pump control

Use hysteresis

Use separate start and stop thresholds so small measurement changes do not cause relay chatter:

Rank #4
CQRobot Contact Photoelectric Liquid Level Sensor for Arduino Raspberry Pi
  • Contact Water/Liquid Level Sensor, This is a photoelectric water liquid level sensor that is operates using optical principles. Open collector output mode, suitable for connecting various circuits and product applications.
  • The sensor has no mechanical parts, requires no additional adjustment, and has high sensitivity, low power consumption, corrosion resistance, high pressure resistance, high temperature resistance and chemical stability.
  • This sensor probe is small in size and has a structure that can be placed up, down, laterally, and diagonally in multiple orientations to detect solution spillage, dryness and horizontal level. Can be used as a reminder and alarm function.
  • The sensor has a DIP switch. The DIP switch controls the output voltage (high level) of the signal terminal (green line). When the DIP switch is dialed to 5V, the high level is 5V. When the DIP switch is dialed At 3V, the high level is 3.3V.
  • Compatible with Arduino motherboard and Raspberry Pi motherboard. for Automatic Irrigation Systems, Aquariums, Plants, in The Garden, in Agriculture etc.
const float PUMP_START_PERCENT = 30.0f;
const float PUMP_STOP_PERCENT  = 85.0f;

Conceptually:

if level < 30%: pump ON
if level > 85%: pump OFF

Add independent interlocks

A robust controller should include:

  • Source-tank float switch to prevent dry running.
  • Independent high-level overflow cutoff.
  • Maximum continuous pump runtime.
  • Minimum off-time between starts.
  • Sensor timeout and plausibility checks.
  • Manual override with a clear safe state.
  • Defined behavior after power loss.
  • Hardware emergency cutoff where consequences of overflow are serious.

A conservative state machine can include FAULT, IDLE, FILLING, FULL, SOURCE_EMPTY, and TIMEOUT. On an invalid reading or an unavailable source, the pump should turn off. Wi-Fi must not be required for local safety.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Relay and mains safety

An ESP32 GPIO cannot drive a pump motor directly.

For a low-voltage DC pump, use a correctly rated MOSFET or relay, a flyback diode for relay coils or inductive DC loads, and wiring sized for the pump current. Confirm that the relay input reliably recognizes 3.3 V.

For an AC pump, use an appropriately rated relay, contactor, or solid-state device. Consider motor starting current, inductive-load ratings, fusing, grounding, enclosure, isolation, creepage, and clearance. Do not put mains terminals on a breadboard. A relay module advertised as “30 A” is not automatically suitable for a motor or household installation.

Keep water and mains wiring physically separated, use cable glands and strain relief, and install the electronics in a suitable enclosure. Have permanent household wiring completed or checked by a qualified electrician.

Wi-Fi monitoring without compromising control

The ESP32 can publish level data through a local web server, MQTT, Home Assistant, a cloud dashboard, or an ESP-NOW link to another ESP32. These are monitoring and convenience features, not safety mechanisms.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When Wi-Fi fails, the controller should continue local measurement and local control if readings remain valid. If the sensor becomes invalid for a defined period, switch the pump off. Reconnect with backoff rather than blocking the control loop.

Best Value
DIYables Rain Sensor for Arduino, ESP32, ESP8266, Raspberry Pi, 5 Pieces
  • Rain Detection: Effectively detects rain, allowing you to monitor weather conditions or automate actions in response to rainfall.
  • Sensitivity Adjustment: Easily adjust sensitivity using the built-in potentiometer to fine-tune the rain detection level.
  • Versatile Power: Compatible with supply voltages ranging from 3.3V to 5V DC, ensuring adaptability to various power sources.
  • Dual Output Format: Offers both digital switch output (0 and 1) for easy integration into digital circuits and analog AO voltage output for more precise measurements and applications.
  • Comprehensive Tutorials: Access detailed tutorials for Arduino, ESP32, ESP8266 and Raspberry Pi, enabling you to quickly implement rain detection solutions with confidence.

If you use an analog sensor on the original ESP32, prefer ADC1 when Wi-Fi is active. ADC2 has limitations during Wi-Fi operation. See Espressif’s hardware design guidance and ADC documentation.

Conductive and analog sensor cautions

Conductive probes should be powered only during measurement where possible. A representative ESP32 example powers the sensor briefly, reads the ADC, then turns it off: conductive water-sensor example.

Raw ADC values are not precision voltage measurements. On the original ESP32, the nominal ADC reference is 1.1 V, but actual reference values can vary approximately from 1.0 to 1.2 V between chips. Use calibration when converting ADC readings to voltage: Espressif ADC calibration. A calibrated percentage map for one tank is different from an accurate, repeatable industrial measurement.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting

No echo, zero, or maximum distance

  • Check sensor power, ground, trigger, and echo wiring.
  • Confirm the software pin assignments.
  • Test against a fixed object at a known distance.
  • Install the required divider or level shifter.
  • Check whether the water surface is inside the blind zone.
  • Confirm the exact sensor revision and timing mode.

Erratic readings

  • Use a median or trimmed-mean filter.
  • Increase the interval between readings.
  • Reduce turbulence and foam with a stilling tube.
  • Move the transducer away from walls and obstructions.
  • Separate sensor and pump wiring.
  • Improve grounding, decoupling, and power regulation.
  • Reject readings outside the physically possible range.

ESP32 resets when the pump starts

Likely causes include voltage sag, relay-coil current, motor EMI, poor grounding, or inadequate isolation. Use appropriately separate supplies where necessary, an isolated switching interface, load-appropriate suppression, and decoupling near the ESP32. Keep high-current motor returns out of the ESP32 ground path.

Analog readings change when Wi-Fi starts

Move the analog input from ADC2 to ADC1 on the original ESP32. Also check attenuation, calibration, sensor supply stability, and the selected board’s pin mapping. ESP32-C3, S3, and other variants do not have identical GPIO and ADC arrangements.

When to choose another sensor

Choose a pressure sensor when foam, vapor, or turbulence makes acoustic measurement unreliable and continuous level information is important. Choose capacitive sensing when the sensor must remain outside the liquid or the liquid is corrosive. Choose multiple float switches when the application needs dependable threshold protection rather than a percentage display. Conductive probes are useful for inexpensive demonstrations but require attention to corrosion, mineral deposits, liquid conductivity, and material suitability.

Practical limitations

  • The ultrasonic system measures distance and derived depth, not volume unless tank geometry is modeled.
  • Low-cost hobby sensors should not be presented as industrial instruments without appropriate testing and certification.
  • Do not claim potable-water suitability without evidence for materials, hygiene, and certification.
  • “Waterproof” depends on the exact probe, module, cable termination, and enclosure installation.
  • Every ESP32 family has different pin, ADC, boot, and peripheral details.
  • Pump protection exists only when the required independent interlocks and failure behavior have actually been implemented.

For a construction or home-automation prototype, the most balanced design is a calibrated waterproof ultrasonic sensor connected through a protected echo input, filtered firmware with timeouts, and a separate float switch for source-empty or overflow protection. Treat Wi-Fi as an optional reporting layer and treat mains switching as an electrical-installation task, not as an extension of the breadboard circuit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Site Office

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.