ESP32 Water Monitoring: Custom IoT for Leak Detection and Usage Analytics
Building a comprehensive water monitoring system with ESP32 microcontrollers, induction pulse counters, custom 3D printed mounts, and Grafana visualization—detecting leaks before they become disasters.
ESP32 Water Monitoring: Custom IoT for Leak Detection and Usage Analytics
A property manager came to us after a hidden leak in an irrigation system cost them thousands in water bills before it was discovered. They wanted real-time monitoring of city water meters, tank levels, and pump operations with automated alerting for anomalous usage patterns.
We built a custom IoT monitoring system using ESP32 microcontrollers, induction sensors, and the TIG stack (Telegraf, InfluxDB, Grafana). The system provides live usage dashboards, automated leak detection, and historical trend analysis—all for a fraction of commercial monitoring solutions.
The Challenge: Monitoring Without Modification
The key constraint: we couldn't modify or replace existing meters and equipment. The city water meter, pump systems, and valves were all already installed and operational. Our monitoring solution needed to be non-intrusive.
This ruled out inline flow meters or meter replacements. We needed to read existing equipment without interfering with operation.
Induction Pulse Counting: Reading Mechanical Meters
Most water meters have a rotating dial or gear that spins proportional to water flow. Many include a small magnet embedded in the dial for exactly this purpose—allowing external pulse counting without breaking the seal.
The Sensor: TCRT5000 vs. Inductive Proximity Sensors
We tested two approaches:
TCRT5000 (Optical Reflective Sensor)
- Pros: Cheap ($0.50), low power, digital output
- Cons: Affected by ambient light, requires clean meter face, shorter range
LJ12A3-4-Z/BX Inductive Proximity Sensor
- Pros: Detects metal directly, immune to dirt/moisture, 4mm sensing distance
- Cons: Higher power draw (requires 12V), more expensive ($3-5)
We went with inductive sensors because water meters are often in pits, enclosures, or locations where dirt and moisture would interfere with optical sensing. The proximity sensor detects the magnet/metal gear directly through meter glass.
Pulse Calibration
Each pulse represents a specific volume of water. For the city meter we were monitoring:
1 pulse = 10 liters
This is typically marked on the meter face or available from the manufacturer. Calibration process:
- Record initial pulse count
- Fill a known volume container (100L test bucket)
- Verify pulse count increased by expected amount (10 pulses)
- Adjust scaling factor if needed
ESP32: The Microcontroller Heart
The ESP32-WROOM-32 was chosen for several reasons:
- WiFi connectivity: Push data to InfluxDB over local network
- Low power modes: Deep sleep between readings for battery operation
- Multiple GPIO pins: Monitor multiple sensors per device
- Abundant resources: 520KB SRAM, 4MB flash, dual-core 240MHz CPU
Interrupt-Driven Pulse Counting
Water flow is sporadic. The ESP32 uses hardware interrupts triggered by sensor state changes—capturing every pulse regardless of when it occurs, no polling loop required. The interrupt handler increments a counter each time the induction sensor detects the magnet passing by.
Deep Sleep and Battery Operation
For remote sensors without mains power, battery operation is achieved using ESP32's deep sleep mode:
- Wake every 5 minutes, connect to WiFi, transmit data
- Return to deep sleep immediately after
- Active power draw (WiFi TX): ~160mA
- Deep sleep: ~10μA
- Average over 5-minute cycle: ~0.5mA
An 18650 Li-ion cell (3000mAh) provides 6+ months of operation.
Custom 3D Printed Mounting System
Commercial sensor mounts don't exist for every meter type. We designed custom 3D printed brackets that:
- Clamp to meter housing without tools or modification
- Position sensor at optimal distance (2-3mm from sensing point)
- Protect sensor from weather (outdoor installations)
- Allow adjustment for fine-tuning sensor alignment
Mounting system was modeled in Fusion 360, printed in PETG (better outdoor UV and temperature resistance than PLA), and includes cable strain relief.
Tank Level Monitoring: Ultrasonic Distance Sensors
For water storage tanks, we added ultrasonic distance sensors (HC-SR04) mounted to tank lids. The sensors measure distance from lid to water surface, then calculate volume based on tank dimensions and cross-sectional area.
Why ultrasonic instead of pressure sensors?
- Non-contact (no submerged components to fail)
- No calibration drift from sensor fouling
- Works with any tank shape (just adjust volume calculation)
Pump Automation: Current Sensing and Relay Control
Monitoring pump operation required detecting when pumps were running and enabling remote control:
Current Transformer (CT) Sensors
We clamped CT sensors around pump power wires to detect current draw. When current exceeds 500mA threshold, the pump is considered running. This provides non-intrusive pump state monitoring without modifying pump circuits.
Relay Control via ESP32
For automated control, we added solid-state relays (SSRs) in series with pump control circuits:
- Manual override maintained: Physical switches still functional
- Remote control enabled: Turn pumps on/off via MQTT or HTTP API
- Safety interlocks: Tank level checks prevent dry-running
- Automated scheduling: Run pumps during off-peak power times
Data Pipeline: TIG Stack Implementation
The monitoring system needed centralized data collection, storage, and visualization.
Telegraf: Data Collection
Telegraf agent collects metrics from multiple sources—ESP32 devices publish to MQTT topics or expose HTTP endpoints. Telegraf normalizes and forwards to InfluxDB.
InfluxDB: Time-Series Database
InfluxDB stores the metrics with time-series optimizations. Retention policies automatically downsample old data:
- Raw data: 30 days
- 5-minute aggregates: 1 year
- 1-hour aggregates: 5 years
Grafana: Visualization and Alerting
Grafana dashboards provide real-time visibility:
Main Dashboard Features:
- Current flow rate (L/min) with 24-hour trend
- Tank levels with fill/empty projections
- Pump runtime hours and cycle counts
- Daily/weekly/monthly usage comparison
- Cost estimation (volume × water rate)
Anomaly Detection: Leak Alerting
The most valuable feature: automated leak detection before damage occurs.
Statistical Baseline
The system learns normal usage patterns using 30 days of historical data, establishing hourly baseline consumption with standard deviation.
Anomaly Triggers
Alerts fire when usage exceeds expected patterns:
- Flow > baseline + 3 standard deviations for 15+ minutes → Potential leak detected
- Flow > 0 between 2AM-5AM for 30+ minutes → Unexpected nighttime usage (likely leak or running toilet)
- Tank level change > expected pump fill volume → Tank leak or overflow
Alerts push via:
- Email notifications
- SMS (via Twilio integration)
- Push notifications (via Pushover)
- Telegram bot messages
False Positive Reduction
Initial deployment had too many false alerts. We added:
- Grace periods: Ignore short spikes (sprinkler startup, etc.)
- Day-of-week patterns: Weekend usage differs from weekdays
- Seasonal adjustment: Summer irrigation vs. winter baseline
- Manual acknowledgment: Mark expected high-usage events
This reduced false positives by 90% while maintaining sensitivity to real leaks.
Real-World Performance
After 12 months of operation across multiple properties:
Leak Detection Success
- 3 major leaks caught within hours (vs. weeks/months without monitoring)
- $12,000+ in water bill savings from early leak detection
- 1 tank overflow prevented (level alert triggered before spillage)
System Reliability
- 99.2% uptime across all sensors
- 2 sensor failures in first year (both outdoor mount weathering issues—solved with better sealing)
- Zero false leak alerts after tuning period
Operational Benefits
- Automated pump scheduling reduced power costs by 20% (running during off-peak)
- Historical data enabled water conservation efforts (identified wasteful usage patterns)
- Tank level monitoring eliminated manual checks (saving labor hours)
Deployment Costs
Total hardware cost per monitoring point:
- ESP32 dev board: $6
- Inductive sensor: $4
- Power supply (if mains): $5
- 3D printed mount: $2 (material cost)
- Enclosure (weatherproof): $8
Total: ~$25 per sensor
Compare to commercial IoT water monitors ($200-500 per unit) with monthly subscription fees ($10-30/month). Our solution paid for itself in months.
Lessons Learned
Sensor Placement Matters
Initial installations had sensors too far from detection points. The inductive sensors need to be within 2-3mm of the target. Our 3D printed mounts include slotted holes for easy position adjustment without reprinting.
WiFi Range Issues
Water meters are often in pits or metal enclosures. WiFi signal was weak or nonexistent. Solutions:
- External antenna on ESP32 (RP-SMA connector variant)
- WiFi mesh network expansion (cheap access points)
- Fallback to 433MHz radio (RFM69) for truly remote sensors
Power Supply Decisions
Battery vs. mains power trade-offs:
Battery-powered worked well for meters with infrequent readings (city water, tank levels)
Mains-powered necessary for pumps (high-frequency monitoring, relay control requires continuous power)
Hybrid approach: Battery for sensors, mains for control nodes.
Expansion Possibilities
The system architecture supports additional sensors:
- Pressure monitoring: Detect pump failures or line breaks
- Water quality sensors: TDS/pH monitoring for tanks
- Valve position feedback: Confirm automated valve operations
- Rain gauge integration: Correlate usage with weather data
All integrate into the same data pipeline and Grafana dashboards.
Need custom IoT monitoring for water, energy, or environmental systems? We design and deploy sensor networks tailored to your infrastructure. Contact us to discuss your monitoring requirements.