Contents β 26 sections
Project Overview
A zone-based drip system that waters by crop stage and real evapotranspiration demand, verifies delivery with a flow meter, and catches the burst pipes and blocked emitters that silently waste water or kill crops.
Drip irrigation is the most water-efficient way to water crops β it delivers water slowly to the root zone, minimising evaporation and runoff. But an automated drip system that runs on a fixed schedule wastes much of that advantage: it waters the same amount whether it is a cool damp week or a hot dry one, and it has no idea whether the water it commanded actually reached the plants. This project addresses both β it waters to real demand and it verifies delivery.
The demand side uses evapotranspiration (ET), the combined water loss from soil evaporation and plant transpiration. ET is what a crop actually consumes, and it is driven by weather β temperature, humidity, solar radiation and wind. By estimating ET from local sensors (or a weather feed) and multiplying by a crop coefficient that reflects the crop's stage of growth, the system computes how much water the crop needs, and replaces that. This is how professional irrigation scheduling works, and it typically saves 20β40 % of water over fixed scheduling while improving yield.
The verification side uses a flow meter. This is the feature that separates a real system from a hopeful one: the controller measures the water actually delivered, not just the time the valve was open. From the flow it detects the failures that silently ruin drip systems β a burst pipe or fitting (flow far higher than expected), a blocked emitter or filter (flow far lower), and a valve that failed to open or close. Without flow measurement, a burst main can run for days and a blocked line can starve a crop, both undetected until the damage is done.
The system manages multiple zones independently β different crops, different growth stages, different soil, each with its own schedule and ET-based demand β sequenced so the water supply is not overloaded. It is built for the field: solar-capable, weather-aware, and reporting so you can see water use and catch faults remotely.
What this project does
- Waters multiple zones independently based on evapotranspiration demand and crop stage.
- Measures actual water delivered per zone with a flow meter.
- Detects burst pipes, blocked emitters and valve failures from the flow signal.
- Adjusts watering to real ET demand rather than a fixed schedule.
- Sequences zones so the water supply is not overloaded.
- Respects rain β skips or reduces watering after rainfall.
- Logs water use per zone and alerts on faults.
Real-World Applications
| Setting | How it is used |
|---|---|
| Efficient crop irrigation | ET-based watering with delivery verification β the core precision-irrigation case. |
| Orchards and vineyards | Multiple zones with different demands, where burst detection prevents large losses. |
| Market gardens | Diverse crops at different stages, each zone scheduled to its own demand. |
| Landscape and turf | Water-restriction compliance with logged, demand-based use. |
| Water-scarce regions | Where the 20β40 % saving is not just economic but essential. |
| Research plots | Precise, logged, per-zone water delivery for experiments. |
Deployment contexts where a build of this kind earns its keep.
Features & Capabilities
- ET-based scheduling β waters to real crop demand, saving 20β40 % over fixed schedules.
- Crop-coefficient staging so demand tracks the crop through its growth cycle.
- Flow verification β measures delivered water, the difference between a real and a hopeful system.
- Fault detection: burst (high flow), blockage (low flow), valve failure (no flow).
- Multi-zone sequencing that respects supply capacity.
- Rain skip from a rain sensor or weather feed.
- Per-zone water logging for efficiency tracking and compliance.
- Fail-safe valves that close on power loss, so a fault cannot flood.
Difficulty, Time & Required Skills
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 12β18 hours |
| Indicative build cost | βΉ3,800 β βΉ5,200 |
| Primary discipline | Agriculture |
| Reference platform | ESP32 DevKit V1 (ESP-WROOM-32) |
Skills you should have (or will pick up)
- Arduino C++ with state machines and scheduling
- Flow-meter pulse counting with interrupts
- Valve and pump control
- Evapotranspiration estimation
- Fault detection from sensor signals
Bill of Materials
Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift β treat them as a budgeting guide, not a quotation.
| Component | Key specification | Qty | Approx. cost |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) Wi-Fi transmit bursts peak near 500 mA β size the regulator accordingly. | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18Γ 12-bit ADC, 2Γ 8-bit DAC | 1 | βΉ450 |
| YF-S201 hall-effect water flow sensor Count pulses on a hardware interrupt; the K-factor changes with pipe orientation. | 1β30 L/min, Β±10 %, 450 pulses per litre, Β½β³ BSP thread, β€ 1.75 MPa | 1 | βΉ350 |
| 12 V solenoid valve (Β½β³, normally closed) Continuous energising heats the coil β use latching valves for battery builds. | 0.02β0.8 MPa, 12 V DC, 8 W, brass body | 4 | βΉ2,600 |
| SHT31-D temperature + humidity sensor The built-in heater burns off condensation β essential for outdoor or greenhouse use. | β40 to +125 Β°C Β±0.2 Β°C, 0β100 %RH Β±2 %, 1 Hzβ10 Hz, on-chip heater | 1 | βΉ620 |
| BH1750 digital ambient light sensor Far more linear than an LDR β use it whenever you need real lux, not a relative value. | 1β65535 lx, 16-bit, Β±20 %, spectral response close to the human eye | 1 | βΉ140 |
| 4-channel opto-isolated relay board All four coils energised draw ~280 mA β do not power from the MCU 5 V pin. | 4 Γ SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel | 1 | βΉ280 |
| 0.96β³ SSD1306 OLED display Static images burn in β invert or scroll the screen periodically. | 128 Γ 64 monochrome, 1.3β3.3 V logic, 100 kHzβ400 kHz IΒ²C | 1 | βΉ250 |
| LM2596 adjustable buck converter module Set the output voltage with no load connected before wiring the board. | 4.5β40 V in, 1.25β37 V out, 2 A (3 A peak), ~92 % efficiency | 1 | βΉ90 |
| 12 V 5 A SMPS adapter Fuse the 12 V rail at ~1.5Γ your calculated draw. | 100β240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ 2.1 mm barrel | 1 | βΉ650 |
| Double-sided perfboard 7 Γ 9 cm + headers Solder female headers so the MCU can be swapped without desoldering. | FR-4, 0.1β³ pitch, plated through-holes, 24 Γ 18 grid | 1 | βΉ60 |
| IP65 ABS junction enclosure 158 Γ 90 Γ 60 mm Fit cable glands, not drilled holes, or the IP rating means nothing. | IP65, ABS, β20 to +80 Β°C, transparent lid, wall-mount lugs | 1 | βΉ260 |
| Drip irrigation kit A pressure regulator and filter per zone are essential β drip emitters clog and are pressure-sensitive. | Tubing, emitters, filter, pressure regulator per zone | 1 | βΉ1,200 |
| Rain sensor | Tipping-bucket or simple rain board | 1 | βΉ350 |
| Manifold + fittings | For the multi-zone valve manifold | 1 | βΉ400 |
| MOSFET/relay drivers + flyback diodes | For the solenoid valves | 1 | βΉ80 |
Estimated total: βΉ7,780, excluding tools, shipping and consumables.
Tools and consumables
- Soldering iron (temperature controlled, 350 Β°C) with 0.8 mm 60/40 or lead-free solder
- Digital multimeter β continuity, DC volts and current ranges
- Wire strippers, flush cutters and a small set of precision screwdrivers
- Heat-shrink tubing and a heat gun (or a lighter, carefully)
- A laptop with a USB port and the toolchain listed above
Hardware Specifications
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18Γ 12-bit ADC, 2Γ 8-bit DAC | 3.3 V logic / 5 V USB | UART, SPI, IΒ²C, IΒ²S, CAN, PWM | Datasheet |
| YF-S201 hall-effect water flow sensor | 1β30 L/min, Β±10 %, 450 pulses per litre, Β½β³ BSP thread, β€ 1.75 MPa | 5β18 V | Open-collector pulse | Datasheet |
| 12 V solenoid valve (Β½β³, normally closed) | 0.02β0.8 MPa, 12 V DC, 8 W, brass body | 12 V | Relay / MOSFET + flyback diode | Datasheet |
| SHT31-D temperature + humidity sensor | β40 to +125 Β°C Β±0.2 Β°C, 0β100 %RH Β±2 %, 1 Hzβ10 Hz, on-chip heater | 2.4β5.5 V | IΒ²C (0x44/0x45) | Datasheet |
| BH1750 digital ambient light sensor | 1β65535 lx, 16-bit, Β±20 %, spectral response close to the human eye | 2.4β3.6 V | IΒ²C (0x23/0x5C) | Datasheet |
| 4-channel opto-isolated relay board | 4 Γ SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel | 5 V coil | 4Γ digital | Datasheet |
| 0.96β³ SSD1306 OLED display | 128 Γ 64 monochrome, 1.3β3.3 V logic, 100 kHzβ400 kHz IΒ²C | 3.3β5 V | IΒ²C (0x3C) | Datasheet |
| LM2596 adjustable buck converter module | 4.5β40 V in, 1.25β37 V out, 2 A (3 A peak), ~92 % efficiency | 4.5β40 V | Screw terminals + trimmer | Datasheet |
| 12 V 5 A SMPS adapter | 100β240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ 2.1 mm barrel | 12 V | DC barrel | Datasheet |
| Double-sided perfboard 7 Γ 9 cm + headers | FR-4, 0.1β³ pitch, plated through-holes, 24 Γ 18 grid | β | β | Datasheet |
| IP65 ABS junction enclosure 158 Γ 90 Γ 60 mm | IP65, ABS, β20 to +80 Β°C, transparent lid, wall-mount lugs | β | β | Datasheet |
Consolidated electrical and interface specifications for every active part in the build.
Power Budget & Supply Sizing
Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA β size the regulator accordingly. |
| YF-S201 hall-effect water flow sensor | 5β18 V | 15 | Count pulses on a hardware interrupt; the K-factor changes with pipe orientation. |
| 12 V solenoid valve (Β½β³, normally closed) | 12 V | 2600 | Continuous energising heats the coil β use latching valves for battery builds. |
| SHT31-D temperature + humidity sensor | 2.4β5.5 V | 1.5 | The built-in heater burns off condensation β essential for outdoor or greenhouse use. |
| BH1750 digital ambient light sensor | 2.4β3.6 V | 0.19 | Far more linear than an LDR β use it whenever you need real lux, not a relative value. |
| 4-channel opto-isolated relay board | 5 V coil | 280 | All four coils energised draw ~280 mA β do not power from the MCU 5 V pin. |
| 0.96β³ SSD1306 OLED display | 3.3β5 V | 20 | Static images burn in β invert or scroll the screen periodically. |
| LM2596 adjustable buck converter module | 4.5β40 V | 8 | Set the output voltage with no load connected before wiring the board. |
| 12 V 5 A SMPS adapter | 12 V | 5000 | Fuse the 12 V rail at ~1.5Γ your calculated draw. |
Summed typical draw is 8084.6900000000005 mA. With a 1.5Γ design margin the supply should deliver at least 12200 mA continuously at the stated rail voltage.
Software Requirements & Development Environment
Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.
- Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
- Add
https://espressif.github.io/arduino-esp32/package_esp32_index.jsonunder File β Preferences β Additional Board Manager URLs, then install esp32 from the Boards Manager. - Set the correct port under Tools β Port. On Linux add yourself to the
dialoutgroup:sudo usermod -aG dialout $USERand log out and back in. - Open the Serial Monitor at 115200 baud β every sketch here logs its state there.
- Keep File β Preferences β Show verbose output during: compilation switched on while you are debugging build errors.
Required libraries
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| PubSubClient 2.8 | Lightweight MQTT 3.1.1 client for constrained devices. | Library Manager β "PubSubClient" by Nick O'Leary |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager β "ArduinoJson" by Benoit Blanchon |
| Adafruit BME280 2.2.x | Compensation maths for the Bosch pressure/humidity/temperature sensor. | Library Manager β "Adafruit BME280 Library" |
| Adafruit Unified Sensor 1.1.x | Common sensor event abstraction; a dependency of most Adafruit drivers. | Library Manager β "Adafruit Unified Sensor" |
| BH1750 1.3.0 | Digital lux readings with selectable resolution modes. | Library Manager β "BH1750" by Christopher Laws |
| Adafruit SSD1306 + GFX 2.5.x | Framebuffer and text/graphics primitives for the OLED. | Library Manager β "Adafruit SSD1306" |
| Preferences (NVS) bundled | Wear-levelled key/value storage in ESP32 flash for settings. | Bundled with the ESP32 core |
| NTPClient / configTime bundled | Wall-clock time from an NTP server for timestamping. | Bundled (`configTime()` on ESP32) |
Block Diagram
The block diagram shows the functional decomposition of the system β what senses, what decides, what acts, and where the data ends up.
Circuit Diagram & Wiring
Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| YF-S201 flow meter | Pulse | GPIO 27 | Open-collector pulse, interrupt |
| SHT31 weather | SDA / SCL | GPIO 21 / 22 | IΒ²C, for ET estimate |
| BH1750 solar radiation | SDA / SCL | GPIO 21 / 22 | Shared IΒ²C, for ET |
| Rain sensor | OUT | GPIO 32 | Rain skip |
| Zone 1β4 valves | IN1βIN4 | GPIO 25 26 14 12 | Solenoid valves, fail-closed |
| Master pump/valve | Relay | GPIO 33 | Supply |
| SSD1306 OLED | SDA / SCL | GPIO 21 / 22 | Shared IΒ²C |
Wire one row at a time and tick it off β most "it does not work" reports trace back to a single swapped pair.
Wiring explanation
- The flow meter outputs an open-collector pulse train β one pulse per fixed volume of water. Wire it to an interrupt-capable pin with a pull-up, and count pulses in the ISR. The pulses-per-litre (K-factor) is specified for the meter but changes with orientation and flow rate, so calibrate it.
- The solenoid valves must be normally-closed and fail-closed β losing power closes them. This means a power failure or a crashed controller cannot leave a valve open flooding a zone. Wire and choose valves accordingly.
- Each zone needs a pressure regulator and filter ahead of the drip line. Drip emitters are pressure-sensitive (too much pressure and they blow off or over-deliver) and clog easily (a filter is essential). These are irrigation-plumbing requirements, not electronics.
- Fit flyback diodes across the solenoid coils β they are inductive and will damage the drivers without them.
- Place the flow meter after the master valve but where it sees the flow to all zones (or one per zone for per-zone flow, which is better for fault localisation). Install it in the correct orientation per the arrow.
- For the ET estimate, place the weather sensors representatively β the temperature/humidity sensor shaded and aspirated, the light sensor unshaded. Or use a weather feed instead of local sensors.
System Architecture
Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.
Working Principle
Evapotranspiration is the foundation of demand-based irrigation. It is the total water a crop loses β evaporation from the soil surface plus transpiration through the plant β and it is what the crop must have replaced. ET is driven by weather: it rises with temperature, solar radiation and wind, and falls with humidity. The reference ET (ETβ) is the water use of a standard reference crop under the current weather, computed from those variables. The FAO Penman-Monteith equation is the standard method; a simpler approximation (like Hargreaves, which needs only temperature) is adequate for many field uses. The controller estimates ETβ from its weather sensors.
The crop coefficient (Kc) converts reference ET into the actual crop's water need: ETc = ETβ Γ Kc. Kc reflects the crop and its growth stage β a young seedling with little leaf area transpires little (Kc around 0.3β0.5), a mature crop at full canopy transpires most (Kc up to 1.1β1.2), and a senescing crop declines again. By tracking the crop stage and applying the right Kc, the system waters a seedling less and a mature crop more, matching real demand through the season. This staging is what a fixed schedule cannot do.
The water to apply replaces the crop's consumption since the last watering, accounting for what came from rain. This is why rain skip matters β rain contributes to the crop's water and must be subtracted from the irrigation demand, or the system over-waters. A simple system skips watering after significant rain; a better one measures the rain and subtracts it from the deficit.
The flow verification is the engineering heart of the project, and it is what most drip controllers lack. A flow meter counts pulses proportional to water volume, so the controller knows the actual delivered volume, not just the valve-open time. This enables three critical detections. A burst (a split pipe or blown fitting) shows as flow much higher than expected for the zone β the water is escaping, not reaching the plants, and left running it wastes enormous volumes and can wash out a field. A blockage (a clogged filter or emitters) shows as flow much lower than expected β the crop is being starved. A valve failure shows as no flow when a zone should be watering (valve stuck closed) or flow when none is commanded (valve stuck open). Detecting these promptly is the difference between a minor fix and a ruined crop or a flooded field.
The system is fail-safe by construction. The valves are normally-closed, so any power loss or controller crash closes them β a fault can never leave a zone flooding. On detecting a burst, the controller closes the affected zone and alarms rather than continuing. And a hard maximum runtime per zone bounds the damage from any undetected fault.
Multi-zone sequencing respects the water supply. A drip system's pump or supply main has a finite flow capacity, and running all zones at once may exceed it, dropping the pressure below what the emitters need. The controller waters zones in sequence, each for its computed volume, so the supply is never overloaded and each zone gets the pressure its emitters are designed for.
The maths behind it
Reference ET (Hargreaves approximation)
ET0 = 0.0023 Β· Ra Β· (Tmean + 17.8) Β· sqrt(Tmax β Tmin)
Ra = extraterrestrial radiation (from latitude & day)
Tmean, Tmax, Tmin = daily temperatures (Β°C)
Example: Tmean 26, Tmax 33, Tmin 19, Ra ~40 MJ/mΒ²/day:
ET0 = 0.0023 Β· 40 Β· 43.8 Β· sqrt(14)
= 0.0023 Β· 40 Β· 43.8 Β· 3.74 = 15.1 mm... (Γ0.408 to mm)
β 6.2 mm/day
Crop ET: ETc = ET0 Β· Kc
seedling Kc 0.4 β 2.5 mm/day
mature Kc 1.1 β 6.8 mm/day
Water volume and flow verification
Water to apply (litres) for a zone of area A (mΒ²):
V = ETc (mm) Β· A Β· 1 L/mΒ²/mm β effective_rainfall
Flow meter: pulses per litre = K (calibrate!)
delivered_L = pulse_count / K
Expected flow rate for the zone: Q_expected (L/min)
burst: Q_measured > 1.5 Β· Q_expected
blockage: Q_measured < 0.5 Β· Q_expected
no-flow: Q_measured β 0 when valve commanded open
Stop and alarm on any of these; do not keep watering
into a fault.
Multi-zone sequencing
Supply capacity: Q_supply (L/min)
Each zone needs Q_zone at its design pressure.
If Ξ£ Q_zone > Q_supply, water zones SEQUENTIALLY:
total_time = Ξ£ (V_zone / Q_zone)
A zone gets its full design pressure (emitters uniform)
rather than a shared, sagging pressure. Sequence during
the low-ET early morning to minimise evaporation and
avoid peak supply demand.
Program Flowchart
The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.
Assembly Instructions
Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.
Step-by-Step Implementation Guide
Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.
Complete Source Code
The listing below is complete and compiles as written β there are no elided sections. Read the annotations under each block before you upload it.
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Automated Drip Irrigation β ESP32, ET-based, flow-verified
Waters multiple zones to evapotranspiration demand, VERIFIES
delivery with a flow meter, and detects bursts, blockages and
valve failures. Fail-closed valves.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Adafruit_SHT31.h>
#include <BH1750.h>
#include <Adafruit_SSD1306.h>
#include <Preferences.h>
#include <time.h>
#include <math.h>
#define WIFI_SSID "YOUR_WIFI"
#define WIFI_PASS "YOUR_PASSWORD"
#define MQTT_HOST "192.168.1.50"
#define DEVICE_ID "irrigation-field"
#define PIN_FLOW 27
#define PIN_RAIN 32
#define N_ZONES 4
#define FLOW_K 450.0f // pulses per litre β CALIBRATE
const uint8_t ZONE_PIN[N_ZONES] = { 25, 26, 14, 12 };
struct Zone {
float areaM2; // zone area
float kc; // crop coefficient (updated by stage)
float qExpected; // expected flow L/min at design pressure
float lToday; // water delivered today
} zones[N_ZONES] = {
{ 50, 0.8f, 4.0f, 0 }, { 40, 1.1f, 3.5f, 0 },
{ 30, 0.4f, 2.5f, 0 }, { 60, 0.9f, 5.0f, 0 }
};
Adafruit_SHT31 sht = Adafruit_SHT31();
BH1750 lux;
Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WiFiClient net;
PubSubClient mqtt(net);
Preferences prefs;
volatile uint32_t flowPulses = 0;
float tMin = 99, tMax = -99, tMean = 25;
bool rainedRecently = false;
int lastDay = -1;
void IRAM_ATTR flowISR() { flowPulses++; }
/* ββ ET estimate (simplified Hargreaves) ββββββββββββββββββββββ */
float referenceET() {
// Ra approximated as a constant for the site; a full implementation
// computes it from latitude and day of year.
const float Ra = 40.0f; // MJ/m2/day, site value
float et = 0.0023f * Ra * (tMean + 17.8f) * sqrtf(fmaxf(0.1f, tMax - tMin));
return et * 0.408f; // β mm/day
}
/* ββ watering with flow verification ββββββββββββββββββββββββββ */
enum Result { OK_DONE, BURST, BLOCKAGE, NO_FLOW };
Result waterZone(int z, float litres) {
flowPulses = 0;
digitalWrite(ZONE_PIN[z], LOW); // open (active-low)
uint32_t start = millis(), lastCheck = millis();
uint32_t lastPulses = 0;
const uint32_t MAX_RUN_MS = 30UL * 60UL * 1000UL; // hard runtime cap
while ((flowPulses / FLOW_K) < litres) {
delay(500);
uint32_t now = millis();
if (now - start > MAX_RUN_MS) { // safety timeout
digitalWrite(ZONE_PIN[z], HIGH);
return BLOCKAGE; // too slow to finish
}
if (now - lastCheck >= 5000) { // check flow every 5 s
float qNow = (flowPulses - lastPulses) / FLOW_K / (5.0f / 60.0f); // L/min
lastPulses = flowPulses; lastCheck = now;
if (qNow > 1.5f * zones[z].qExpected) { // BURST
digitalWrite(ZONE_PIN[z], HIGH);
return BURST;
}
if (millis() - start > 15000 && qNow < 0.1f) { // NO FLOW after 15 s
digitalWrite(ZONE_PIN[z], HIGH);
return NO_FLOW; // valve stuck closed
}
if (millis() - start > 15000 && qNow < 0.5f * zones[z].qExpected) {
digitalWrite(ZONE_PIN[z], HIGH);
return BLOCKAGE; // clogged filter/emitters
}
}
}
digitalWrite(ZONE_PIN[z], HIGH); // close
zones[z].lToday += flowPulses / FLOW_K;
return OK_DONE;
}
void alert(int z, Result r) {
const char *msg = r == BURST ? "burst" : r == BLOCKAGE ? "blockage" : "valve-failure";
JsonDocument d; d["zone"] = z; d["fault"] = msg;
char b[96]; size_t n = serializeJson(d, b, sizeof(b));
mqtt.publish("farm/" DEVICE_ID "/fault", (uint8_t *)b, n, true);
Serial.printf("ZONE %d FAULT: %s β stopped and alarmed\n", z, msg);
}
/* ββ daily irrigation cycle βββββββββββββββββββββββββββββββββββ */
void runIrrigation() {
if (rainedRecently) { Serial.println("Rain skip"); return; }
float et0 = referenceET();
Serial.printf("ET0 %.1f mm/day\n", et0);
for (int z = 0; z < N_ZONES; z++) {
float etc = et0 * zones[z].kc; // mm/day for this crop
float litres = etc * zones[z].areaM2; // 1 L per m2 per mm
if (litres < 1) continue;
Serial.printf("Zone %d: %.1f L needed\n", z, litres);
Result r = waterZone(z, litres);
if (r != OK_DONE) alert(z, r);
delay(2000); // pause between zones
}
}
/* ββ setup / loop βββββββββββββββββββββββββββββββββββββββββββββ */
void setup() {
Serial.begin(115200);
pinMode(PIN_FLOW, INPUT_PULLUP);
pinMode(PIN_RAIN, INPUT_PULLUP);
attachInterrupt(PIN_FLOW, flowISR, FALLING);
for (int z = 0; z < N_ZONES; z++) { pinMode(ZONE_PIN[z], OUTPUT); digitalWrite(ZONE_PIN[z], HIGH); }
Wire.begin(21, 22);
sht.begin(0x44);
lux.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
prefs.begin("irrig", false);
WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS);
for (int i = 0; i < 40 && WiFi.status() != WL_CONNECTED; i++) delay(250);
configTime(19800, 0, "pool.ntp.org");
mqtt.setServer(MQTT_HOST, 1883);
Serial.println("Drip irrigation controller running");
}
void loop() {
if (!mqtt.connected() && WiFi.status() == WL_CONNECTED) mqtt.connect(DEVICE_ID);
mqtt.loop();
// Track daily min/max temperature for the ET estimate.
float t = sht.readTemperature();
if (!isnan(t)) { tMean = t; tMin = fminf(tMin, t); tMax = fmaxf(tMax, t); }
rainedRecently = digitalRead(PIN_RAIN) == LOW;
time_t now = time(nullptr); struct tm tmv; localtime_r(&now, &tmv);
// Water once a day in the early morning (low ET, full supply pressure).
static int lastWaterDay = -1;
if (tmv.tm_hour == 5 && tmv.tm_yday != lastWaterDay) {
lastWaterDay = tmv.tm_yday;
runIrrigation();
// Reset daily accumulators and temperature extremes.
for (int z = 0; z < N_ZONES; z++) zones[z].lToday = 0;
tMin = 99; tMax = -99;
}
static uint32_t lastDisplay = 0;
if (millis() - lastDisplay > 2000) {
lastDisplay = millis();
oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE); oled.setTextSize(1);
oled.setCursor(0, 0); oled.printf("ET0 %.1f mm %s", referenceET(), rainedRecently ? "RAIN" : "");
for (int z = 0; z < N_ZONES; z++) {
oled.setCursor(0, 14 + z * 10);
oled.printf("Z%d Kc%.1f %.0fL today", z + 1, zones[z].kc, zones[z].lToday);
}
oled.display();
}
delay(1000);
}
Configuration & Calibration
Configuration steps
- Calibrate the flow meter K-factor (pulses per litre) by running a known volume β the datasheet value is approximate and changes with orientation and flow rate.
- Set each zone's area, crop coefficient and expected flow. Update the crop coefficient as the crop advances through its growth stages β this is what makes the watering track demand.
- Set the ET method's site parameters (latitude for the radiation term) or feed ET from a weather service instead of local sensors.
- Configure the rain-skip threshold and duration to your climate β how much rain, for how long, should reduce or skip watering.
- Set the per-zone burst/blockage thresholds (multiples of expected flow) and the hard runtime cap conservatively β false fault alarms are annoying but a missed burst is expensive.
Calibration procedure
An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.
Calibrate the flow meter
Run water through a zone into a measured container for a fixed pulse count, and compute litres per pulse. Repeat at the flow rate you actually use β the K-factor varies with flow. This calibration sets the accuracy of both the water volume and the fault detection.
Measure each zone's expected flow
Run each zone normally and record its steady flow rate. This is the baseline against which bursts and blockages are detected, so it must reflect the healthy system.
Validate the ET estimate
Compare your ETβ estimate against a reference (a local weather station's ET or an online ET calculator) over a week. The Hargreaves approximation is adequate but check it is in the right range for your site.
Test fault detection
Deliberately induce a fault β disconnect a line (burst-like high flow or no flow), or partly block a filter (low flow) β and confirm the controller detects it, stops, and alarms. Verify the hard runtime cap works.
Network Architecture & Connectivity
Dashboard setup
The key panels are per-zone water use over the season (efficiency tracking, and the evidence for the ET-based savings) and a fault log. A burst alert that reaches your phone in minutes rather than being discovered days later is the single most valuable output.
Overlaying water delivered against estimated ET demand shows whether the system is meeting demand and reveals any systematic over- or under-watering to tune the crop coefficients.
Security considerations
- Authenticate the control link β an open irrigation controller could be made to flood a field or withhold water.
- Keep the fail-safe (valves close on power/comms loss) entirely local; it must not depend on the network.
- Alert on communication loss and on any fault so problems are caught promptly.
Testing Procedure & Expected Output
Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop β the first failing step tells you exactly where to look.
| Test | What you should see |
|---|---|
| Calibrate and verify the flow meter | Measured litres match a known delivered volume within a few percent. |
| Run a zone to a target volume | The valve closes when the measured delivered volume reaches the target, not on a timer. |
| Induce a burst (high flow) | The controller detects flow far above expected, stops the zone, and alarms. |
| Induce a blockage (partly block the filter) | Flow far below expected is detected as a blockage; the zone stops and alarms. |
| Prevent a valve from opening | No flow when the valve is commanded open is detected as a valve failure. |
| Cut power mid-watering | The valve closes (fail-closed) β no flooding. |
| Trigger the rain sensor | Watering is skipped or reduced for that cycle. |
| Change a crop coefficient | The computed water volume for that zone changes proportionally, demonstrating demand-based scheduling. |
Bench-test checklist. If a row fails, stop and fix it before moving on.
Expected output
With everything wired and the firmware uploaded, the Serial Monitor at 115200 baud should look similar to the trace below. Values will differ; the shape of the output should not.
Troubleshooting: Common Errors & Fixes
Performance Optimisation
- Count flow pulses in an interrupt β at high flow the pulse rate is too fast to poll reliably, and missed pulses under-report delivered water.
- Check for faults on a few-second cadence during watering, after an initial settle period so the valve-opening ramp is not mistaken for a fault.
- Water once a day to accumulated demand rather than in many small pulses β fewer valve cycles, less evaporation, and full supply pressure.
- Replace every
delay()with amillis()comparison β blocking delays are the single most common cause of dropped readings. - Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
- Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
- Use
uint8_t/uint16_twhere the range allows; on an 8-bit AVR a 32-bit add costs four times as much. - Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
- Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
- For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 Β΅A asleep, which is the difference between days and months of runtime.
- Profile before optimising β print
micros()deltas around each stage and fix the slowest one first.
Safety Precautions
- Valves must be fail-closed so a power loss or crash cannot leave a zone flooding. This is a design requirement, not an option.
- A hard maximum runtime per zone bounds the damage from any undetected fault β always include it.
- A burst left running wastes enormous water and can erode or flood a field; prompt detection and shutoff is the core safety function.
- Apply mains-safety practices for any mains-powered pump, and keep electronics sealed against water in a wet field environment.
- Do not over-irrigate β beyond wasting water, it leaches nutrients into groundwater and can waterlog and damage crops.
- Mains voltage kills. Anything on the load side of the relay is at 230 V. Do not work on a powered circuit, and never leave exposed mains wiring on a bench where someone could touch it.
- Keep at least 6 mm of creepage between the mains and low-voltage sides of any board you make, and never route mains tracks under the microcontroller.
- Have a qualified electrician do the final installation into a consumer unit or wall fitting. In most jurisdictions this is a legal requirement, not a suggestion.
- Fit an RCD/RCBO upstream and fuse the load appropriately for its rating.
- Moving parts pinch. Keep fingers, cables and hair out of gear trains and wheels, and always test motion with the drivetrain unloaded and the robot on blocks first.
- Motors are inductive β always fit a flyback diode across a DC coil, or use a driver that already has one, or the back-EMF spike will destroy your GPIO.
- Water and electronics: mount all boards above the maximum possible water line, use drip loops on every cable, and pressure-test plumbing before wiring anything up.
- Wear eye protection when soldering or cutting, and solder in a ventilated space β rosin flux fumes are a respiratory irritant.
- Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
- Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.
Maintenance
- Re-check every screw terminal and header after the first week β thermal cycling loosens connections that felt tight on day one.
- Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
- Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware β not only in flash.
- Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.
Future Improvements & Upgrades
A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.
- Add per-zone flow meters for precise fault localisation β knowing which zone burst, not just that flow is wrong.
- Add soil-moisture feedback (the soil-moisture project) to close the loop β ET estimates demand, soil moisture confirms the root zone actually received it.
- Add weather-forecast integration to skip watering ahead of forecast rain and pre-water ahead of a heat wave.
- Add fertigation β injecting nutrients into the irrigation water, dosed from the soil-NPK node.
- Add a full Penman-Monteith ET with wind and radiation for more accurate demand than the temperature-only approximation.
- Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
- Add over-the-air firmware updates so you never have to physically reach a deployed node again.
- Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
- Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
- Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
- Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.
Frequently Asked Questions
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- FAO Irrigation and Drainage Paper 56 β Crop evapotranspirationFAO
- Hargreaves & Samani, "Reference crop evapotranspiration from temperature"Applied Engineering in Agriculture, 1985
- YF-S201 water flow sensor β datasheet and K-factorHobbytronics
- Netafim, "Drip Irrigation Design and Management"Netafim
- Allen et al., "Crop coefficients and Kc values by crop and stage"FAO
- USDA NRCS β Irrigation Water ManagementUSDA NRCS