Skip to content

Project

ESP32 Automatic Plant Watering with Blynk and Soil Moisture Sensor

Build an ESP32 plant-watering system with a capacitive soil sensor, a MOSFET-driven pump and a Blynk dashboard. Calibrate readings, use hysteresis, limit pump runtime, and keep watering safely on the device even when Wi-Fi or the cloud is down.

  • 17 min read
  • Updated November 2, 2026
ESP32 Automatic Plant Watering with Blynk and Soil Moisture Sensor

What You Will Build

This project waters a plant for you and tells you what it is doing. An ESP32 reads a capacitive soil-moisture sensor, decides when the soil is too dry, and switches a small DC pump through a MOSFET. A Blynk dashboard on your phone shows the moisture level and the pump state, and lets you switch between automatic and manual watering.

The design rule that makes the project trustworthy is simple: the ESP32 makes the watering decisions, and the cloud only watches and nudges. Moisture checks, thresholds, the maximum pump run time and the rest period between waterings all run on the board. If your router restarts or Blynk has a bad day, the plant still gets looked after, and the pump cannot run forever.

What you will learn:

  • How capacitive soil sensors behave and why you must calibrate your own
  • How to drive a pump safely from a 3.3 V GPIO with a logic-level MOSFET, a gate resistor, a pull-down and a flyback diode
  • Why hysteresis (two thresholds) prevents a pump from rapidly switching on and off
  • How to set up Blynk datastreams and a dashboard for monitoring and manual control
  • How to write firmware that keeps working offline, rejects a faulty sensor and limits every pump run

Time: about three hours. Skill level: intermediate. Everything is low voltage.

How the System Is Organised

Three loops share one board. A sensing loop averages eight ADC readings every 2.5 seconds and converts them to a relative moisture percentage. A decision loop applies the hysteresis rule, the rest period and the maximum run time, and drives the pump pin. A reporting loop sends moisture and pump state to Blynk only when a connection exists.

Because the decision loop never waits for Wi-Fi, the system behaves the same online and offline. Blynk is a window onto the system rather than a dependency of it. The flowchart below shows one pass through the control loop.

Control loop: read the sensor, reject implausible values, apply the hysteresis rule, enforce the maximum run time, then report to Blynk

Components

10 items
NameQtyLink
ESP32 DevKit (WROOM-32)×1—
Capacitive soil-moisture sensor (analog output, 3.3 V compatible)×1—
Small DC submersible pump (3 to 6 V) with silicone tubing×1—
Logic-level N-channel MOSFET, or a MOSFET driver module (rated well above the pump current)×1—
Flyback diode (1N5819 or 1N4007)×1—
100 Ω resistor (gate series)×1—
10 kΩ resistor (gate pull-down)×1—
5 V power supply for the pump, rated above the pump’s startup current×1—
Water reservoir (a bottle or tub) and a pot with a drainage tray×1—
Breadboard and jumper wires×1—

Choosing the Parts Well

The soil sensor

Soil sensors fall into two families, and the difference matters for a project that stays powered for months:

TypeHow it measuresStrengthsWeaknesses
CapacitiveSoil changes the capacitance of a coated PCB probeNot exposed to the soil, far longer lifeReadings differ between modules, needs calibration
Resistive (two exposed prongs)Current passes through the soil between metal prongsVery cheapElectrolysis corrodes the prongs within weeks if powered continuously

Use a capacitive sensor. Keep its electronics above the soil line, because only the marked probe area is waterproof, and the exposed edge and components are not.

The pump and the driver

Small hobby pumps usually draw a few hundred milliamps, and more at the moment they start. Check your pump's datasheet and choose a supply with comfortable headroom. Never power a pump from an ESP32 pin or the board's 3.3 V regulator. A GPIO can safely source only a few tens of milliamps and exists to switch something else.

A logic-level N-channel MOSFET is an efficient, silent switch. The key specification is a low on-resistance at a gate voltage of 3.3 V or less, not just the headline number. If your parts bin has only 5 V-gate MOSFETs, use a ready-made MOSFET driver module, or a relay module that is rated for the load and that you know works from a 3.3 V signal.

