Build Project

Sensor Projects

ESP32 Soil Moisture: Relative Sensor Index

Read a defined SEN0193 sensor on classic ESP32, record your own references and display a relative 0–100 index without claiming water-content percentage.

BeginnerAges 12+Setup time variesParts cost variesLow-voltage measurement lesson — unverified hardware
Relative soil-sensor index logical overview; not a physical layout, photograph or recorded measurement
Jump to a section

What You Will Build

A Serial relative-index display for an identified DFRobot SEN0193 sensor, plus green/yellow/red LEDs. The index locates a reading between your air/water references; it is not percent water, relative humidity, watering advice or an automatic pump controller. The buzzer and incomplete cloud/pump alternatives are not supported here. The overview is a logical illustration, not a photograph or recorded result.

Before You Start

Classic ESP32-WROOM-32/32E DevKit with free GPIO34 (ADC1 input only), Arduino-ESP32 3.3.2 review baseline, Arduino IDE 2.x and built-in ADC functions only. Not a latest-release claim or a pin map for S3/C3/C5. No external sensor library is needed for this explicit recorded-point calculation.

Parts

Wiring

Power the identified module from a separate regulated 5.0 V supply, ±5%, not from a GPIO. Its documented supply range is 3.3–5.5 V and output envelope is 0–3.0 V. USB powers the ESP32; never join the two positive supply outputs. Module AOUT feeds 15 kΩ (1%) then GPIO34; 10 kΩ (1%) and 100 nF connect this node to GND. Grounds are common. This divider scales the signal, not the module supply. Power both sides together while connected; power off USB and module supply before rewiring. Never connect a bare electrode or unknown output directly to GPIO34.

Logical DFRobot Gravity SEN0193 capacitive soil sensor circuit: separate regulated 5 V, common ground, 15k/10k divider and 100 nF at GPIO34; not physical pin order or tested hardware.

Open wiring diagram full size

  1. 1

    Switch USB and module supply off. Identify exact module, rail and connector labels.

  2. 2

    Module +/VCC → external regulated 5.0 V (±5%); module −/GND → common ESP32/external-supply GND. Never join positive rails. Keep sensor electronics and connector above the marked immersion limit.

  3. 3

    Module A/AOUT → 15 kΩ → GPIO34 node; 10 kΩ and 100 nF separately node → GND. Never bypass the divider.

  4. 4

    GPIO25/26/27 each → its own 330 ohm resistor → green/yellow/red LED anode; all cathodes → GND. GPIO32 unused; no buzzer.

  5. 5

    Check logical diagram before powering. Serial 115200; first leave the record-enable flag false and inspect raw counts/pin-mV diagnostics.

  6. 6

    Record both stable endpoints and conditions with this same chain before enabling calculation. Invalid/outside-interval signals deliberately give no calculated result.

Wiring Reference

SignalESP32 PinDirectionNotes
Module + / VCCNo GPIO; external regulated 5.0 V (±5%)SupplyIdentified module 3.3–5.5 V supply; distinct from signal rating.
Module − / GNDGNDCommon returnDivider bottom/capacitor share ground.
Module A / AOUT15 kΩ → GPIO34; 10 kΩ and 100 nF node → GNDADC1 inputDivided 0–3.0 V documented envelope; GPIO34 has no internal pull resistor.
Green / yellow / red LEDsGPIO25 / GPIO26 / GPIO27OutputsEach through separate 330 ohm to anode; cathodes GND. OFF if invalid/unreferenced.

Libraries and Setup

  • Arduino-ESP32 3.3.2 built-in ADC APIsNo DFRobot library or EEPROM dependency. Explicit recorded-point calculation, not library defaults.

Configure the Example

With REFERENCES_RECORDED=false, record repeated stable ADC_pin_mV_est windows in air as AIR_PIN_MV. Briefly place only the sensing portion in water, no further than the manufacturer's marked limit; electronics/connector stay dry. Record WATER_PIN_MV using the same board, supply, divider and attenuation. Do not copy Arduino Uno counts. Air voltage must exceed water voltage by at least 100 mV before enabling the flag. The separation and 20 mV short-window noise limits are lesson screening choices, not manufacturer accuracy specifications.

