Measuring soil moisture

Lesson 11 of 28 · Arduino and ESP32

Measuring soil moisture is a common and useful practical exercise for learning how sensors are connected to microcontrollers and how an analog signal is turned into a meaningful physical quantity. The two most common approaches are capacitive and resistive (based on resistance). Both kinds of sensors give an electrical signal that the microcontroller reads through an AD converter (analog-to-digital converter), but they work on different physical principles and have different advantages and disadvantages in practice.

Capacitive soil moisture sensor – how it works

A capacitive soil moisture sensor is basically a capacitor made on a printed circuit board (PCB), whose capacitance changes with the electrical (dielectric) properties of the soil around it. The “electrodes” are copper traces on the board that interleave and form the two plates of the capacitor, separated by the board material and the soil around it.

When the soil moisture increases, the dielectric constant of the material between and around the traces increases (water has a much higher dielectric constant than dry soil or air). Because of this, the capacitance also increases. The sensor module has simple electronics (an oscillator, an RC circuit or a capacitance-to-voltage converter) that turns the small change of capacitance into a measurable analog voltage (AOUT), which we read with the AD converter.

Important in practice: capacitive sensors do not pass current through the soil (the traces are usually covered with a protective layer), so they do not corrode quickly. They are usually more stable and last longer, and they work well with microcontrollers at 3.3 V or 5 V.

Resistive soil moisture sensor – how it works

A resistive moisture sensor measures the electrical resistance (i.e. the conductivity) between two bare metal electrodes pushed into the soil. When the soil contains more water and dissolved ions, it conducts current better and the resistance between the electrodes decreases; when the soil is dry, the resistance increases.

A resistive probe is usually used in a voltage divider: the probe is one part of the divider, and a known resistor the other. The voltage at the middle point of the divider changes with the resistance of the probe, and the microcontroller reads it on an analog input. Many ready-made kits have a small board with an operational amplifier or a comparator, which gives both an analog output (A0) and a digital output with an adjustable threshold (D0).

Important in practice: resistive probes are simple and cheap, and the digital output is handy for simple threshold control (e.g. turning on a pump). But since direct current flows through the electrodes, they corrode and wear out over time; in the long run they also give less stable readings than capacitive sensors.

In the exercise that follows we will show how both kinds of sensors are connected to an Arduino (or ESP32), how the analog signal is read and interpreted, and how the readings are adjusted for your soil. The exercise contains wiring diagrams, example code and a graphical display of the measured values.

Capacitive soil moisture sensor – measuring moisture
Figure 1: Capacitive soil moisture sensor – measuring moisture

Resistive soil moisture sensor

This part continues the lesson on measuring moisture and deals with the resistive probe. A resistive probe is a simple and cheap sensor that measures how well the soil conducts current – a practical way to estimate moisture. Below we explain what the probe measures, what it is usually used for, and how it is connected – in a simplified diagram in Tinkercad and in a real circuit with a small driver board (the LM393 module).

How a resistive probe measures moisture

The probe has two bare metal electrodes that are pushed into the soil. The soil between the electrodes behaves like a resistor: when it has more water and dissolved ions, the resistance decreases; when it is dry, the resistance increases. The probe itself is not an active component – it must be part of a simple circuit (most often a voltage divider) so that the microcontroller can read a voltage that depends on the resistance of the soil.

It is most often used for:

  • simple moisture monitoring for watering plants,
  • recognizing a threshold (whether the soil is dry or moist) in automatic watering systems,
  • school projects and prototypes where low cost matters.

Wiring – the basic idea

The usual electric circuit is a voltage divider. One part of the divider is the probe (the variable resistance Rsoil), and the other a known resistor R1. The voltage at the middle point is read by the microcontroller's AD converter:

VCC --- R1 ---+--- A0 (ulaz AD konvertora)
              |
           Rsoil (sonda)
              |
             GND