A pump is an inductive load. When it switches off, its coil produces a voltage spike that can destroy the MOSFET and disturb the ESP32. The flyback diode across the pump absorbs that spike, and it is not optional.

Wiring

FromTo
Soil sensor VCCESP32 3V3
Soil sensor GNDESP32 GND
Soil sensor AOUTESP32 GPIO34
ESP32 GPIO26100 Ω resistor, then MOSFET gate
MOSFET gate10 kΩ resistor to GND (pull-down)
MOSFET sourceGND rail
MOSFET drainPump negative wire
Pump positive wire+5 V pump supply
Flyback diodeAcross the pump: cathode (striped end) to +5 V, anode to the MOSFET drain
5 V supply negativeGND rail, joined to ESP32 GND

Each part of the pump circuit has a job:

  • 100 Ω gate resistor: limits the current spike into the gate when the pin switches and tames ringing.
  • 10 kΩ pull-down: while the ESP32 resets, a GPIO can float. Without the pull-down, noise could briefly switch the pump on every time the board boots.
  • Flyback diode: safely returns the pump's switch-off spike.
  • Common ground: the gate signal is measured against the MOSFET source, so the pump supply and the ESP32 must share ground. This is the most common reason a "correct" circuit does nothing.

The sensor connects to GPIO34, an input-only pin on ADC1. ADC1 keeps working while Wi-Fi is active, whereas ADC2 pins do not. Powering a capacitive sensor from 3.3 V also keeps its output within the ESP32's input range.

Wiring diagram: soil sensor on GPIO34, MOSFET pump driver on GPIO26 with gate resistor, pull-down and flyback diode

🚨 Danger

Keep this project low voltage and keep water away from the electronics. Never connect mains voltage to the breadboard. Place the ESP32, MOSFET and wiring above and away from the reservoir, in a spot where a leak or an overflow cannot reach them, and test the pump with its outlet in a bowl before you attach it to a plant.

Calibrating the Sensor Instead of Guessing

An ADC number is not a moisture percentage until you have measured what your sensor reads in your soil. Two measurements are enough:

  • DRY_RAW: the reading in dry soil, or in air if the soil is still wet.
  • WET_RAW: the reading after you water the pot thoroughly and let the excess drain.

Most capacitive modules give a lower number when wetter, but this is not universal. Measure instead of assuming. To collect the numbers, upload the main sketch with placeholder values and watch the Serial Monitor at 115200 baud: it prints raw=... every 2.5 seconds.

Then follow this sequence:

Steps

  1. 1Keep the pump driver disconnected (or the pump out of any water) while you calibrate.
  2. 2Hold the sensor in air or dry soil. Wait until the raw value settles and note it as DRY_RAW.
  3. 3Push the sensor into the pot to the marked line, water thoroughly, and let it drain for several minutes.
  4. 4Note the stable raw value as WET_RAW. If it is higher than DRY_RAW, your sensor rises when wet. The code still works because map() accepts reversed ranges.
  5. 5Write both numbers into the sketch, upload, and confirm the percentage moves in the right direction as the soil dries.
  6. 6Choose MOISTURE_ON and MOISTURE_OFF for your plant. Start with 30% and 45%, then adjust after a week of observation.

The percentage that results is a relative indicator. Soil type, compaction, temperature, salinity and probe position all shift the reading, and sensors age. It is excellent for deciding "dry versus watered" in one pot, and it is not a laboratory measurement of water content.

Why two thresholds

If the pump started at 30% and stopped at 31%, a tiny change would flip it constantly. Dry soil takes time to soak, so the reading lags behind the pump. With separate ON (30%) and OFF (45%) points, the pump runs until the soil is clearly wet and stays off until it is clearly dry. The gap between them is the hysteresis band.

Hysteresis in action: the pump starts below 30%, stops at 45% and does not switch again until the soil has dried back down

Setting Up Blynk

