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.
Parts
- ESP32 DevKit board
- Capacitive soil moisture sensor (v1.2). Avoid the two-bare-prong resistive type: its electrodes corrode through electrolysis within weeks.
- 5V 1-channel relay module (opto-isolated)
- Mini submersible DC pump (5V or 12V) and silicone tubing. Check the current rating on the label (typically 100–500 mA).
- A separate DC supply for the pump, matching its voltage and current
- 1N4007 diode (flyback protection), jumper wires, a waterproof enclosure
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.
Wiring
| From | To | Notes |
|---|---|---|
| Sensor VCC | ESP32 3V3 | The v1.2 module runs on 3.3–5.5V; powering it at 3.3V keeps AOUT within the ADC limit |
| Sensor AOUT | GPIO34 | ADC1 pin, input only |
| Sensor GND | GND | |
| Relay VCC | VIN (5V) | The relay coil needs 5V; VIN comes from the USB port |
| Relay IN | GPIO26 | Most modules trigger on a low level (active-low) |
| Relay GND | GND | |
| Relay COM | Pump supply (+) | Use COM–NO: if the ESP32 loses power the pump turns off |
| Relay NO | Pump (+) | |
| Pump (−) | Pump supply (−) | Separate pump supply, not connected to the ESP32 |
| 1N4007 diode | Across the pump | Stripe (cathode) towards (+), i.e. reverse-biased in normal operation |
Calibrating the sensor
The raw values depend on the individual module, supply voltage and soil, so you need to measure two reference points yourself:
- Flash the code below with the defaults and open the Serial Monitor (115200). It prints the raw value every 2 seconds.
- Dry the sensor and hold it in air: note the stable raw value. That is
RAW_DRY(typically around 2600–3000). - 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). - For best results repeat in the actual pot: completely dry soil and thoroughly watered soil. Update the two constants and reflash.
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
- Hysteresis: start below 30%, stop at 60% or more.
- Maximum pumping time (
MAX_PUMP_MS): even if the sensor fails, the pump never runs more than 20 seconds at a time. This is the last line of defence against overflowing the pot. - Soak delay (
SOAK_MS): water takes time to reach the sensor. Without a delay the controller still sees "dry" soil right after pumping and pumps again. - Sensor check: a raw value that is too low (< 300) or too high (> 4000) is treated as a fault and the pump is blocked.
- Median of 15 samples: the ESP32 ADC is noisy and non-linear; the median discards spikes.
- The "off" level is written before
pinMode: the relay is not pulsed when the output is enabled.
Testing before using real plants
- 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%.
- If the relay behaves the opposite way, flip
RELAY_ACTIVE_LOW. - Connect the pump to a bucket of water and check that it stops after at most 20 seconds when the sensor stays dry.
- Install it in the pot and raise
MAX_PUMP_MSgradually until the water amount suits your pot.
Troubleshooting
| Symptom | Likely cause |
|---|---|
| Relay clicks constantly | The 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-up | An 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 around | A 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 out | Empty reservoir or kinked tubing; a submersible pump must be fully under water while running. |
Next steps
- Add a float switch to detect an empty tank and block the pump (prevents dry running).
- Publish the moisture to Home Assistant over MQTT as in the weather station project.
- Use deep sleep to run on battery: wake every 30 minutes, measure, pump if needed and sleep again. Remember to keep
lastStopin RTC memory. - Use ESPHome if you prefer YAML configuration over C++.