When Rsoil changes, the voltage at the middle point changes too, so analogRead() returns a different value. For reliable results:

  • choose R1 so that the voltage at the middle point changes in a useful range of the AD converter (most often 10 kΩ),
  • power the probe only briefly, during the measurement, so that the electrodes wear out less,
  • use a common ground for the sensor module and the microcontroller.
Wiring diagram of a resistive soil moisture sensor with an Arduino UNO board in Tinkercad
Figure 2: Wiring diagram of a resistive soil moisture sensor with an Arduino UNO board, simulation in Tinkercad

A soil moisture sensor measures the amount of water in the soil based on the change of its electrical resistance. When the soil is dry, the resistance is high, and in moist soil it decreases. The sensor turns this resistance into a voltage that the Arduino board can read.

Figure 2 shows the basic wiring diagram of the moisture sensor connected directly to an Arduino UNO board. The diagram, made in Tinkercad, shows a simple connection of the sensor pins VCC, GND and Signal to the matching Arduino pins.

In this exercise the analog pin A0 is used to read the sensor's output voltage. This voltage depends on the resistance of the soil between the two electrodes of the probe. The Arduino converts the analog voltage into a digital value from 0 to 1023, which shows the relative moisture.


Using a module with the LM393 comparator

Figure 3 shows a real connection of the sensor through a module with the LM393 comparator. This module lets the sensor work in both analog and digital mode.

  • Analog output (A0) – gives a voltage that changes continuously with the soil moisture.
  • Digital output (D0) – gives a signal 0 or 1, depending on the set threshold.

The comparator board has a small potentiometer for setting the voltage threshold. When the measured sensor voltage drops below this threshold, the digital output (D0) becomes LOW (0); otherwise it stays HIGH (1). This can trigger simple actions, for example turning on a water pump or an LED indicator.


Pinout