The sketch uses Blynk IoT (the platform formerly marketed as Blynk 2.0). Menu names change from time to time, so follow the current Blynk documentation if a label differs.

  1. Install the Blynk library by Volodymyr Shymanskyy in the Arduino IDE's Library Manager.
  2. In the Blynk Console, create a template named Plant Watering, with hardware ESP32 and connection type Wi-Fi.
  3. Add four datastreams to the template, exactly as in the table.
  4. Build a web dashboard from widgets and bind each to a datastream.
  5. Create a device from the template. Blynk shows the template ID, template name and the device auth token. Paste those into the first three #define lines of the sketch.
PinNameTypeRangeWidget
V0ModeInteger0 to 1 (0 manual, 1 automatic)Switch
V1MoistureInteger0 to 100 (%)Gauge
V2Pump StateInteger0 to 1LED
V3Manual PumpInteger0 to 1Button or switch

Treat the auth token like a password. Do not post it in screenshots or commit it to a public repository. Plan limits, data retention and event quotas change over time, so check the current Blynk documentation before relying on a particular feature.

The Firmware

Install the Blynk library, put your credentials and calibration values in, and upload. The sketch is written so that the pump decision never depends on the network.

sketch.ino
// ESP32 plant watering with Blynk IoT: local control first, cloud second
#define BLYNK_TEMPLATE_ID   "REPLACE_WITH_TEMPLATE_ID"
#define BLYNK_TEMPLATE_NAME "Plant Watering"
#define BLYNK_AUTH_TOKEN    "REPLACE_WITH_DEVICE_AUTH_TOKEN"
#define BLYNK_PRINT Serial

#include <WiFi.h>
#include <BlynkSimpleEsp32.h>

// ---- Pins ----
const int SOIL_PIN = 34;            // ADC1 input (works with Wi-Fi on)
const int PUMP_PIN = 26;            // MOSFET gate drive, NOT pump power
const bool PUMP_ACTIVE_LOW = false; // true if your driver switches on at LOW

// ---- Calibration: measure these on YOUR sensor and soil ----
const int DRY_RAW = 3000;           // raw reading in dry soil
const int WET_RAW = 1400;           // raw reading in watered, drained soil
const int FAULT_LOW_RAW  = 100;     // below this: sensor shorted or unplugged
const int FAULT_HIGH_RAW = 4000;    // above this: sensor open or floating

// ---- Watering policy ----
const int MOISTURE_ON  = 30;                 // start watering below this %
const int MOISTURE_OFF = 45;                 // stop watering at or above this %
const unsigned long SAMPLE_MS   = 2500;      // control loop period
const unsigned long MAX_PUMP_MS = 8000;      // hard limit for one run
const unsigned long REST_MS     = 10UL * 60UL * 1000UL; // wait between runs

char ssid[] = "REPLACE_WITH_WIFI";
char pass[] = "REPLACE_WITH_WIFI_PASSWORD";

BlynkTimer timer;
bool autoMode = true;
bool manualRequest = false;
bool pumpOn = false;
bool hasRun = false;
unsigned long pumpStartedAt = 0;
unsigned long lastStopAt = 0;

void reportState() {
  if (!Blynk.connected()) return;
  Blynk.virtualWrite(V0, autoMode ? 1 : 0);
  Blynk.virtualWrite(V2, pumpOn ? 1 : 0);
  Blynk.virtualWrite(V3, manualRequest ? 1 : 0);
}

void setPump(bool on) {
  if (on == pumpOn) return;
  pumpOn = on;
  digitalWrite(PUMP_PIN, on ? (PUMP_ACTIVE_LOW ? LOW : HIGH)
    : (PUMP_ACTIVE_LOW ? HIGH : LOW));
  if (on) {
    pumpStartedAt = millis();
  } else {
    lastStopAt = millis();
    hasRun = true;
  }
  if (Blynk.connected()) Blynk.virtualWrite(V2, pumpOn ? 1 : 0);
}

int readSoilRaw() {
  long sum = 0;
  for (int i = 0; i < 8; i++) {
    sum += analogRead(SOIL_PIN);
    delay(5);
  }
  return sum / 8;
}

// The device is the source of truth: on (re)connect, publish local state
// instead of restoring whatever the cloud last remembered.
BLYNK_CONNECTED() {
  reportState();
}

