Siddhant Kumar
Project 029 Β· Agriculture

Automated Drip Irrigation.

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.

Intermediate 12–18 hours 39 min read IrrigationSoilPump
Jump to source Bill of materials
Automated Drip Irrigation β€” reference build illustration MCU VCC Β· GND Β· SIG Β· NC
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
β‚Ή3,800 – β‚Ή5,200
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Agriculture
Last updated
28 July 2026
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.

A field irrigation system watering crops
A field irrigation system. Drip delivers water efficiently to the root zone; ET-based scheduling and flow verification make an automated system genuinely efficient. Photograph sourced from Wikimedia Commons β€” Irrigation system.jpg. Reused under the licence stated on that page; please check it before republishing.

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

SettingHow it is used
Efficient crop irrigationET-based watering with delivery verification β€” the core precision-irrigation case.
Orchards and vineyardsMultiple zones with different demands, where burst detection prevents large losses.
Market gardensDiverse crops at different stages, each zone scheduled to its own demand.
Landscape and turfWater-restriction compliance with logged, demand-based use.
Water-scarce regionsWhere the 20–40 % saving is not just economic but essential.
Research plotsPrecise, 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

AttributeValue
Difficulty levelIntermediate
Estimated completion time12–18 hours
Indicative build costβ‚Ή3,800 – β‚Ή5,200
Primary disciplineAgriculture
Reference platformESP32 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.

ComponentKey specificationQtyApprox. 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 DAC1β‚Ή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 MPa1β‚Ή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 body4β‚Ή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 heater1β‚Ή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 eye1β‚Ή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 channel1β‚Ή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Β²C1β‚Ή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 % efficiency1β‚Ή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 barrel1β‚Ή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 grid1β‚Ή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 lugs1β‚Ή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 zone1β‚Ή1,200
Rain sensorTipping-bucket or simple rain board1β‚Ή350
Manifold + fittingsFor the multi-zone valve manifold1β‚Ή400
MOSFET/relay drivers + flyback diodesFor the solenoid valves1β‚Ή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

PartSpecificationSupplyInterfaceReference
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 DAC3.3 V logic / 5 V USBUART, SPI, IΒ²C, IΒ²S, CAN, PWMDatasheet
YF-S201 hall-effect water flow sensor1–30 L/min, Β±10 %, 450 pulses per litre, Β½β€³ BSP thread, ≀ 1.75 MPa5–18 VOpen-collector pulseDatasheet
12 V solenoid valve (Β½β€³, normally closed)0.02–0.8 MPa, 12 V DC, 8 W, brass body12 VRelay / MOSFET + flyback diodeDatasheet
SHT31-D temperature + humidity sensorβˆ’40 to +125 Β°C Β±0.2 Β°C, 0–100 %RH Β±2 %, 1 Hz–10 Hz, on-chip heater2.4–5.5 VIΒ²C (0x44/0x45)Datasheet
BH1750 digital ambient light sensor1–65535 lx, 16-bit, Β±20 %, spectral response close to the human eye2.4–3.6 VIΒ²C (0x23/0x5C)Datasheet
4-channel opto-isolated relay board4 Γ— SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel5 V coil4Γ— digitalDatasheet
0.96β€³ SSD1306 OLED display128 Γ— 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz IΒ²C3.3–5 VIΒ²C (0x3C)Datasheet
LM2596 adjustable buck converter module4.5–40 V in, 1.25–37 V out, 2 A (3 A peak), ~92 % efficiency4.5–40 VScrew terminals + trimmerDatasheet
12 V 5 A SMPS adapter100–240 VAC in, 12 V Β±5 %, 5 A, 60 W, DC 5.5 Γ— 2.1 mm barrel12 VDC barrelDatasheet
Double-sided perfboard 7 Γ— 9 cm + headersFR-4, 0.1β€³ pitch, plated through-holes, 24 Γ— 18 gridβ€”β€”Datasheet
IP65 ABS junction enclosure 158 Γ— 90 Γ— 60 mmIP65, 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.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA β€” size the regulator accordingly.
YF-S201 hall-effect water flow sensor5–18 V15Count pulses on a hardware interrupt; the K-factor changes with pipe orientation.
12 V solenoid valve (Β½β€³, normally closed)12 V2600Continuous energising heats the coil β€” use latching valves for battery builds.
SHT31-D temperature + humidity sensor2.4–5.5 V1.5The built-in heater burns off condensation β€” essential for outdoor or greenhouse use.
BH1750 digital ambient light sensor2.4–3.6 V0.19Far more linear than an LDR β€” use it whenever you need real lux, not a relative value.
4-channel opto-isolated relay board5 V coil280All four coils energised draw ~280 mA β€” do not power from the MCU 5 V pin.
0.96β€³ SSD1306 OLED display3.3–5 V20Static images burn in β€” invert or scroll the screen periodically.
LM2596 adjustable buck converter module4.5–40 V8Set the output voltage with no load connected before wiring the board.
12 V 5 A SMPS adapter12 V5000Fuse 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.json under 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 dialout group: sudo usermod -aG dialout $USER and 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

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager β†’ "PubSubClient" by Nick O'Leary
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager β†’ "ArduinoJson" by Benoit Blanchon
Adafruit BME280 2.2.xCompensation maths for the Bosch pressure/humidity/temperature sensor.Library Manager β†’ "Adafruit BME280 Library"
Adafruit Unified Sensor 1.1.xCommon sensor event abstraction; a dependency of most Adafruit drivers.Library Manager β†’ "Adafruit Unified Sensor"
BH1750 1.3.0Digital lux readings with selectable resolution modes.Library Manager β†’ "BH1750" by Christopher Laws
Adafruit SSD1306 + GFX 2.5.xFramebuffer and text/graphics primitives for the OLED.Library Manager β†’ "Adafruit SSD1306"
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core
NTPClient / configTime bundledWall-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.