The LM393 module has 4 + 2 pins:

  • on the side with two pins, the metal electrodes of the sensor are connected;
  • on the side with four pins (the module's output):
    • VCC → to the Arduino's 5V
    • GND → to the Arduino's GND
    • A0 → to the analog input A0
    • D0 → a digital output, optional, for recognizing a threshold

This kind of wiring makes measuring moisture easier and shows well the principle of measuring through resistance with an Arduino.

The LM393 module of a soil moisture sensor connected to an Arduino Uno board: 5V, GND, analog pin A0 and a resistive probe with two electrodes
Figure 3: Wiring diagram of a resistive moisture sensor (LM393 module) with an Arduino Uno board – power, analog output (A0) and connecting the probe
This diagram shows how a resistive moisture sensor with an LM393 module is connected to an Arduino Uno board for analog moisture measurement. The two metal electrodes of the sensor are attached to the module's two-pin connector. The LM393 board is powered from the Arduino's 5V and GND pins, and its analog output (A0) is connected to the Arduino's input A0 for continuous measurement. Unlike the bare probe, the module has a comparator and a potentiometer and gives a stable analog voltage that depends on the conductivity of the soil. Higher moisture lowers the resistance of the probe and gives a lower analog value on A0, which is then turned into a percentage in the program. This way the soil moisture is monitored reliably without the digital output (D0), which is needed only for simple dry/moist switching.

Measuring soil moisture with a capacitive sensor

A capacitive soil moisture sensor is a more advanced type of moisture sensor. Unlike the resistive one, which measures the change of electrical resistance between two electrodes, the capacitive sensor measures the change of capacitance caused by the dielectric properties of the soil. When the soil becomes moister, its dielectric constant increases, the capacitance increases and the sensor's analog output signal changes.

The main advantage of the capacitive sensor over the resistive one is that it does not cause electrolysis, because no direct current flows through the soil. That is why the sensor lasts much longer and gives more stable and repeatable measurements.

Overview

Figure 1 shows a real connection of a capacitive moisture sensor with an Arduino board, pushed into a flowerpot, and Figure 2 shows the wiring diagram of the sensor – the power pins (Vcc and GND) and the analog output (A0) connected to the Arduino's analog input.

How the sensor works

The capacitive sensor has an analog output marked AO, which gives a voltage proportional to the soil moisture. The Arduino reads this voltage with the function analogRead(A0). The value is usually from 0 to 1023 and can be converted linearly into a moisture percentage, to make it easier to interpret.

// Example: reading a capacitive soil moisture sensor
int sensorPin = A0;        // analog input connected to the AO pin of the sensor
float moistureValue = 0;   // current moisture

void setup() {
  Serial.begin(115200);    // communication with Processing
}

void loop() {
  int rawValue = analogRead(sensorPin);              // raw value from the sensor
  moistureValue = map(rawValue, 1023, 300, 0, 100);  // converting to a percentage (adjust the limits for your sensor)
  Serial.println(moistureValue);                     // sending the moisture to Processing
  delay(3000);                                       // 3-second pause between measurements
}

Serial communication and display in Processing

The data is sent to Processing the same way as for the resistive sensor. In both cases the Arduino sends one number – the soil moisture percentage – over the serial port at 115200 baud.

That is why the same Processing program from the previous part can be used for this sensor too. It receives the moisture values by itself through the function serialEvent(), shows them on the screen and displays the changes live, as text and as a colored bar.

The only difference between these two sensors is the measuring principle – resistive sensors measure conductivity, and capacitive ones the change of the dielectric constant. The wiring, communication and display are the same.

Arduino code – measuring soil moisture

The following Arduino program reads data from a resistive moisture sensor through the analog input A0. The measured value is turned into a moisture percentage and sent over the serial port every 3 seconds. The data can be watched directly in the Serial Monitor (in the Arduino IDE) or read in other programs, such as Processing, for display and further analysis.

Arduino program

// analog pin the soil moisture sensor is connected to
const int pin_A0 = A0;

// threshold below which the soil is considered dry
const int dryThreshold = 200;

void setup() {
  // serial connection at 115200 bits per second
  Serial.begin(115200);
}

void loop() {
  // raw analog value from the sensor (0 to 1023)
  int sensorValue = analogRead(pin_A0);

  // converting to a percentage:
  // a high value (e.g. 1023) → dry soil → a low moisture percentage
  // a low value (e.g. 300) → moist soil → a high moisture percentage
  float moisturePercent = 100.0 * (1023 - sensorValue) / 1023;

  // sending the computed percentage to the serial port
  Serial.println(moisturePercent);

  // 3-second pause before the next measurement
  delay(3000);
}

Explanation

  • analogRead(A0) reads the voltage from the sensor and converts it into a digital value from 0 to 1023.
  • Higher values mean drier soil (higher resistance), and lower values moister soil.
  • The percentage is computed linearly, to make it easier to interpret.
  • Serial.println() sends the measured moisture percentage to the serial interface – it can be followed in the Serial Monitor or in other programs that read serial data, such as Processing, MATLAB or Python scripts.

This simple program can be the basis for more complex applications, such as automatic watering systems or environmental data logging.

Processing code – showing soil moisture data

The following Processing program receives soil moisture data from the Arduino over the serial port and shows it on the screen as text and graphically. Each value the Arduino sends is the current moisture percentage, sent every 3 seconds with the statement Serial.println().

Processing program

import processing.serial.*;

Serial myPort;
String val = "";
float moisture = 0;   // last moisture value (0–100 %)

void setup() {
  size(400, 200);                                       // window size
  myPort = new Serial(this, Serial.list()[0], 115200);  // opening the first available serial port
  myPort.bufferUntil('\n');                             // serialEvent() is called when a whole line arrives
}

void draw() {
  background(255);                       // white background
  fill(0);                               // black text color
  textSize(20);
  text("Soil moisture: " + nf(moisture, 0, 2) + "%", 50, 60);  // printing with 2 decimal places

  // bar that shows the moisture
  fill(0, 100, 255);
  rect(50, 100, map(moisture, 0, 100.0, 0, 300), 30);  // blue bar proportional to the moisture
}

void serialEvent(Serial p) {
  val = p.readStringUntil('\n');         // reading the whole line sent by the Arduino
  if (val != null) {
    val = trim(val);                     // removing spaces and the newline character
    try {
      moisture = float(val);             // converting the text to a number
    } catch (Exception e) {
      println("Failed to read the value: " + val);  // message if the conversion fails
    }
  }
}

Explanation

  • Serial communication: the program uses the library processing.serial to communicate with the Arduino board over USB.
  • Serial.list() returns the list of available ports. The first one ([0]) is usually the Arduino – if it is not, try another index.
  • The function serialEvent() is called by itself when new serial data arrives. It reads the whole line (ending with the character '\n') sent by the Arduino. So that it is called only when a whole line arrives, myPort.bufferUntil('\n') is called in setup().
  • The text is then converted to a float, so that it can be used for calculation and drawing.
  • In the loop draw(), the last value is shown as text and as a blue bar whose length matches the moisture percentage.

This display lets you follow moisture changes live. When you connect a resistive or capacitive sensor to the Arduino, you can see how the measured value changes in different conditions (dry, moist, wet). Processing is a simple and interesting way to show sensor data graphically in Arduino projects.

Practice tasks

Try to solve the task yourself first, and only then open the solution.

  1. Print the state of the soil in words: below 30 % – “dry”, from 30 to 70 % – “just right”, above 70 % – “wet”.
  2. Add three LEDs (red – pin 4, yellow – pin 5, green – pin 6) that show these three states.
  3. The capacitive sensor does not need to be powered all the time. Power it from digital pin 7: turn it on, wait 100 ms, measure, and then turn it off; repeat the measurement every 10 seconds.
Solution 1: three states of the soil
int sensorPin = A0;

void setup() {
  Serial.begin(115200);
}

void loop() {
  int raw = analogRead(sensorPin);
  int procenat = constrain(map(raw, 1023, 300, 0, 100), 0, 100);
  Serial.print(procenat);
  if (procenat < 30) {
    Serial.println(" %  dry");
  } else if (procenat <= 70) {
    Serial.println(" %  just right");
  } else {
    Serial.println(" %  wet");
  }
  delay(1000);
}
Solution 2: a traffic light for moisture
int sensorPin = A0;
const int CRVENA = 4, ZUTA = 5, ZELENA = 6;

void setup() {
  pinMode(CRVENA, OUTPUT);
  pinMode(ZUTA, OUTPUT);
  pinMode(ZELENA, OUTPUT);
}

void loop() {
  int procenat = constrain(map(analogRead(sensorPin), 1023, 300, 0, 100), 0, 100);
  digitalWrite(CRVENA, procenat < 30 ? HIGH : LOW);
  digitalWrite(ZUTA, (procenat >= 30 && procenat <= 70) ? HIGH : LOW);
  digitalWrite(ZELENA, procenat > 70 ? HIGH : LOW);
  delay(500);
}
Solution 3: the sensor is turned on only for measuring
int sensorPin = A0;
const int NAPAJANJE = 7;   // sensor VCC on pin 7 (the sensor draws a few mA)

void setup() {
  Serial.begin(115200);
  pinMode(NAPAJANJE, OUTPUT);
  digitalWrite(NAPAJANJE, LOW);
}

void loop() {
  digitalWrite(NAPAJANJE, HIGH);   // turn the sensor on
  delay(100);                      // wait for the output to settle
  int raw = analogRead(sensorPin);
  digitalWrite(NAPAJANJE, LOW);    // turn the sensor off
  Serial.println(raw);
  delay(10000);
}

Check your knowledge

Open the quiz

Quiz: soil moisture

1. What happens to the resistance of the soil when it is moister?




2. What is the main advantage of the capacitive sensor?




3. What is the output D0 on the LM393 module for?




4. Why is myPort.bufferUntil('\n') called in Processing?