Smart homeAutomation

Automatic plant watering system with an ESP32

Difficulty: medium · Time: ~2 hours · Cost: ~$10–14

This project reads the soil moisture in a pot and switches a small water pump on when the soil is dry and off once it is moist enough. The interesting part is not the few digitalWrite calls but the safety layers: hysteresis, a soak delay, a maximum pumping time and sensor fault detection. Without them it is very easy to flood the pot or burn out the pump.

Safety: this guide only uses a low-voltage DC pump (5–12V). Do not use a mains-powered pump unless you really understand electrical work. Keep the power supply, relay and wiring dry and above the water level.

Parts

How it works

A capacitive sensor measures the dielectric constant of the soil. Water has a far higher dielectric constant than air, so the wetter the soil, the lower the AOUT output voltage. The ADC therefore returns a high raw value for dry soil and a low one for wet soil, the opposite of what you might expect. The code converts it to a percentage using two calibration points, RAW_DRY and RAW_WET.

The controller is a two-state machine with two different thresholds (start at 30%, stop at 60%). With a single threshold, moisture hovering around it would make the relay chatter. The gap between the thresholds is called hysteresis.

IDLEPUMPINGmoisture < 30% AND soak time elapsedAND sensor reading validmoisture ≥ 60% OR pump ran > 20 sOR sensor fault
Figure 1: The pump control state machine. Every transition has a safety condition.

Wiring

ESP32 DevKit3V3GPIO34GNDVIN (5V)GPIO26GNDCapacitive soil sensor v1.2VCCAOUTGNDRelay module 5V (1 ch)VCCINGNDNCCOMNOPump supply+−MDC pump1N4007Flyback diode
Figure 2: Circuit diagram. A solid dot is a junction; crossing lines without a dot are not connected. The pump has its own supply, switched by the relay's COM–NO contacts.
FromToNotes
Sensor VCCESP32 3V3The v1.2 module runs on 3.3–5.5V; powering it at 3.3V keeps AOUT within the ADC limit
Sensor AOUTGPIO34ADC1 pin, input only
Sensor GNDGND
Relay VCCVIN (5V)The relay coil needs 5V; VIN comes from the USB port
Relay INGPIO26Most modules trigger on a low level (active-low)
Relay GNDGND
Relay COMPump supply (+)Use COM–NO: if the ESP32 loses power the pump turns off
Relay NOPump (+)
Pump (−)Pump supply (−)Separate pump supply, not connected to the ESP32
1N4007 diodeAcross the pumpStripe (cathode) towards (+), i.e. reverse-biased in normal operation
Why GPIO34 and GPIO26? ADC2 is taken over by WiFi and cannot be read while WiFi is on; GPIO34 is on ADC1 so it keeps working when you add WiFi/MQTT later. GPIO26 is not a strapping pin so it does not interfere with boot. See ESP32 GPIO pins to avoid.

Calibrating the sensor

The raw values depend on the individual module, supply voltage and soil, so you need to measure two reference points yourself:

  1. Flash the code below with the defaults and open the Serial Monitor (115200). It prints the raw value every 2 seconds.
  2. Dry the sensor and hold it in air: note the stable raw value. That is RAW_DRY (typically around 2600–3000).
  3. Dip the sensor into a glass of water up to the limit line printed on the PCB (not beyond: the electronics above it are not waterproof): note the raw value. That is RAW_WET (typically around 1100–1500).
  4. For best results repeat in the actual pot: completely dry soil and thoroughly watered soil. Update the two constants and reflash.
Protect the sensor: seal the exposed electronics at the top with epoxy or conformal coating and keep water from running down onto the components. A capacitive sensor does not corrode like a resistive one, but the PCB edge can still absorb water.

Source code

The code runs standalone, with no WiFi. Tested in the Arduino IDE with the "ESP32 Dev Module" board.

// Automatic plant watering: ESP32 + capacitive soil sensor + relay + DC pump
const int  PIN_SOIL  = 34;     // ADC1_CH6, input only, never use ADC2
const int  PIN_RELAY = 26;     // not a strapping pin
const bool RELAY_ACTIVE_LOW = true;   // most relay modules: LOW = contact closed

// Calibration: raw value in open air (dry) and dipped in water (wet)
const int RAW_DRY = 2800;
const int RAW_WET = 1300;