Automated Drip Irrigation β€” system block diagramFunctional block diagram of the Automated Drip Irrigation system. DemandWeather sensorsET inputsCrop stagecoefficientRain sensorskipScheduleWater neededper zoneSequence zonessupply limitDeliverOpen valvefail-closedFlow meterverify deliveryVerifyFault detectburst/block/no-flowLog + alertwater useET + stagezone + volumeflow vs expected
Automated Drip Irrigation β€” system block diagram

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.

Automated Drip Irrigation β€” wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBYF-S201 flow meterGPIO 27Open-collectorpulse, interruptSHT31 weatherGPIO 21 / 22IΒ²C, for ET estimateBH1750 solar radiationGPIO 21 / 22Shared IΒ²C, for ETRain sensorGPIO 32Rain skipZone 1–4 valvesGPIO 25 26 14 12Solenoid valves,fail-closedMaster pump/valveGPIO 33SupplySSD1306 OLEDGPIO 21 / 22Shared IΒ²C
Automated Drip Irrigation β€” wiring schematic
PeripheralPeripheral pinController pinSignal
YF-S201 flow meterPulseGPIO 27Open-collector pulse, interrupt
SHT31 weatherSDA / SCLGPIO 21 / 22IΒ²C, for ET estimate
BH1750 solar radiationSDA / SCLGPIO 21 / 22Shared IΒ²C, for ET
Rain sensorOUTGPIO 32Rain skip
Zone 1–4 valvesIN1–IN4GPIO 25 26 14 12Solenoid valves, fail-closed
Master pump/valveRelayGPIO 33Supply
SSD1306 OLEDSDA / SCLGPIO 21 / 22Shared 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.

Automated Drip Irrigation β€” architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) Β· YF-S201 hall-effect water flow sensor Β·SHT31-D temperature + humidity sensor Β· BH1750 digital ambient lightsensorDriver layerwifi Β· pubsub Β· arduinojson Β· bmeApplication logicsampling loop Β· filtering Β· thresholds Β· state machineTransport layerWi-Fi + MQTT (or LoRa) Β· TLS Β· retry and backoffPresentation layerdashboard Β· mobile notifications Β· historical charts
Automated Drip Irrigation β€” architecture stack

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)

