Hardware-Oriented
Detection of moisture levels in (1) Air, (2) Dry Soil, and (3) Wet Soil using a moisture sensor interfaced with ESP32
Aim
To design and implement a moisture detection system using a moisture sensor interfaced with an ESP32esp32A low-cost, low-power system-on-a-chip microcontroller with integrated Wi-Fi and Bluetooth capabilities, widely used by students and engineers for IoT applications and sensor data acquisition. microcontroller to measure moisture levels in air, dry soil, and wet soil, and to log the measured data along with timestamps to Google Sheets for analysis using Wi-Fi connectivity.
Apparatus & Software
Hardware Components:
- ESP32 Microcontroller
- Soil Moisture Sensorsoil moisture sensorA device that estimates the volumetric water content in soil, commonly by measuring the dielectric constant or the electrical resistance between two embedded conductive electrodes. Module
- USB Cable, Jumper Wires
- Breadboard
Software and Tools:
- Computer or Laptop
- Arduino IDE with ESP32 Board Support Package
- Google Sheets
- Active Internet Connection (Wi-Fi)
Theory
1.1 Principle of Soil Moisture Sensing
Soil moisture sensors measure the volumetric water content (VWC) of a medium by exploiting the change in electrical properties caused by the presence of water. The most common low-cost modules operate on the resistive sensing principle: two exposed conductive probes are inserted into the medium, and the sensor measures the electrical resistance between them. Pure water is a poor conductor, but soil water contains dissolved ions (electrolytes) that make it significantly conductive. As moisture increases, ionic concentration rises and inter-probe resistance falls.
The relationship between volumetric water content and bulk electrical conductivity is empirically approximated by the linear mixing model:
where is the conductivity of soil water, is the conductivity of solid particles, is the conductivity of air ( 0), is the volumetric water content, and is the air-filled porosity. For the resistive probe sensor this simplifies to the empirical observation: for a fixed soil composition.
The sensor module includes a voltage divider in which acts as one resistive element. The output voltage at the analog output pin is:
As moisture increases, decreases and rises. The onboard LM393 comparator compares against a threshold set by the potentiometer, generating the binary digital output (DO):
1.2 ESP32 ADC Interfacing and Signal Acquisition
The ESP32 reads the sensor's analog output via its built-in 12-bit SAR ADC, mapping the input range 0–3.3 V to digital codes 0–4095:
The theoretical voltage resolution per LSB is:
A two-point calibration maps raw ADC readings to a normalized moisture percentage:
where is the code in air (minimum moisture reference) and is the code in fully saturated soil (maximum moisture reference).
1.3 Probe Degradation and Measurement Artefacts
A fundamental limitation of resistive moisture sensors is electrolytic corrosion of the probe electrodes. When DC voltage is applied continuously across the probes in a conductive medium, electrolysis occurs — the anode oxidises and the cathode reduces dissolved ions, degrading the probe surface over time and introducing measurement drift. The electrolytic current density at the probe surface is:
To minimise corrosion, firmware implementations apply voltage to the probes only during sampling (pulsed excitation), keeping the duty cycle low. Additionally, ionic conductivity increases approximately 2% per °C with temperature, meaning moisture readings will appear higher at elevated temperatures for the same actual water content, requiring temperature compensation for precision applications.
1.4 Wi-Fi Connectivity and Cloud Data Logging
The ESP32 connects to a Wi-Fi network in Station (STA) mode using the 802.11 b/g/n protocol. After DHCP-based IP assignment, the device issues HTTP GET requests to a Google Apps Script web application, encoding the sensor reading as URL query parameters:
The Apps Script endpoint appends each incoming record as a new timestamped row in Google Sheets. The total round-trip logging latency is:
Under normal conditions, lies between 300 ms and 2 s. The logging interval must satisfy to prevent request queuing and data loss. The complete IoT data pipeline is: Moisture Sensor → ESP32 ADC/GPIO → Wi-Fi AP → Internet → Google Apps Script → Google Sheets, forming a complete end-to-end IoT sensing and cloud logging system.
Pre-Lab / Circuit Diagram
Circuit Connections:
Note: A circuit diagram is not available for this experiment. Please follow the connection details below.
- VCC → ESP32 3.3V or 5V
- GND → ESP32 GND
- AO (Analog Output) → ESP32 ADC Pin (e.g., VP/36)
- DO (Digital Output) → Optional / Not Used
Procedure
- Connect the ESP32 and the soil moisture sensor module on a breadboard.
- Connect the ESP32 to a computer using a USB cable and open the Arduino IDE.
- Select the appropriate ESP32 board and COM port, then execute the ESP32 program code.
- Upload the program to the ESP32 and open the Serial Monitor to observe the moisture values obtained from the sensor.
- Place the moisture sensor in different conditions, namely air, dry soil, and wet soil, and note the corresponding sensor readings.
- Create a Google Sheet and open the Apps Script editor from the Extensions menu.
- Execute the required function and deploy it as a web application.
- Enter the generated web application URL and Wi-Fi credentials in the ESP32 program and upload the updated code.
Simulation / Execution
Arduino IDE Code:

Arduino IDE Code (Part 1)

Arduino IDE Code (Part 2)
Google Apps Script Code:

Google Apps Script Code
Observations
- The Serial Monitor displayed real-time moisture sensor readings obtained from the soil moisture sensor interfaced with the ESP32.
- Distinct variations in sensor readings were observed when the sensor was exposed to air, dry soil, and wet soil, indicating different moisture levels.
- The moisture sensor exhibited lower readings in air, moderate readings in dry soil, and higher readings in wet soil, demonstrating its sensitivity to moisture content.
- The ESP32 successfully connected to the configured Wi-Fi network and transmitted the moisture sensor data to Google Sheets.
- Each moisture sensor reading corresponding to air, dry soil, and wet soil was logged in Google Sheets along with the appropriate timestamp for further analysis.
- The Google Sheets link containing the logged moisture sensor data is attached here for reference: Google Sheets Data

Serial Monitor Output Showing Analog and Digital Rain Sensor Values

Google Sheets Showing Logged Data with Timestamp
Calculations (Not Applicable)
This section is not required for this experiment.
Results & Analysis
The IoT-based moisture detection system using a soil moisture sensor interfaced with an ESP32 microcontroller was successfully designed and implemented. The moisture sensor provided real-time readings corresponding to different environmental conditions, namely air, dry soil, and wet soil.
Distinct variations in sensor values were observed for each condition, and these readings were displayed in real time on the Serial Monitor, confirming correct sensor operation, interfacing, and data acquisition by the ESP32.
The ESP32 successfully connected to the configured Wi-Fi network and transmitted the moisture sensor data to Google Sheets using the Google Apps Script. Each moisture reading corresponding to air, dry soil, and wet soil was logged along with the appropriate timestamp and updated automatically in the Google Sheet.
Limitations:
- Electrolysis: DC current flow degrades the probe electrodes used in resistive sensors over time.
- Soil Contact: Inconsistent contact between soil and probe can lead to fluctuating readings.
- Salt Content: High salinity in soil increases conductivity, which may be misinterpreted as higher moisture.
Conclusion
The experiment effectively demonstrated real-time moisture monitoring and reliable cloud-based data logging, thereby fulfilling the objective of integrating sensing, data processing, and wireless communication using an IoT-based approach.
Post-Lab / Viva Voce
Note: The following questions are of medium to hard difficulty and are application- and concept-based.
- Q: The soil moisture sensor's analog output voltage increases as moisture increases, yet the raw ESP32 ADC reading also increases. Explain the circuit reason for this, and why the relationship is not perfectly linear.
A: The sensor uses a voltage divider where is in series with . . As moisture increases, decreases, increasing and hence the ADC code. Non-linearity arises because the voltage divider equation is hyperbolic (), not linear. Additionally, ionic conductivity varies non-linearly with volumetric water content, soil texture, compaction, and dissolved salt concentration. - Q: Why do resistive soil moisture sensors degrade faster than capacitive sensors? What physical mechanism is responsible, and how can firmware mitigate this?
A: Resistive sensors apply a continuous DC voltage across bare metal probes in conductive soil-water electrolyte, driving electrolysis: the anode undergoes oxidative corrosion and the cathode undergoes reductive ion deposition, shifting the baseline resistance irreversibly. Capacitive sensors use AC excitation and measure dielectric permittivity without DC current flow, avoiding this entirely. Firmware mitigation: pulsed excitation — applying supply voltage only for a few milliseconds during each ADC sample — drastically reduces average electrolytic current and slows corrosion. - Q: A student calibrates the sensor: (air), (saturated soil). For , compute the moisture percentage. What does a negative result imply?
A: Moisture (%) = . A negative percentage occurs if , meaning the reading exceeds the dry-air reference. This signals a calibration error — the reference was recorded incorrectly (sensor not fully dried), or sensor drift has shifted the baseline. Recalibration is required. - Q: The ESP32 ADC has known nonlinearity near 0 V and 3.3 V. How does this affect moisture readings at the extremes, and what are the recommended mitigations?
A: Near the rail extremes, the SAR ADC exhibits ±10–20 LSB nonlinearity, making codes near 0 and 4095 unreliable. For moisture sensing, very dry readings (high , low V) and very wet readings (low , V) are distorted. Mitigations: (a) use ADC_11db attenuation to spread the usable range; (b) apply Espressif's esp_adc_cal_characterize calibration API using factory eFuse correction coefficients; (c) restrict sensor operating range to 0.15–3.1 V where linearity is acceptable. - Q: What happens when the Google Apps Script execution quota is exhausted mid-experiment? How should the firmware respond to avoid data loss?
A: Quota exhaustion causes the endpoint to return HTTP 429 or 503, or silently time out without logging. If firmware ignores response codes, data is lost without notification. Correct firmware response: (a) check HTTP response code after every request; (b) on 429/503, enter exponential back-off retry; (c) buffer missed readings in ESP32 SPIFFS or EEPROM for retransmission on reconnection; (d) reduce sampling/transmission frequency to stay within daily quota limits. - Q: Why do moisture readings differ between air, dry soil, and wet soil even though all three are non-metallic? Explain in terms of the charge transport mechanism.
A: In air, virtually no free charge carriers exist, so is extremely high (hundreds of kΩ to MΩ) and is low. In dry soil, residual surface-bound ions and hygroscopic moisture provide limited ionic conduction, giving moderate . In wet soil, water fills pore spaces and dissolves mineral salts (Na⁺, K⁺, Ca²⁺, Cl⁻), dramatically increasing ionic conductivity and lowering to a few kΩ. The charge transport is entirely ionic (electrolytic), not electronic, so temperature and dissolved salt concentration affect readings independently of pure water content. - Q: If the Wi-Fi connection drops mid-experiment, what happens to data being transmitted? Describe a robust firmware strategy to ensure no data loss.
A: A dropped connection causes the HTTP client to block until timeout (5–10 s) or immediately fail with a connection error; any unacknowledged reading is lost. Robust strategy: (a) check WiFi.status() before each transmission and reconnect if disconnected; (b) store failed readings in a SPIFFS ring buffer with timestamps; (c) flush buffered records to Google Sheets in sequence after reconnection before resuming normal logging; (d) use a watchdog timer to reset the ESP32 if the reconnection loop hangs. - Q: Compare the information content of the sensor's DO versus AO. Under what application scenario would relying solely on DO be insufficient?
A: DO is binary — LOW when moisture exceeds a fixed threshold, HIGH otherwise — conveying only wet/dry state. AO is continuous, providing quantitative moisture content across the full range. Relying solely on DO is insufficient for: (a) precision irrigation control requiring VWC maintained within a narrow band (e.g., 40–60%); (b) drought monitoring requiring moisture trend analysis over time; (c) research applications requiring calibration curves; (d) detecting gradual moisture loss that takes hours to cross the DO threshold but is already visible in the AO trend. - Q: The Apps Script timestamps each entry server-side. What is the limitation of this, and how would you implement accurate client-side timestamping on the ESP32?
A: Server-side timestamping records arrival time at Google's servers, not the physical acquisition time. Network latency (0.3–2 s) introduces a systematic offset. Batched or buffered retransmissions receive a single timestamp, destroying temporal accuracy. Client-side fix: (a) synchronise ESP32 RTC via NTP using configTime() at boot (fetches UTC from pool.ntp.org); (b) call time() at the exact moment of ADC sampling; (c) embed the acquisition timestamp as a query parameter in the HTTP GET request, so it is recorded independently of server processing time. - Q: Temperature rises by 10°C while soil water content remains constant. How does this affect the ADC reading, and what compensation formula should be applied?
A: Ionic conductivity of soil water increases per °C. A 10°C rise increases by , reducing by and raising and the ADC code — the soil appears wetter than it is. Temperature compensation: measure temperature with a co-located sensor (e.g., DS18B20); correct the measured conductance using , where and (calibration temperature); compute moisture from to reflect actual water content rather than thermally-induced conductivity changes.
References & Resources (Not Applicable)
This section is not required for this experiment.
Was this experiment helpful?
Your feedback helps us improve
Please Sign In to rate this experiment.