Recommended Free Tools
An ESP32 water-level controller can measure tank height with an HC-SR04 ultrasonic sensor, publish readings over MQTT, and operate fill or drain equipment through relays. It is an excellent educational prototype and simulation project—but not, without substantial additional engineering, an industrial or unattended mains-voltage control system.
The most important corrections are to protect the ESP32 from the sensor’s 5 V Echo signal, use calibrated tank measurements, add genuine hysteresis rather than comparing directly with the target, and design a defined safe response to sensor, network, power, and actuator failures.
As an Amazon Associate I earn from qualifying purchases.
What the system does
The project, published by The Embedded Things on Hackster.io on September 19, 2025, uses an ESP32, HC-SR04 ultrasonic sensor, MQTT, relays, and a PyQt5/PyQtGraph desktop dashboard. The sensor measures the distance from the tank roof to the water surface. Firmware converts that distance into an estimated level percentage, while MQTT carries telemetry, commands, status, and activation messages.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchThe resulting path is:
Water surface distance → calibrated level percentage → MQTT telemetry
↓
Dashboard or ESP32 logic
↓
Fill/drain command
↓
Relay → valve or pump
These are separate capabilities:
- Monitoring: reporting the estimated level.
- Remote control: accepting fill, drain, or stop commands over MQTT.
- Automatic control: selecting an actuator based on a target or threshold.
- Safety control: preventing conflicting outputs and limiting the consequences of failures.
The original project demonstrates the first three. Its wiring and control logic should be strengthened before it is connected to real pumps, valves, or construction-site water equipment.
#1 Best Overall
- 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.
- KNOW NOW! This is a smart device with a full-featured app. Beware of products that require you be in earshot of the alarm. Types of notifications available to you include: app push notifications, email, SMS, siren or lighting activation, SpeakerHub sound or spoken messages. Each account receives 5 SMS per month per device, plus 5, free. YoLink Siren, Switch, Plug, Relay or SpeakerHub purchased separately.
View the original Hackster project.
Recommended architecture
HC-SR04
│
├── Trigger → ESP32 GPIO 22
└── Echo → voltage divider/level shifter → ESP32 GPIO 23
│
▼
ESP32 firmware
│
Wi-Fi / MQTT connection
┌─────────────────┴─────────────────┐
▼ ▼
MQTT broker Fill/drain relays
│ │
▼ ▼
PyQt5 dashboard Valves or pump contactors
There are two ways to place the automatic decision.
Dashboard-mediated control
- The ESP32 publishes the measured level.
- The desktop dashboard compares it with the target.
- The dashboard publishes a fill, drain, or stop command.
- The ESP32 applies the command.
This is close to the architecture described in the project and is convenient for learning. However, a crashed computer, lost Wi-Fi connection, unavailable broker, or closed dashboard can interrupt control or leave an actuator in its last state unless the ESP32 has its own timeout and safe-state logic.
Local ESP32 control
A stronger arrangement is for the ESP32 to measure the tank and apply local thresholds. MQTT then handles telemetry, configuration, manual override, and alarms. Local control avoids making a desktop application part of the safety chain and usually provides more predictable response.
Parts and safety additions
The core bill of materials is:
- ESP32 development board.
- HC-SR04 ultrasonic sensor.
- Two-channel relay arrangement or two relay modules.
- Fill and drain valves, a pump, or contactors controlling them.
- Suitable 5 V and 3.3 V power supplies.
- MQTT broker.
- Computer running the dashboard.
- Optional Wokwi simulation.
Add the following for a responsible prototype:
- Voltage divider or level shifter for the HC-SR04 Echo line.
- Independent high-high and low-low float switches.
- Fuses or circuit breakers.
- Emergency stop or local override.
- Pump dry-run protection.
- Check valve where backflow or siphoning is possible.
- Waterproof enclosure and cable glands.
- Motor-rated contactor for loads exceeding a relay board’s rating.
- Surge suppression and motor-noise protection.
- Hardware interlock or auxiliary contacts to prevent simultaneous fill and drain.
Safe wiring
The project assigns GPIO 22 to the ultrasonic trigger, GPIO 23 to Echo, GPIO 17 to the fill relay, and GPIO 16 to the drain relay. That mapping is usable as a starting point, but the Echo wire must not be connected directly to an ESP32 GPIO when the sensor is powered at 5 V.
The HC-SR04 uses a 5 V supply, while ESP32 GPIOs are 3.3 V-class inputs. Espressif-related guidance recommends a voltage divider or level shifter for Echo. A practical divider is:
HC-SR04 Echo ── 1 kΩ ──┬── ESP32 GPIO 23
│
2 kΩ
│
GND
This produces approximately 3.33 V from a nominal 5 V Echo signal. Verify the selected resistor values, wiring, and input limits for the exact board being used.
| Function | Pin | Recommended treatment |
|---|---|---|
| HC-SR04 VCC | 5 V | Use a regulated supply |
| HC-SR04 GND | GND | Share logic ground with the ESP32 |
| HC-SR04 TRIG | GPIO 22 | ESP32 output |
| HC-SR04 ECHO | GPIO 23 | Use a divider or level shifter |
| Fill relay input | GPIO 17 | Confirm active polarity |
| Drain relay input | GPIO 16 | Confirm active polarity |
References: Wokwi’s HC-SR04 reference, Espressif-related HC-SR04 guidance, and the ESP32 datasheet.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Keep low-voltage electronics physically separated from mains wiring. A hobby relay module should not directly switch a large AC pump unless its contacts, isolation, enclosure, fusing, suppression, and installation are correctly engineered. Mains work should be designed and inspected by a qualified professional.
Rank #2
- Breakthrough 1804 ft Connectivity: Engineered with advanced Sub-1G long-range wireless tech, our leak detector maintains robust signals over unprecedented distances—reaching up to 1804 feet even through 5 dense walls. Secure every critical space in expansive properties, from deep basements to detached garages and distant outbuildings.
- Multiple Reminder Methods: Our water leak sensor supports multiple remote alarm. It can instantly send SMS, APP, and Email notifications to your phone (no matter how many times the SMS is used, it's free). Also, the water leak sensor flashes red and sounds a 105 dB alarm. Perfect for the basement, kitchen, or vacation home!
- Feature-Rich App: Receive instant push notifications. Use the “Find Device” feature to quickly trigger audible beeps to retrieve misplaced sensors. Add multiple email addresses through the APP, and your family and friends can also receive reminders when there is a water leak at home.
- Industry Leading IP67 Waterproof: Its IP67 waterproof rating ensures durability against spills, humidity, and accidental submersion.It can be used multiple times after wiping dry.
- Four-level volume adjustment: Customize your own alarm to fit your life! Use the app to adjust the volume in 4 levels, with a maximum alarm volume of 105 decibels. Whether it's day or night, whether it's in the bedroom or the basement, you can find the right volume.
Level calculation and calibration
The simple example maps 400 cm to empty and 0 cm to full:
int distance = duration * 0.034 / 2;
int waterLevelPercent = constrain(
100 - (distance * 100 / 400),
0,
100
);
That formula is only a rough demonstration. It assumes the sensor is directly above the water, the tank is linear, the full distance is zero, and the usable range is exactly 400 cm. Real installations need measured endpoints:
level_percent =
100 × (empty_distance - measured_distance)
/ (empty_distance - full_distance)
Then constrain the result to 0–100% and reject readings outside the calibrated operating range. The HC-SR04 documentation gives an approximate conversion of distance_cm = echo_duration_microseconds / 58 and a nominal 2–400 cm range in Wokwi. See the Wokwi reference.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →This percentage represents liquid height, not automatically liquid volume. A vertical tank with a constant cross-section is close to linear. A horizontal cylinder, cone, or irregular reservoir needs a geometry-specific formula or calibration table.
Robust ESP32 measurement
The commonly shown call below is unsafe for a controller because it has no timeout:
long duration = pulseIn(echoPin, HIGH);
If Echo never arrives, the firmware can wait indefinitely. Use a timeout and distinguish a sensor fault from a genuine empty or full reading:
constexpr unsigned long ECHO_TIMEOUT_US = 30000;
long duration = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
if (duration == 0) {
publishSensorFault("echo_timeout");
return;
}
float distanceCm = duration / 58.0f;
if (distanceCm < MIN_VALID_CM || distanceCm > MAX_VALID_CM) {
publishSensorFault("distance_out_of_range");
return;
}
For a physical tank, take multiple readings and use a median or trimmed mean. Reject sudden impossible jumps, allow for water movement, and avoid treating stale data as current. Ultrasonic sensors can be affected by foam, bubbles, turbulence, condensation, narrow tanks, angled surfaces, floating objects, temperature, and corrosive environments.
Relay interlocking and startup
The intended actuator functions are:
void Fill() {
digitalWrite(relayIn, HIGH);
digitalWrite(relayOut, LOW);
}
void Drain() {
digitalWrite(relayIn, LOW);
digitalWrite(relayOut, HIGH);
}
void FillDrain_OFF() {
digitalWrite(relayIn, LOW);
digitalWrite(relayOut, LOW);
}
This is a software interlock only, and it assumes an active-high relay board. Define polarity explicitly:
Rank #3
- ALERTS AND NOTIFICATIONS: 2 notification points for high and low levels to email and SMS, share your device with your water level company
- WEATHER RESISTANT AND EXTREME TEMPERATURE DESIGN: Works anywhere you need it to with -40 degrees to 85 degrees Celsius operating range
- POWERED FOR YEARS WITH 4AA BATTERIES: The PTLevel is a low-maintenance device providing you reliable liquid level alerts and history year-round
- LONG DISTANCE WIRELESS RANGE: Up to 1km (0.62miles) can be achieved for reliable connectivity
- HISTORY AND GRAPHS: 1 month liquid level history to track your usage and delivery patterns
constexpr bool RELAY_ON = HIGH;
constexpr bool RELAY_OFF = LOW;
pinMode(FILL_RELAY, OUTPUT);
pinMode(DRAIN_RELAY, OUTPUT);
digitalWrite(FILL_RELAY, RELAY_OFF);
digitalWrite(DRAIN_RELAY, RELAY_OFF);
For active-low modules, invert the definitions. Initialize both outputs to OFF before connecting Wi-Fi or MQTT. Add a maximum continuous runtime, a minimum off-time to reduce relay cycling, actuator feedback where possible, and independent float switches. A software interlock is not equivalent to a hardware interlock or certified electrical isolation.
Use real hysteresis
The comparison if target > current: fill() and elif target < current: drain() is not true hysteresis. Sensor noise and surface movement can repeatedly change the decision around the target, causing chatter and relay wear.
A deadband controller separates the fill and drain thresholds:
Free tools Windows power users keep installed
One-click scans. No signup required.
if current <= target - deadband:
command = "FILL_ON DRAIN_OFF"
elif current >= target + deadband:
command = "FILL_OFF DRAIN_ON"
else:
command = "FILL_DRAIN_OFF"
For example, with a target of 60% and a five-point deadband:
- At or below 55%: fill.
- At or above 65%: drain.
- Between 55% and 65%: stop.
Separate low and high thresholds may be easier to reason about:
- Below 35%: fill.
- Above 65%: drain.
- Between those limits: stop.
The project describes a 500 ms control update interval. That may be unnecessarily fast for a slow tank and can increase command traffic and relay transitions. Measure the tank’s response and select an interval appropriate to the actuator and process.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.MQTT topic and message design
The original topic arrangement uses arduino/sensor for telemetry, arduino/sensor_Control for commands, mqtt/request for requests, and mqtt/response for responses. Example payloads include Water Level: 45, FILL_ON DRAIN_OFF, FILL_OFF DRAIN_ON, and FILL_DRAIN_OFF.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsThose strings are easy to demonstrate, but structured messages are easier to validate and extend:
Rank #4
- Breakthrough 1804 ft Connectivity: Engineered with advanced Sub-1G long-range wireless tech, our leak detector maintains robust signals over unprecedented distances—reaching up to 1804 feet even through 5 dense walls. Secure every critical space in expansive properties, from deep basements to detached garages and distant outbuildings.
- Multiple Reminder Methods: Our water leak sensor supports multiple remote alarm. It can instantly send SMS, APP, and Email notifications to your phone (no matter how many times the SMS is used, it's free). Also, the water leak sensor flashes red and sounds a 105 dB alarm. Perfect for the basement, kitchen, or vacation home!
- Feature-Rich App: Receive instant push notifications. Use the “Find Device” feature to quickly trigger audible beeps to retrieve misplaced sensors. Add multiple email addresses through the APP, and your family and friends can also receive reminders when there is a water leak at home.
- Industry Leading IP67 Waterproof: Its IP67 waterproof rating ensures durability against spills, humidity, and accidental submersion.It can be used multiple times after wiping dry.
- Four-level volume adjustment: Customize your own alarm to fit your life! Use the app to adjust the volume in 4 levels, with a maximum alarm volume of 105 decibels. Whether it's day or night, whether it's in the bedroom or the basement, you can find the right volume.
{
"level_percent": 45.2,
"distance_cm": 219.1,
"mode": "auto",
"actuator": "fill",
"sensor_ok": true,
"timestamp": "2026-08-18T12:00:00Z"
}
A scalable topic hierarchy could be:
tank/01/telemetry
tank/01/status
tank/01/cmd/actuator
tank/01/cmd/mode
tank/01/config
tank/01/alarm
Use a unique client ID per ESP32, authenticate clients, and use TLS outside a trusted laboratory network. Add a Last Will message, command acknowledgments, command expiry, and a defined broker-loss policy. Retained messages are useful for selected state and configuration, but an old retained “fill” command must never restart a pump unexpectedly.
Espressif’s MQTT component supports MQTT 3.1.1 and 5.0, authentication, TLS, keep-alive, will messages, QoS, and WebSocket transports.
Dashboard design
The described PyQt5/PyQtGraph dashboard includes MQTT status, current percentage, automatic/manual modes, manual fill and drain controls, a target slider, a history graph, logs, and thread-safe signal/slot updates.
A field-useful dashboard should also show:
- Raw distance and calibrated level.
- Sensor quality and last valid reading.
- Current command and actual actuator feedback.
- Last message time and MQTT connection state.
- Device uptime and firmware version.
- Automatic, manual, disabled, and fault states.
- High-high and low-low alarms.
- Pump runtime and relay transition count.
- Last fault and the action required to clear it.
Manual controls should require confirmation and clearly display the safe state. The dashboard should not imply that a command was completed merely because the broker accepted a message; “command accepted” and “valve physically confirmed” are different states.
Testing in Wokwi
Wokwi supports ESP32 variants, HC-SR04, and relay modules. Its HC-SR04 model includes an interactive distance control, allowing you to change the simulated measurement while observing firmware behavior. This is useful for checking pin assignments, MQTT flow, relay interlocking, calibration math, and dashboard updates.
- Build the ESP32, sensor, and relay circuit in Wokwi.
- Confirm whether the simulated relay inputs are active-high or active-low.
- Move the simulated distance through empty, full, and invalid ranges.
- Check that a timeout produces a sensor fault rather than an actuator command.
- Verify that fill and drain cannot be active together.
- Test the deadband at both threshold boundaries.
- Test MQTT disconnection and ESP32 restart behavior.
Simulation cannot validate pump starting current, relay contact wear, electrical noise, splashing, foam, condensation, plumbing dynamics, mains safety, actuator feedback, or long-term reliability.
Minimum commissioning checklist
- Simulate the complete logic before purchasing hardware.
- Protect the HC-SR04 Echo line with a divider or level shifter.
- Confirm relay polarity and initialize both outputs OFF.
- Test telemetry with pumps and valves disconnected.
- Test commands with LEDs or safe low-voltage loads.
- Add calibrated endpoints and genuine deadband control.
- Add timeout, invalid-reading handling, and maximum actuator runtime.
- Test Wi-Fi loss, broker failure, dashboard crash, sensor disconnection, reboot, and brownout.
- Test high-high and low-low independent limits.
- Only then connect correctly rated valves, pumps, or contactors.
- Keep mains work outside the low-voltage prototype unless designed and inspected by a qualified professional.
Alternatives and upgrades
| Option | Strength | Limitation |
|---|---|---|
| HC-SR04 | Low-cost, simple, Wokwi-supported prototype sensor | Exposed electronics; sensitive to foam, turbulence, and condensation |
| Waterproof ultrasonic sensor | Better for splash-prone installations | Still affected by acoustics, foam, and condensation |
| Pressure transducer | Useful for closed or turbulent tanks | Requires calibration, liquid compatibility, and drift management |
| Float switches | Simple independent safety limits | Provide discrete thresholds rather than continuous level |
| Capacitive or conductive probes | Can suit particular liquids and tank shapes | Fouling, corrosion, conductivity, and geometry matter |
| PLC or industrial controller | Stronger diagnostics, maintenance, and safety options | Higher cost and engineering effort |
For a small educational installation, the ESP32 design is a useful way to learn sensing, MQTT, and actuator control. For an unattended construction, commercial, or industrial water system, use a properly engineered control panel with rated switching equipment, independent protective limits, documented failure behavior, and appropriate professional review.
Quick Recap
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.