relative_index = 100×(Vair−Vpin)/(Vair−Vwater). This dimensionless 0–100 scale is NOT volumetric/gravimetric water percentage, %RH or a plant-water requirement. Outside-reference readings are withheld, not clipped. Soil composition, insertion depth, packing, salinity and temperature can change response. Record those conditions. Air/water endpoint adjustment alone does not validate a soil-water-content model.

LEDs show arbitrary lower/middle/upper bands (<33, 33–<67, ≥67); they are not watering thresholds. No buzzer, relay, pump or cloud logger is implemented. Such extensions need separate complete circuits and validation.

Code

Install the libraries above and match the configuration and wiring before uploading.

esp32-soil-moisture-monitor.ino
#include <Arduino.h>
#include <math.h>
// Classic ESP32-WROOM DevKit; Arduino-ESP32 3.3.2 review baseline.
constexpr uint8_t SENSOR_PIN = 34; // ADC1 input only; no internal pull resistor.
// AOUT -- 15k (1%) -- GPIO34 -- 10k (1%) -- GND; 100 nF GPIO34 to GND.
// Raw and mV are separate conversions, averaged over the same short window.
float rawMean = 0, pinMv = 0;
bool readWindow() {
  uint32_t rawSum = 0, mvSum = 0, minMv = 100000, maxMv = 0;
  bool rails = false;
  for (int i = 0; i < 32; ++i) {
    uint16_t raw = analogRead(SENSOR_PIN);
    uint32_t mv = analogReadMilliVolts(SENSOR_PIN);
    rawSum += raw; mvSum += mv;
    if (raw <= 16 || raw >= 4079) rails = true;
    if (mv < minMv) minMv = mv;
    if (mv > maxMv) maxMv = mv;
    delay(5);
  }
  rawMean = rawSum / 32.0f; pinMv = mvSum / 32.0f;
  // Lesson screening, not electrical protection or sensor-health proof.
  return !rails && minMv >= 250 && maxMv <= 2200 && maxMv - minMv <= 20;
}

constexpr uint8_t LED_GREEN = 25, LED_YELLOW = 26, LED_RED = 27;
constexpr bool REFERENCES_RECORDED = false;
constexpr float AIR_PIN_MV = 0.0f, WATER_PIN_MV = 0.0f;
void indicatorsOff() {
  digitalWrite(LED_GREEN, LOW); digitalWrite(LED_YELLOW, LOW); digitalWrite(LED_RED, LOW);
}
bool validReferences() {
  return REFERENCES_RECORDED && isfinite(AIR_PIN_MV) && isfinite(WATER_PIN_MV) &&
    WATER_PIN_MV >= 250 && AIR_PIN_MV <= 2200 && AIR_PIN_MV - WATER_PIN_MV >= 100;
}
void setup() {
  Serial.begin(115200);
  analogReadResolution(12);
  analogSetPinAttenuation(SENSOR_PIN, ADC_11db);
  digitalWrite(LED_GREEN, LOW); digitalWrite(LED_YELLOW, LOW); digitalWrite(LED_RED, LOW);
  pinMode(LED_GREEN, OUTPUT); pinMode(LED_YELLOW, OUTPUT); pinMode(LED_RED, OUTPUT);
  indicatorsOff();
  Serial.println("SEN0193 relative index; NOT water-content percent or watering advice");
}
void loop() {
  indicatorsOff();
  bool valid = readWindow();
  Serial.printf("raw_counts=%.1f ADC_pin_mV_est=%.1f\n", rawMean, pinMv);
  if (!valid) Serial.println("INVALID_SIGNAL: rail, range or short-window noise; index withheld");
  else if (!validReferences()) Serial.println("REFERENCE_REQUIRED: record air/water pin mV; index withheld");
  else if (pinMv < WATER_PIN_MV || pinMv > AIR_PIN_MV)
    Serial.println("OUTSIDE_REFERENCE_INTERVAL: index withheld, not clamped");
  else {
    float index = 100.0f * (AIR_PIN_MV - pinMv) / (AIR_PIN_MV - WATER_PIN_MV);
    if (!isfinite(index)) Serial.println("INVALID_CALCULATION: index withheld");
    else {
      Serial.printf("relative_index=%.1f / 100; NOT percent water\n", index);
      // Arbitrary display bands, not plant-specific watering thresholds.
      if (index >= 67) digitalWrite(LED_GREEN, HIGH);
      else if (index >= 33) digitalWrite(LED_YELLOW, HIGH);
      else digitalWrite(LED_RED, HIGH);
    }
  }
  delay(5000);
}

