Example Code for Arduino-Soil Moisture Detection

Last revision 2025/12/17

How to connect the DFRduino UNO, wire the capacitive soil moisture sensor to A0, and upload the sample sketch to read humidity levels and print Dry, Wet or Very Wet on Serial. It’s like using a digital gauge to label soil from air‑dry to water‑soaked based on calibration. Insert the probe, note the analog value in dry soil as AirValue and in soaked soil as WaterValue, for example 520 and 260, then divide this range into three intervals so the code can classify moisture bands and react reliably for smart irrigation or STEM projects.

Hardware Preparation

  • DFRduino UNO x1
  • Capacitive Soil Moisture Sensor x1
  • Jumper Cable x3

Software Preparation

Wiring Diagram

The final output value is affected by probe insertion depth and how tight the soil packed around it is. We regard "value_1" as dry soil and "value_2" as soaked soil. This is the sensor detection range.
For example: Value_1 = 520; Value_2 = 260.
The range will be divided into three sections: dry, wet, water. Their related values are:

  • Dry: (520 430]
  • Wet: (430 350]
  • Water: (350 260]

Sample Code

/***************************************************
 This example reads Capacitive Soil Moisture Sensor.

 Created 2015-10-21
 By berinie Chen <[email protected]>

 GNU Lesser General Public License.
 See <http://www.gnu.org/licenses/> for details.
 All above must be included in any redistribution
 ****************************************************/

/***********Notice and Trouble shooting***************
 1.Connection and Diagram can be found here: https://www.dfrobot.com/wiki/index.php?title=Capacitive_Soil_Moisture_Sensor_SKU:SEN0193
 2.This code is tested on Arduino Uno.
 3.Sensor is connect to Analog 0 port.
 ****************************************************/

const int AirValue = 520;   //you need to replace this value with Value_1
const int WaterValue = 260;  //you need to replace this value with Value_2
int intervals = (AirValue - WaterValue)/3;
int soilMoistureValue = 0;
void setup() {
  Serial.begin(9600); // open serial port, set the baud rate to 9600 bps
}
void loop() {
soilMoistureValue = analogRead(A0);  //put Sensor insert into soil
if(soilMoistureValue > WaterValue && soilMoistureValue < (WaterValue + intervals))
{
  Serial.println("Very Wet");
}
else if(soilMoistureValue > (WaterValue + intervals) && soilMoistureValue < (AirValue - intervals))
{
  Serial.println("Wet");
}
else if(soilMoistureValue < AirValue && soilMoistureValue > (AirValue - intervals))
{
  Serial.println("Dry");
}
delay(100);
}

Was this article helpful?

TOP