Practical Bench / IoT & Security · Intermediate · 120 min
Smart irrigation with a soil moisture sensor
Calibrate a capacitive soil sensor, switch a 5 V pump through a relay with hysteresis and a fail-safe timer, and read the state over Wi-Fi as JSON.
Why it matters
Precision irrigation saves water and labour for Indian farmers. The same sensing, decision and fail-safe pattern is used in greenhouse and city-park systems.
Toy or everyday hack
Use a small USB water pump from a toy fountain or aquarium kit
Safety
- Use only low-voltage (5 V) pumps. Never switch mains 230 V in this practical.
- Keep the ESP32, relay and wiring away from splashes. Put the electronics in a box above the water level.
- Fit the fail-safe timer before the first pump run: an empty tank can burn a pump in seconds.
- Do not put the sensor circuit board in water: only the marked probe area goes in the soil.
Parts list
| Part | Qty | Note |
|---|---|---|
| ESP32 DevKit | 1 | |
| Capacitive soil moisture sensor (analog) | 1 | Prefer capacitive: resistive probes corrode |
| 5 V relay module | 1 | Check whether it is active-LOW |
| 5 V mini submersible pump + tube | 1 | From a toy fountain or aquarium kit |
| Pot with soil + glass of water | 1 | |
| USB power bank or 5 V supply for the pump | 1 | Separate from the ESP32 if possible |
| 1N4007 diode | 1 | Across the pump if the relay board has none |
Tools and equipment
Connections
| From | To | Note |
|---|---|---|
| Sensor VCC / GND | ESP32 3V3 / GND | |
| Sensor AOUT | ESP32 GPIO34 | ADC1 pin, works with Wi-Fi |
| Relay VCC / GND | ESP32 VIN (5 V) / GND | |
| Relay IN | ESP32 GPIO26 | |
| Relay COM | Power bank 5 V + | |
| Relay NO | Pump + | |
| Pump − | Power bank GND | Add 1N4007 across the pump |
What you should see
Raw value falls as water content rises, because water raises the capacitance of the probe. The logbook converts each reading to a percentage between your own two reference points. Two different thresholds (start and stop) stop the pump from chattering on and off around one value.
Step by step
- Wire the sensor and relay. Leave the pump disconnected for the first test; the relay should click.
- Upload the sketch with your Wi-Fi name and password. Note the IP address printed in the Serial Monitor.
- Calibrate: with the sensor in air, read the raw value; in a glass of water (up to the marked line), read again. Enter both in the logbook as rows 1 and 2, then add readings in dry, slightly damp and wet soil.
- Put your two calibration numbers into RAW_DRY and RAW_WET in the sketch and re-upload.
- Connect the pump. Place the tube above a pot or container. Let the system run: when moisture falls below the start level, the pump runs until the stop level is reached.
- Open http://<ESP32-IP>/ in a browser on the same Wi-Fi. You should see a small JSON text with moisture and pump state.
- Test the fail-safe: lift the tube out of the water so that the soil never gets wetter. The pump must stop by itself after the maximum run time.
Challenge: Make the ESP32 sleep between readings (deep sleep for 10 minutes) and estimate the battery life with the battery calculator in Tools.
Code (ESP32 DevKit, Arduino IDE)
Check pin numbers against your board. Test the sketch on your own hardware before a class demo.
// Practical 2 - Soil moisture + automatic irrigation + JSON status page (ESP32)
#include <WiFi.h>
#include <WebServer.h>
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";
const int SOIL_PIN = 34; // ADC1 pin: ADC2 does not work while Wi-Fi is on
const int RELAY_PIN = 26;
const bool RELAY_ACTIVE_LOW = true; // most relay boards switch ON with a LOW signal
int RAW_DRY = 2800; // 1) sensor in air -> measure and replace
int RAW_WET = 1200; // 2) sensor in water -> measure and replace
const int START_BELOW = 35; // pump ON when moisture < 35 %
const int STOP_ABOVE = 60; // pump OFF when moisture > 60 % (hysteresis)
const uint32_t MAX_PUMP_MS = 20000; // fail-safe: never run longer than 20 s
const uint32_t COOLDOWN_MS = 60000; // after a fail-safe stop, wait 60 s
WebServer server(80);
bool pumpOn = false;
int moisturePct = 0;
uint32_t pumpStart = 0, blockedUntil = 0;
int readPct() {
long sum = 0;
for (int i = 0; i < 16; i++) { sum += analogRead(SOIL_PIN); delay(5); } // average 16 samples
int pct = map(sum / 16, RAW_DRY, RAW_WET, 0, 100);
return constrain(pct, 0, 100);
}
void setPump(bool on) {
pumpOn = on;
if (on) pumpStart = millis();
digitalWrite(RELAY_PIN, (on ^ RELAY_ACTIVE_LOW) ? HIGH : LOW);
}
void handleStatus() {
String j = "{\"moisture\":" + String(moisturePct) + ",\"pump\":" + (pumpOn ? "true" : "false") + "}";
server.send(200, "application/json", j);
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
setPump(false);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) { delay(300); Serial.print('.'); }
Serial.println(WiFi.localIP());
server.on("/", handleStatus);
server.begin();
}
void loop() {
static uint32_t t = 0;
if (millis() - t > 2000) {
t = millis();
moisturePct = readPct();
if (!pumpOn && moisturePct < START_BELOW && millis() > blockedUntil) setPump(true);
if (pumpOn && moisturePct > STOP_ABOVE) setPump(false);
if (pumpOn && millis() - pumpStart > MAX_PUMP_MS) { // fail-safe: empty tank / broken sensor
setPump(false); blockedUntil = millis() + COOLDOWN_MS;
Serial.println("FAIL-SAFE: pump stopped");
}
Serial.printf("moisture=%d%% pump=%s\n", moisturePct, pumpOn ? "ON" : "OFF");
}
server.handleClient();
}Readings logbook
Type your measured values. Calculated columns and the analysis update as you type, and your entries are saved in this browser.
If it does not work
| Symptom | Likely cause and fix |
|---|---|
| Raw value jumps around | Average more samples, keep wires short, and avoid running the sensor wire next to the pump wire. |
| WiFi connects but readings freeze | You used an ADC2 pin (GPIO 0, 2, 4, 12 to 15, 25 to 27). Use ADC1 pins (32 to 39) when Wi-Fi is on. |
| Relay works backwards | Your board is active-HIGH. Change RELAY_ACTIVE_LOW to false. |
| Pump never stops | Soil too dry to reach the stop level, or sensor not in soil. This is exactly what the fail-safe timer is for. |