How the Code Works

All LEDs start OFF. REFERENCES_RECORDED defaults false and both endpoints zero. Finite/range/separation checks precede division; outside-interval readings are withheld, not clamped. Bands at 33/67 are arbitrary display practice, not watering thresholds. Screening cannot establish sensor health: disconnected probes or stuck signals may look plausible.

Expected Output

Serial prints raw_counts/ADC_pin_mV_est with REFERENCE_REQUIRED and LEDs OFF until references are entered. In-interval signals print relative_index / 100 and light one band; invalid/outside-reference signals withhold the index and turn LEDs OFF. These are prospective message types, not recorded measurements or proof of calibration.

Troubleshooting

  • No calculated result Read the named state; record both stable endpoints with the same circuit. Zero defaults deliberately fail; enabling the flag alone is insufficient.
  • INVALID_SIGNAL Power off; check module, common ground, divider and GPIO34. Rail/zero, outside 250–2200 mV or >20 mV within-window span is rejected. Do not force a result.
  • OUTSIDE interval Do not clamp to 0/100. Recheck sensor, depth, supply and references. A relative index is not water-content calibration.
  • Plausible but stuck reading A disconnected electrode, floating module input or stuck signal may look plausible. Use controlled references and independent instruments; software cannot prove connection/health.

Checks to Perform on Your Build

  • Documentation/API and numerical review only; no compilation or hardware/calibration result supplied.
  • Identify actual module and verify rail/interface with suitable instruments before trusting output.
  • Record reference conditions and unedited diagnostics separately from expected messages.
  • Check rejected readings withhold the index and turn all three LEDs OFF.

Practical Design Notes

Raw counts are uncalibrated 12-bit codes, not volts or a physical quantity. analogReadMilliVolts uses the core ADC calibration path to estimate voltage at the divided pin; it is not independent system calibration or a voltmeter accuracy guarantee. Raw and mV use separate conversions. Classic ESP32 at 11 dB has a documented measurement range of about 150–3100 mV, distinct from 3.3 V logic. The sketch accepts only 250–2200 mV and rejects rail samples or more than 20 mV span within 32 samples. These are conservative lesson screening choices, not manufacturer sensor specifications. Slow drift and plausible wiring faults can pass.

Vpin=Vout×Rb/(Rt+Rb). For Rt=15 kΩ and Rb=10 kΩ, ratio=0.4 nominal; with 1% resistors the largest ratio is 10.1/(14.85+10.1)=0.40481. Documented 3.0 V output gives at most 1.2145 V. A 5.0 V supply at +5% gives 5.25 V; even output-to-supply pass-through gives only 2.1253 V at the ADC. At the module maximum 5.5 V, the bound is 2.2265 V, below the classic 11 dB range ceiling around 3.1 V; the sketch rejects above 2.2 V. This bounded calculation is not protection from arbitrary supplies, miswiring or transients. The divider also pulls a disconnected signal wire low, but does not prove electrode health. Nominal module voltage is 2.5×pin voltage; resistor-ratio uncertainty alone is about ±1.2%, before ADC, loading and sensor errors. Endpoint records are ADC-pin values from this complete chain; changing any part invalidates them.

Upgrade Ideas

  • Assess uncertainty with a separate check/reference and recorded evidence; none is supplied here.

FAQs

Does this establish sensor accuracy?

No. ADC calibration and two recorded endpoints do not independently validate accuracy, drift or sample preparation.

Does rejection detect every disconnected sensor?

No. It rejects obvious rail/range/noise problems, but a plausible voltage can still be faulty.

Review, Testing, and References

Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-11-17. Reviewed: wiring logic, Arduino code structure, beginner safety, and learning sequence.

Educational level: Beginner. Estimated completion time: Setup time varies. This project is for learning and prototyping; production or unattended hardware needs additional engineering review.