const int      START_PCT     = 30;                 // pump below this level
const int      STOP_PCT      = 60;                 // stop once this level is reached
const uint32_t READ_EVERY_MS = 2000;
const uint32_t MAX_PUMP_MS   = 20UL * 1000;        // max 20 s per pumping run
const uint32_t SOAK_MS       = 10UL * 60 * 1000;   // wait 10 min between runs so water can soak in

bool     pumping = false, hasWatered = false;
uint32_t pumpStart = 0, lastStop = 0, lastRead = 0;

void setPump(bool on) {
  digitalWrite(PIN_RELAY, (on != RELAY_ACTIVE_LOW) ? HIGH : LOW);
  if (on) pumpStart = millis();
  else if (pumping) { lastStop = millis(); hasWatered = true; }
  pumping = on;
}

// Median of 15 samples: rejects ADC noise better than a plain average
int readRawMedian() {
  int v[15];
  for (int i = 0; i < 15; i++) { v[i] = analogRead(PIN_SOIL); delay(5); }
  for (int i = 1; i < 15; i++) {            // insertion sort
    int k = v[i], j = i - 1;
    while (j >= 0 && v[j] > k) { v[j + 1] = v[j]; j--; }
    v[j + 1] = k;
  }
  return v[7];
}

void setup() {
  Serial.begin(115200);
  digitalWrite(PIN_RELAY, RELAY_ACTIVE_LOW ? HIGH : LOW);   // set the OFF level before enabling the output
  pinMode(PIN_RELAY, OUTPUT);
  analogReadResolution(12);
  analogSetPinAttenuation(PIN_SOIL, ADC_11db);              // measures up to ~3.1 V
}

void loop() {
  uint32_t now = millis();
  if (now - lastRead < READ_EVERY_MS) return;
  lastRead = now;

  int  raw      = readRawMedian();
  bool sensorOk = raw > 300 && raw < 4000;     // extremes usually mean a broken wire or short
  int  pct      = constrain(map(raw, RAW_DRY, RAW_WET, 0, 100), 0, 100);
  Serial.printf("raw=%d  moisture=%d%%  pump=%s\n", raw, pct, pumping ? "ON" : "off");

  if (pumping) {
    if (!sensorOk || pct >= STOP_PCT || now - pumpStart >= MAX_PUMP_MS) setPump(false);
  } else if (sensorOk && pct < START_PCT && (!hasWatered || now - lastStop >= SOAK_MS)) {
    setPump(true);
  }
}

Safety layers in the code

10060300STOP THRESHOLD 60%START THRESHOLD 30%ONONPump ONSoak time (SOAK_MS)Soil moisture (%)Time →
Figure 3: Simulated soil moisture over time. The pump starts when moisture falls to 30% and stops at 60%, followed by a soak period. The curve is an illustration, not measured data.

Testing before using real plants

  1. Pump disconnected: power only the relay and sensor. Cover/dip the sensor by hand and listen for the relay clicking when moisture falls below 30% and releasing at 60%.
  2. If the relay behaves the opposite way, flip RELAY_ACTIVE_LOW.
  3. Connect the pump to a bucket of water and check that it stops after at most 20 seconds when the sensor stays dry.
  4. Install it in the pot and raise MAX_PUMP_MS gradually until the water amount suits your pot.
Simulation tip: you can try the logic first in Wokwi: replace the sensor with a potentiometer on GPIO34 and the pump with an LED switched by a relay. Turn the potentiometer to imitate dry/wet soil (adjust the two raw constants to match the pot's range).

Troubleshooting

SymptomLikely cause
Relay clicks constantlyThe start/stop thresholds overlap, or a weak USB supply makes the ESP32 reset when the relay closes. Use a 5V supply of at least 1A.
Relay is on at power-upAn active-high module configured as active-low, or the control pin floating during boot. For active-low modules add a 10 kΩ pull-up from IN to VCC.
Percentage jumps aroundA long unshielded sensor lead or noise from the pump. Add a 100 nF capacitor near the ADC pin, route the wire away from the pump and keep the median filter.
Always 0% or 100%Not calibrated, or AOUT wired to the wrong pin. Look at the raw value in Serial.
Pump runs but no water comes outEmpty reservoir or kinked tubing; a submersible pump must be fully under water while running.

Next steps