plainReference 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

plainWater 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

plainMulti-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.

Automated Drip Irrigation β€” firmware flowchartControl flow through the main program loop. Read weather, compute ET,check rainRained recently?reduce/skipproceedCompute water needed per zone(ET Γ— Kc)For each zone in sequence:open valveFlow within expectedrange?continueburst/block β€” alarm, closeDelivered volume reached?close valvekeep wateringNext zone or doneLog water use, publish
Automated Drip Irrigation β€” firmware flowchart

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.

cppdrip-irrigation.ino
/* ═══════════════════════════════════════════════════════════════
   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);
}
waterZone() returns a ResultThe core design decision: watering is verified, not fire-and-forget. The function waters until the measured delivered volume reaches the target, and returns whether it succeeded or hit a burst, blockage or valve failure β€” detected from the actual flow, not the valve-open time.
Flow checked every 5 s during wateringThe controller continuously compares measured flow against the zone's expected flow. Flow far too high is a burst (water escaping); far too low is a blockage (crop starving); zero when the valve is open is a valve failure. Each is stopped immediately rather than watering into a fault.
MAX_RUN_MS hard capEven if the flow detection somehow misses a fault, a zone can never run longer than 30 minutes. This bounds the water wasted or the flooding caused by any undetected failure β€” a last line of defence.
Fail-closed valves (HIGH = closed)The valves are normally-closed and driven closed by default, so a power loss or crash closes every valve. A fault can never leave a zone flooding β€” the system fails safe by construction.
referenceET() HargreavesET is estimated from temperature (the Hargreaves method needs only temperature and radiation), giving the reference crop water use. Multiplying by the crop coefficient gives the actual crop demand β€” so watering tracks real weather and crop stage, not a fixed schedule.
ETc Γ— areaM2 = litresOne millimetre of ET over one square metre is one litre of water, so the volume to apply is the crop ET in millimetres times the zone area. This directly converts the demand estimate into a litres target for the flow meter to verify.
Water at 05:00, once a dayEarly-morning watering minimises evaporation loss (low ET, cool) and gets full supply pressure (no competing demand). Watering once a day to the accumulated demand, in sequence, is efficient and gentle on the supply.

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.

  1. 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.

  2. 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.

  3. 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.

  4. 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

Automated Drip Irrigation β€” network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsIrrigation controllerESP32 + flowWi-Fi or LoRaRouter/gatewayfield-dependentMQTT 1883Local broker + Grafanawater loggingWater-use dashboardper zoneFault alertsburst/block
Automated Drip Irrigation β€” network topology

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.

TestWhat you should see
Calibrate and verify the flow meterMeasured litres match a known delivered volume within a few percent.
Run a zone to a target volumeThe 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 openingNo flow when the valve is commanded open is detected as a valve failure.
Cut power mid-wateringThe valve closes (fail-closed) β€” no flooding.
Trigger the rain sensorWatering is skipped or reduced for that cycle.
Change a crop coefficientThe 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.

An ESP32 development board with the ESP-WROOM-32 module and USB connector
An ESP32 development board running the ET-based scheduling and flow-verified delivery for multiple zones. Photograph sourced from Wikimedia Commons β€” ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Delivered water does not match commanded volume

Likely cause. Flow-meter K-factor wrong, or measured at a different flow rate.

Fix. Recalibrate the K-factor at your actual flow rate β€” it changes with flow and orientation. A wrong K-factor makes both the water volume and the fault thresholds wrong.

False burst or blockage alarms

Likely cause. Thresholds too tight, or the expected flow is wrong.

Fix. Re-measure each zone's healthy expected flow and set the burst/blockage thresholds as clear multiples of it (e.g. 1.5Γ— and 0.5Γ—). Account for the normal flow ramp when a valve first opens β€” do not evaluate faults in the first few seconds.

A zone floods when it should be off

Likely cause. Valve stuck open, or wired normally-open.

Fix. Use normally-closed, fail-closed valves. Confirm they close when de-energised. Add per-zone flow monitoring so a stuck-open valve (flow when none is commanded) is detected. The hard runtime cap limits the damage.

Watering is uneven across a zone

Likely cause. Pressure too high/low, or clogged emitters.

Fix. Fit a pressure regulator per zone β€” drip emitters are pressure-sensitive. Fit and maintain a filter β€” emitters clog easily, and a clog shows as reduced flow (which the system should detect). Flush lines periodically.

The system over- or under-waters consistently

Likely cause. Wrong crop coefficient, ET estimate off, or rain not accounted for.

Fix. Check the crop coefficient matches the current growth stage. Validate the ET estimate against a reference. Ensure rain is subtracted from demand. Fine-tune the crop coefficients from observed crop response over a season.

The sketch will not upload β€” "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools β†’ Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it β€” it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 Β΅F electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise β€” shorten the cable and keep motor wiring away from the USB lead.

An IΒ²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an IΒ²C scanner sketch first β€” it should print the device address. Most breakout boards include 4.7 kΞ© pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device β€” check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

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 a millis() 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_t where 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

Why ET-based instead of a timer?

Because crop water demand varies enormously with weather, and a timer ignores that entirely. A fixed schedule waters the same amount on a cool damp week as a hot dry one β€” wasting water in the first and starving the crop in the second. Evapotranspiration-based scheduling estimates what the crop actually consumed and replaces that, which typically saves 20–40 % of water while improving yield because the crop is neither drought-stressed nor waterlogged.

Why is the flow meter so important?

Because without it, the system is hoping rather than knowing. A timer-based drip controller has no idea whether the water it commanded reached the plants. A burst pipe can run for days wasting thousands of litres and washing out a field; a blocked line can starve a crop β€” both undetected until the damage is visible. The flow meter measures actual delivery, catching bursts (high flow), blockages (low flow) and valve failures (no flow) in minutes. It is the difference between a real irrigation system and a hopeful one.

What is a crop coefficient?

A number that scales the reference evapotranspiration to a specific crop at a specific growth stage. A bare reference surface loses water at ETβ‚€; a real crop loses ETβ‚€ Γ— Kc. A young seedling with little leaf area has a low Kc (around 0.4) and needs little water; a mature crop at full canopy has a high Kc (up to 1.1–1.2) and needs the most; a senescing crop declines. Tracking the crop stage and applying the right coefficient is what makes the watering follow real demand through the season.

How accurate does the ET estimate need to be?

Reasonably, but not perfectly. The temperature-only Hargreaves method is less accurate than the full Penman-Monteith equation, but it is adequate for field irrigation scheduling β€” you are replacing consumed water, and small errors accumulate slowly and are corrected as you observe crop response and tune the coefficients. For most crops, getting within 10–15 % of true ET, combined with soil-moisture feedback, gives excellent results. Precision matters more for high-value or water-scarce situations.

Do I need soil-moisture sensors too?

They are a valuable complement, not a replacement. ET-based scheduling estimates demand from the top down (weather β†’ crop need); soil moisture measures the result from the bottom up (did the root zone actually get wetter). Using both closes the loop: ET tells you how much to apply, soil moisture confirms it arrived and did not run off or evaporate. The most robust systems use both, which is why the soil-moisture project is a natural companion.

What happens if a valve sticks open?

The system detects it and, failing that, bounds it. Per-zone flow monitoring detects flow when no zone is commanded open. The valves are fail-closed, so a power loss closes them. And a hard maximum runtime caps how long any zone can run. Together these mean a stuck-open valve is caught quickly or limited in damage β€” which matters because a valve stuck open on a drip main can flood a field or empty a water supply.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. FAO Irrigation and Drainage Paper 56 β€” Crop evapotranspirationFAO
  2. Hargreaves & Samani, "Reference crop evapotranspiration from temperature"Applied Engineering in Agriculture, 1985
  3. YF-S201 water flow sensor β€” datasheet and K-factorHobbytronics
  4. Netafim, "Drip Irrigation Design and Management"Netafim
  5. Allen et al., "Crop coefficients and Kc values by crop and stage"FAO
  6. USDA NRCS β€” Irrigation Water ManagementUSDA NRCS