BLYNK_WRITE(V0) {
  autoMode = (param.asInt() == 1);
  manualRequest = false;
  setPump(false);                       // always stop when the mode changes
  if (Blynk.connected()) Blynk.virtualWrite(V3, 0);
}

BLYNK_WRITE(V3) {
  manualRequest = (param.asInt() == 1);
  if (!autoMode) setPump(manualRequest);
}

void controlLoop() {
  const int raw = readSoilRaw();
  const bool valid = (DRY_RAW != WET_RAW) && raw > FAULT_LOW_RAW && raw < FAULT_HIGH_RAW;

  int pct = -1;
  if (valid) {
    pct = constrain(map(raw, DRY_RAW, WET_RAW, 0, 100), 0, 100);
    if (Blynk.connected()) Blynk.virtualWrite(V1, pct);
    Serial.print("raw=");
    Serial.print(raw);
    Serial.print("  moisture=");
    Serial.println(pct);
  } else {
    Serial.println("Sensor reading invalid; automatic watering paused.");
  }

  if (autoMode) {
    if (!valid) {
      setPump(false);
    } else if (!pumpOn) {
      const bool rested = !hasRun || (millis() - lastStopAt >= REST_MS);
      if (pct < MOISTURE_ON && rested) setPump(true);
    } else if (pct >= MOISTURE_OFF) {
      setPump(false);
    }
  } else {
    setPump(manualRequest);
  }

  if (pumpOn && millis() - pumpStartedAt >= MAX_PUMP_MS) {
    setPump(false);
    manualRequest = false;
    if (Blynk.connected()) Blynk.virtualWrite(V3, 0);
    Serial.println("Maximum pump run reached; pump stopped.");
  }
}

void maintainConnection() {
  if (WiFi.status() == WL_CONNECTED && !Blynk.connected()) {
    Blynk.connect(3000);
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(PUMP_PIN, OUTPUT);
  digitalWrite(PUMP_PIN, PUMP_ACTIVE_LOW ? HIGH : LOW);   // pump off first

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);               // does not block: control runs offline
  Blynk.config(BLYNK_AUTH_TOKEN);

  timer.setInterval(SAMPLE_MS, controlLoop);
  timer.setInterval(30000L, maintainConnection);
}

void loop() {
  if (Blynk.connected()) Blynk.run();
  timer.run();
}

How the Firmware Behaves

Offline first

The most common Blynk example calls Blynk.begin(), which waits for Wi-Fi and the cloud before the rest of the sketch runs. If your router is down at boot, nothing would ever water the plant. This sketch avoids that. It starts Wi-Fi without waiting, configures Blynk with Blynk.config(), and lets the timers run immediately. A second timer tries Blynk.connect(3000) every 30 seconds while Wi-Fi is up but the cloud is not. Every virtualWrite is guarded by Blynk.connected().

Rejecting a bad reading

A disconnected or shorted sensor produces values near the ends of the ADC range or random noise from a floating pin. The code treats any reading below 100 or above 4000 as invalid, pauses automatic watering and turns the pump off. A broken sensor stops the watering, instead of reading as "bone dry" and flooding the pot.

The rule and the three limits

In automatic mode, the pump turns on only when moisture is below 30% and the rest period since the last run has passed, and it turns off at 45% or above. Three independent limits sit around that rule:

  • Hysteresis prevents rapid switching.
  • MAX_PUMP_MS stops any single run after 8 seconds, in either mode.
  • REST_MS forces ten minutes between runs, so water has time to soak toward the sensor before the next decision.

Together they bound how much water one fault can deliver. They are not a complete safety system, so see the section on limits below.

Mode changes and cloud state

Switching the mode always stops the pump and clears the manual request, so a lingering "on" cannot carry over. On every reconnect, BLYNK_CONNECTED() pushes the device's own state to the dashboard. The device is the source of truth, and the cloud cannot silently restart a pump.

Testing Safely, in Stages

