An automatic watering system is more than a soil sensor connected to a relay. Soil readings vary by potting mix, sensor depth, moisture, supply voltage and sensor revision. A pump can also empty a reservoir, run dry or switch too frequently if the control logic is careless.
This guide builds the same core system in two ways: a simple Arduino Uno version for local, stand-alone watering and an ESP32 version that adds Wi-Fi and MQTT monitoring. Both use a capacitive soil-moisture sensor, calibrated readings, a relay or suitable driver and a separate pump supply. The key design principle is the same in both versions: watering decisions and pump shut-off must work locally, even when Wi-Fi, MQTT or a dashboard is unavailable.
Quick answer: connect a capacitive soil moisture sensor to an analog pin (A0 on an Uno, an ADC1 pin such as GPIO 34 on an ESP32), switch a small DC pump through a relay or MOSFET from its own power supply, and calibrate two readings: the sensor in dry soil and in freshly watered soil. Start the pump below about 30 % and stop it above about 45 % (two thresholds, so it doesn't flicker on and off), and always add a maximum pump time so a failed sensor can't empty the reservoir. On a 5 V Uno a typical capacitive v1.2 sensor reads roughly 500–600 in air and 250–300 in water; your own numbers will differ.
What you will build
The controller periodically reads the sensor, converts its raw value to an approximate moisture percentage using calibration points, and starts watering when the reading stays below a selected threshold. It stops when the moisture estimate reaches a higher threshold, when a maximum pump-run time is reached, or when a safety condition fails.
The Arduino Uno version is suitable for a desk or greenhouse prototype that does not need networking. The ESP32 version keeps local control but can publish sensor readings and pump state to a broker such as Mosquitto or Home Assistant via MQTT.
Components
| Component | Purpose / selection note |
|---|---|
| Arduino Uno R3 or compatible board | Local controller for the first version |
| ESP32 development board | Alternative controller with Wi-Fi for MQTT monitoring |
| Capacitive soil-moisture sensor | Usually more resistant to corrosion than exposed resistive probes, but still needs calibration |
| Relay module or suitable pump driver | Must match the controller input and the pump voltage/current |
| Low-voltage DC pump | Choose one appropriate for the water flow and lift needed |
| Separate pump power supply | Sized for pump operating and startup current |
| Breadboard, jumper wires and tubing | For the low-voltage prototype |
| Optional I²C OLED or LCD | Local display; not required for the control loop |
| Wi-Fi and MQTT broker | Required only for the ESP32 telemetry example |
Do not assume two similarly named moisture sensors have the same supply range, output range or pin order. Read the exact module’s labels and datasheet before wiring it.
Safety before wiring
- Never power a pump directly from a microcontroller GPIO. Use a relay rated for the pump or an appropriate transistor/MOSFET driver.
- Power the pump from a separate supply rated for its startup and stall current. A pump can cause resets and noisy sensor readings if its current shares an undersized controller supply.
- Check the relay module's input voltage and active-LOW or active-HIGH behaviour. Do not guess based on its appearance.
- Keep water away from the board, USB connector and exposed terminals. Place the electronics above the reservoir and use drip loops and strain relief.
- This guide covers low-voltage DC prototypes. Do not wire exposed mains voltage on a breadboard; use a properly enclosed, appropriately rated switching device and qualified installation.
- Provide a maximum runtime and a cooldown interval. A failed or disconnected sensor must not cause unlimited pumping.
Wiring A: Arduino Uno
This example uses A0 for the sensor and D7 for the relay input. The optional I²C display uses A4/SDA and A5/SCL on a classic Uno R3. The display is not required to make the pump-control sketch work.
| Connection | Arduino Uno |
|---|---|
| Sensor VCC | The voltage specified by the sensor module; 3.3 V is preferable when the module supports it and the output stays within the Uno's input range |
| Sensor GND | GND |
| Sensor analog output | A0 |
| Relay control input | D7 |
| Relay logic VCC / GND | According to the relay module instructions; use a compatible logic input |
| Optional I²C display SDA / SCL | A4 / A5 |
| Pump power | Separate low-voltage supply routed through the relay contacts or suitable driver |
For a typical DC pump relay circuit, the external pump supply positive connects to the relay COM terminal, relay NO connects to the pump positive lead, and the pump negative lead returns to that supply’s negative terminal. When the relay closes, the pump receives power. Confirm the contact ratings and relay terminal labels on your actual module; not every board uses identical labels.
The relay’s input side is a separate circuit from its switched contacts. Follow the relay module’s wiring diagram for logic power and ground. If the module uses a non-isolated input stage, the controller and relay input need a shared signal reference. Do not accidentally connect the pump supply through the Uno’s 5 V rail.
Arduino Uno code
Set the dry and wet calibration values after testing your own sensor. This example assumes a larger ADC value when the sensor is dry and a smaller value when it is wet. If your sensor behaves in the opposite direction, swap the calibration endpoints. The Arduino Uno R3’s default analog reading range is 0–1023.
The code uses hysteresis: watering starts below the lower threshold and stops only after the higher threshold is reached. It also limits each pump run and enforces a cooldown after a timeout.
const int MOISTURE_PIN = A0;
const int RELAY_PIN = 7;
// Replace these examples with measurements from your own sensor.
const int DRY_RAW = 800;
const int WET_RAW = 350;
const int START_WATER_BELOW = 30;
const int STOP_WATER_ABOVE = 45;
const unsigned long SAMPLE_MS = 2000;
const unsigned long MAX_PUMP_MS = 10000;
const unsigned long COOLDOWN_MS = 60000;
// Change this after testing your relay module.
const bool RELAY_ACTIVE_LOW = true;
bool pumpOn = false;
bool timedOut = false;
unsigned long pumpStartedAt = 0;
unsigned long lastPumpStoppedAt = 0;
unsigned long lastSampleAt = 0;
int moisturePercent = 0;
void setPump(bool on) {
pumpOn = on;
const int outputLevel = (on == RELAY_ACTIVE_LOW) ? LOW : HIGH;
digitalWrite(RELAY_PIN, outputLevel);
if (on) {
pumpStartedAt = millis();
} else {
lastPumpStoppedAt = millis();
}
}
int readMoisturePercent() {
const int raw = analogRead(MOISTURE_PIN);
// An ADC reading pinned to a rail can indicate a disconnected sensor or wiring fault.
if (raw <= 2 || raw >= 1021 || DRY_RAW == WET_RAW) return -1;
long percent = (long)(DRY_RAW - raw) * 100L / (DRY_RAW - WET_RAW);
percent = constrain(percent, 0, 100);
return (int)percent;
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
setPump(false);
lastPumpStoppedAt = millis();
}
void loop() {
const unsigned long now = millis();
if (pumpOn && now - pumpStartedAt >= MAX_PUMP_MS) {
setPump(false);
timedOut = true;
Serial.println("Pump stopped by maximum runtime; inspect the system.");
}
if (now - lastSampleAt >= SAMPLE_MS) {
lastSampleAt = now;
moisturePercent = readMoisturePercent();
Serial.print("Calibrated moisture: ");
Serial.print(moisturePercent);
Serial.println("%");
if (moisturePercent < 0) {
setPump(false);
Serial.println("Invalid calibration; pump forced OFF.");
return;
}
if (pumpOn && moisturePercent >= STOP_WATER_ABOVE) {
setPump(false);
timedOut = false;
} else if (!pumpOn && !timedOut &&
moisturePercent <= START_WATER_BELOW &&
now - lastPumpStoppedAt >= COOLDOWN_MS) {
setPump(true);
}
}
}The sample values in the sketch are examples, not universal sensor calibration. Test that the relay is OFF at startup and verify its active level before connecting a pump. The maximum-run latch requires you to inspect the cause rather than repeatedly starting the pump after a timeout; for a production build, add an explicit reset or supervised recovery procedure appropriate to the system.
Wiring B: ESP32 with MQTT monitoring
The ESP32 version uses the same sensor-and-relay concept, but its GPIOs are not 5 V tolerant. For an original ESP32 DevKit where GPIO34 is exposed and available, GPIO34 is an ADC1 input that can be used for the sensor. That pin number is not universal across ESP32-C3, ESP32-S3 and other development boards. Choose an ADC-capable pin from the exact board's pinout.
| Connection | Original ESP32 DevKit example |
|---|---|
| Sensor VCC | Sensor-approved supply; check output voltage |
| Sensor GND | ESP32 GND |
| Sensor analog output | GPIO34 / ADC1 on compatible original-ESP32 boards |
| Relay control input | GPIO26 in this example |
| Relay input supply and ground | According to the relay module specification |
| Pump contacts | Separate pump supply through rated relay contacts or driver |
| Network | 2.4 GHz Wi-Fi where supported by the board and network |
Do not connect a 5 V analog sensor output directly to an ESP32 GPIO. If the sensor output can exceed the board's input range, use a correctly designed divider or level-shifting circuit after checking the sensor and board documentation. The ESP32 ADC raw readings are not guaranteed to be perfectly linear or identical between units; calibrate using real measurements and use ADC settings appropriate for the chip.
ESP32 sketch with local control and MQTT telemetry
Install the PubSubClient library from the Arduino Library Manager. Enter your Wi-Fi and broker details locally. Use an authenticated MQTT broker on a trusted network; do not publish credentials in a public repository. The example publishes moisture percentage and pump state. It does not require an MQTT command to stop the pump.
Like the Uno version, the dry/wet endpoints below are placeholders. Adjust them for the exact sensor and soil. Confirm the relay's polarity before connecting the pump.
#include <WiFi.h>
#include <PubSubClient.h>
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "192.168.1.10";
const int MQTT_PORT = 1883;
const char* MQTT_USER = "YOUR_MQTT_USER";
const char* MQTT_PASSWORD = "YOUR_MQTT_PASSWORD";
const int MOISTURE_PIN = 34; // Original ESP32 example only; verify your board.
const int RELAY_PIN = 26;
const bool RELAY_ACTIVE_LOW = true;
// Replace calibration values with measured raw readings.
const int DRY_RAW = 3200;
const int WET_RAW = 1400;
const int START_WATER_BELOW = 30;
const int STOP_WATER_ABOVE = 45;
const unsigned long SAMPLE_MS = 2000;
const unsigned long MAX_PUMP_MS = 10000;
const unsigned long COOLDOWN_MS = 60000;
const unsigned long WIFI_RETRY_MS = 10000;
const unsigned long MQTT_RETRY_MS = 5000;
WiFiClient net;
PubSubClient mqtt(net);
bool pumpOn = false;
bool timedOut = false;
unsigned long pumpStartedAt = 0;
unsigned long lastPumpStoppedAt = 0;
unsigned long lastSampleAt = 0;
unsigned long lastWiFiAttempt = 0;
unsigned long lastMQTTAttempt = 0;
int moisturePercent = -1;
void setPump(bool on) {
pumpOn = on;
digitalWrite(RELAY_PIN, (on == RELAY_ACTIVE_LOW) ? LOW : HIGH);
if (on) pumpStartedAt = millis();
else lastPumpStoppedAt = millis();
}
int readMoisturePercent() {
const int raw = analogRead(MOISTURE_PIN);
// An ADC reading pinned to a rail can indicate a disconnected sensor or wiring fault.
if (raw <= 2 || raw >= 4093 || DRY_RAW == WET_RAW) return -1;
long percent = (long)(DRY_RAW - raw) * 100L / (DRY_RAW - WET_RAW);
return (int)constrain(percent, 0, 100);
}
void maintainWiFi(unsigned long now) {
if (WiFi.status() == WL_CONNECTED) return;
if (now - lastWiFiAttempt < WIFI_RETRY_MS) return;
lastWiFiAttempt = now;
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void maintainMQTT(unsigned long now) {
if (WiFi.status() != WL_CONNECTED || mqtt.connected()) return;
if (now - lastMQTTAttempt < MQTT_RETRY_MS) return;
lastMQTTAttempt = now;
mqtt.connect("solderhub-garden-controller", MQTT_USER, MQTT_PASSWORD);
}
void publishState() {
if (!mqtt.connected()) return;
char payload[16];
snprintf(payload, sizeof(payload), "%d", moisturePercent);
mqtt.publish("solderhub/garden-01/moisture_percent", payload, true);
mqtt.publish("solderhub/garden-01/pump_state", pumpOn ? "ON" : "OFF", true);
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
setPump(false);
lastPumpStoppedAt = millis();
analogReadResolution(12);
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setSocketTimeout(2);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void loop() {
const unsigned long now = millis();
// Safety is local; a cloud or broker connection is not required.
if (pumpOn && now - pumpStartedAt >= MAX_PUMP_MS) {
setPump(false);
timedOut = true;
Serial.println("Pump stopped by maximum runtime; inspect before reset.");
}
maintainWiFi(now);
if (WiFi.status() == WL_CONNECTED) {
maintainMQTT(now);
if (mqtt.connected()) mqtt.loop();
}
if (now - lastSampleAt >= SAMPLE_MS) {
lastSampleAt = now;
moisturePercent = readMoisturePercent();
if (moisturePercent < 0) {
setPump(false);
Serial.println("Invalid calibration; pump forced OFF.");
} else if (pumpOn && moisturePercent >= STOP_WATER_ABOVE) {
setPump(false);
timedOut = false;
} else if (!pumpOn && !timedOut &&
moisturePercent <= START_WATER_BELOW &&
now - lastPumpStoppedAt >= COOLDOWN_MS) {
setPump(true);
}
Serial.print("Moisture: ");
Serial.print(moisturePercent);
Serial.print("%, pump: ");
Serial.println(pumpOn ? "ON" : "OFF");
publishState();
}
}This is a starting point for a supervised low-voltage prototype, not a finished unattended irrigation controller. Network calls can temporarily delay loop execution, so do not rely on this sketch alone for a safety-critical pump, flood prevention or livestock watering. For deployment, consider an independent hardware cutoff, reservoir-low switch, flow feedback, sensor-disconnect detection, watchdog and a controller state machine designed for the consequences of a failed sensor or blocked pump.
Calibrate the Sensor Instead of Trusting a Percentage
The number displayed by analogRead is an ADC measurement, not a standardized soil-moisture percentage. The sensor’s output changes with the module, supply, soil composition, salinity, placement and ageing. The simple percentage in the sketches maps two measured endpoints to 0–100; it does not measure volumetric water content.
Use a repeatable calibration process:
- Read the dry condition. Place the probe at the intended depth in the same potting mix and allow the reading to settle. Record several raw readings.
- Read a thoroughly watered condition. Water the soil, allow excess water to drain, and measure again at the same depth and orientation.
- Choose endpoints. Use a representative dry value for DRY_RAW and a representative wet value for WET_RAW. Average several readings or use a median to reduce noise.
- Test intermediate conditions. Check whether the percentage moves in the expected direction as the soil dries. Do not assume all sensors produce lower raw values when wet.
- Set thresholds for the plant and soil. Start watering at a lower calibrated percentage and stop at a higher one. Tune these values based on observation rather than using a universal threshold.
- Recalibrate after changes. Different soil, fertiliser, probe depth or sensor replacement can shift the readings.
Seal the cut edge. The top edge of most capacitive probes is bare fibreglass where the board was cut. Water wicks into it, the reading drifts, and the board eventually fails. Coat the edge and the line where the electronics start with clear nail varnish, epoxy or heat-shrink before the first use, and push the probe in only up to the marked line.
Capacitive probes usually avoid the exposed electrodes that make resistive sensors prone to corrosion, but the protective coating on a capacitive sensor can still degrade. Keep the electronics out of the soil and avoid leaving the sensor powered continuously if the module design or its supplier recommends intermittent sampling.
Hysteresis, Maximum Run Time and Pump Protection
If the pump turns on at 30% and turns off at 31%, readings that bounce around the threshold may cause repeated switching. Hysteresis prevents this: start at a lower moisture threshold and stop at a higher one. The gap between them depends on the calibration stability and how much water the soil needs to absorb.
A maximum runtime is also essential. The controller cannot assume that the soil became wet simply because it activated the relay. A disconnected sensor, empty reservoir, blocked tube or failed pump can prevent the expected change. If the maximum run time is reached, stop the output and require a deliberate inspection/recovery step.
For a stronger design, add:
- A float switch or other reservoir-low detection.
- A flow sensor or current monitoring to detect a pump that runs without moving water.
- A minimum off time to prevent rapid relay cycling.
- Debounced and validated readings; reject impossible or disconnected-sensor values.
- A dry-run and maximum daily pump budget suited to the pump and reservoir.
- A safe power-on state that leaves the pump OFF until a valid sensor reading is obtained.
MQTT and Home Assistant: Monitoring, Not a Safety Dependency
The ESP32 example publishes two retained topics:
- solderhub/garden-01/moisture_percent
- solderhub/garden-01/pump_state
Use unique topic names for each controller. A Home Assistant MQTT sensor can display the moisture percentage, and a binary sensor or template can represent the pump state. The retained value makes a dashboard easier to initialize after reconnecting, but a retained message is only the last published report; it is not proof that the relay contact or pump physically followed the command.
Keep network monitoring separate from pump control. If the broker restarts, the router loses power or a dashboard is unavailable, the local threshold and timeout logic should still stop the pump. Do not automatically turn the pump on because an old retained MQTT command reappears after a reconnect. Authenticate the broker, restrict network access and use TLS when your environment supports it.
See the ESP32 MQTT tutorial for broker basics, MQTT with ESP32 and Home Assistant for showing the readings on a dashboard, and the ESP32 ADC guide for why the sensor must be on an ADC1 pin when Wi-Fi is on.
Testing Checklist
Test the low-voltage circuit with the pump disconnected first, then perform a short supervised pump test with water available. Confirm:
- The relay defaults to the pump-OFF state at boot and reset.
- Dry and wet calibration values produce sensible, correctly ordered percentages.
- The pump starts only below the start threshold.
- The pump stops at the stop threshold and at the maximum runtime.
- Test a disconnected sensor explicitly. The examples force the pump OFF for ADC rail readings, but some sensor faults produce plausible intermediate voltages and need additional fault detection before unattended use.
- The cooldown prevents rapid restart after stopping or timeout.
- The supply does not brown out the controller when the pump starts.
- MQTT loss does not stop local control logic or leave the pump running indefinitely.
- The tubing, reservoir, pump polarity and water path do not leak.
Never leave a first test unattended. Inspect the sensor, pump, relay, reservoir and wiring regularly. A remote dashboard is useful, but it cannot replace checking the physical water system.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Reading barely changes between dry and wet | Clone v1.2 board with an NE555 timer chip, which needs 5 V | Check the chip marking: a TLC555 works at 3.3 V, an NE555 doesn't. Power that board from 5 V (with a divider on the output for an ESP32) or buy a board with the TLC555 |
| Reading stays wet long after the soil dries | Missing 1 MΩ bleed resistor (R4) on some clones | Fit a 1 MΩ resistor from the output to GND, or use another module |
| Readings drift over weeks | Water in the unsealed cut edge, or salt build-up | Seal the top edge; recalibrate; clean the probe |
| ESP32 reading always 0 or junk once Wi-Fi connects | Sensor on an ADC2 pin | Move it to GPIO 32–39 (ADC1) |
| Board resets when the pump starts | Pump sharing the controller's supply | Separate pump supply, common ground, 470 µF capacitor across the pump supply |
| Relay clicks on at power-up | Active-LOW relay and pin floating at boot | Set RELAY_ACTIVE_LOW correctly and write the OFF level before pinMode(); add a pull-up on the input |
| Pump runs but no water arrives | Air lock, empty reservoir, kinked tube | Prime the pump, add a float switch, check the tubing |
| Pump stops after 10 s every time | MAX_PUMP_MS reached before the soil got wet | Increase it carefully, or water in several shorter pulses with a wait between them |
Make the sensor last longer by powering it only while you read it. A capacitive probe draws only a few milliamps, so a spare GPIO can supply it: set the pin HIGH, wait about 100 ms for the reading to settle, read, then set it LOW.
FAQ
Capacitive or resistive soil sensor? Capacitive. The bare-metal resistive probes corrode within weeks because current flows through the soil.
How deep should the sensor go? Into the root zone, up to the line marked on the probe, and at the same depth every time you calibrate.
Can I run it on batteries? Yes with care: power the sensor from a GPIO, put the board to sleep between readings, and size the battery for the pump, which uses far more energy than the electronics. The ESP32 deep sleep guide covers the electronics side.
How often should it check the soil? Every few minutes is plenty; soil moisture changes slowly, and checking less often extends sensor life.
Can one controller water several plants? Yes: one sensor and one pump or solenoid valve per zone, each with its own thresholds and run limit. An 8-channel relay board handles the switching.
Is there a phone-app version? See the ESP32 plant watering project with Blynk.
Official references
- Arduino Uno documentation
- UNO R4 board documentation
- Arduino-ESP32 ADC API
- Arduino-ESP32 GPIO API
- Arduino-ESP32 Wi-Fi API
- PubSubClient library
Related guides: Arduino Uno pinout · ESP32 pinout · ESP32 ADC pins · Install Mosquitto MQTT
The result is one project with two controller choices: use the Uno for a local, simple build, or use the ESP32 when Wi-Fi telemetry is useful. In both cases, calibrate the sensor, use a correctly rated pump driver, limit runtime and keep the safety decisions local.