Steps

  1. 1With the pump disconnected, confirm the Serial Monitor shows raw values and a moisture percentage that moves the right way when you dry and wet the sensor.
  2. 2Connect the pump and driver, but keep the pump outlet in a bowl above the reservoir. Hold the sensor in air so the moisture reads dry, and confirm the pump starts.
  3. 3Watch it stop by itself after about 8 seconds, and confirm it does not restart until the rest period has passed.
  4. 4Dip the sensor into water until the percentage passes 45%, and confirm the pump stops at the upper threshold.
  5. 5Unplug the sensor’s AOUT wire. The Serial Monitor should report an invalid reading and the pump must stay off.
  6. 6Switch to manual mode in Blynk, press the manual pump control, and confirm the pump runs and still stops at the maximum run time.
  7. 7Turn the router off for a few minutes. The pump logic should keep working, and the dashboard should recover when Wi-Fi returns.

Troubleshooting

SymptomLikely causeFix
Percentage is reversedDRY_RAW and WET_RAW are swapped or mismeasuredRe-measure both and put each in the correct constant.
Percentage never changesWrong pin, or sensor not poweredCheck AOUT on GPIO34 and VCC on 3V3. Watch raw= in the Serial Monitor.
Pump never runsWrong polarity, no common ground, MOSFET not fully onConfirm common ground, test with PUMP_ACTIVE_LOW, and check the MOSFET's gate threshold against 3.3 V.
Pump runs at boot or randomlyMissing gate pull-downAdd the 10 kΩ resistor from gate to GND.
Pump cycles rapidlyHysteresis gap too small, or sensor at the edge of the soilWiden the gap and re-seat the sensor in a representative spot.
ESP32 resets when the pump startsSupply sag or noiseUse a separate pump supply, add a 470 µF capacitor across it, and keep the diode across the pump.
Dashboard shows nothingTemplate or token mismatch, or Wi-Fi downCheck the three #define values and the Wi-Fi credentials, and read the BLYNK_PRINT output.
Mode switch resets itselfDashboard and device out of syncThis is deliberate: the device republishes its state on reconnect. Set the mode again.

Limits and Upgrades

The run-time limit, rest period and plausibility check make this a considerate hobby controller, but they are not a complete safety system. Before you leave the system unattended for days, consider these:

  • Reservoir-empty detection. A float switch on the reservoir stops the pump before it runs dry and burns out.
  • Overflow protection. Use a drip tray, a tank larger than the pot's capacity, or a second sensor at the drain.
  • Independent hardware cut-off. A timer relay in series with the pump supply bounds the worst case even if the firmware fails.
  • Several plants. Add one sensor and one pump channel per pot, and give each its own thresholds, since plants and soils differ.
  • Reduce probe wear. If you use a resistive probe anyway, power it from a GPIO only while measuring.
  • Notifications. Use a Blynk event to warn you when the sensor is invalid or the pump hit its maximum run.

Frequently Asked Questions

How often should the plant be watered? It depends on the plant, pot, soil and season, which is exactly why the system waters from the soil reading and not from a clock. Tune the thresholds to the plant.

Can I use a relay instead of a MOSFET? Yes, a relay module rated for the pump and compatible with a 3.3 V signal works, and the flyback diode across the pump is still recommended.

Why GPIO34 and not GPIO2 or GPIO12? GPIO34 is an input-only ADC1 pin with no boot-time role. GPIO2 and GPIO12 are strapping pins and can disturb booting.

Does it work without Blynk? Yes. Delete the Blynk lines and the control loop keeps working. Blynk only adds remote visibility and manual control.

Why a relative percentage and not a real water content? Capacitive modules are not calibrated against a reference method, so only the relative trend is trustworthy.

Summary

You built a plant-watering controller that keeps its decisions on the ESP32: calibrated readings, hysteresis, a maximum run time, a rest period and a sensor fault check, with Blynk as the dashboard rather than the brain. You also learned how to drive an inductive load properly, why the pump needs a pull-down and a flyback diode, and how to test each protective behaviour before trusting it with a living plant.

Next steps

Official reference: Blynk documentation. Calibrate the sensor and validate pump behavior in a supervised low-voltage test before leaving the system unattended.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.