Measuring soil moisture with an Arduino

In this activity, we will use a soil moisture sensor to keep track of the amount of water in the soil surrounding plants so we can know when the soil is dry and plants need watering.

We will need to use jumper wires to connect the soil moisture sensor to the Arduino. We can connect the sensor directly to the Arduino using jumper wires but we can also connect it via a breadboard if we wish to connect more things.

Connect VCC on the moisture sensor to pin 7 on Arduino, GND on the sensor to GND on the Arduino board, and SIG on the sensor to pin A0 on the Arduino (as shown below). Then place the sensor in some soil and open up the Serial Monitor in the Arduino program to test the sensor (at 9600 baud rate). Add some water to the soil to see the moisture values increase.

Moisture sensor

The code

Here is the code to test the moisture sensor.

int val = 0;  // value for storing moisture value 
int soilPin = A0; // declare a variable for the soil moisture sensor signal/input (SIG)
int soilPower = 7;  // variable for soil moisture sensor to receive power (VCC)

// Rather than powering the sensor through the 3.3V or 5V pins, we'll use a digital pin to power the sensor.
// This will prevent corrosion of the sensor as it sits in the soil. 

void setup(){
  Serial.begin(9600); // open serial over USB (make sure baud rate in serial monitor is set to 9600 baud)
  pinMode(soilPower, OUTPUT); // set D7 as an OUTPUT
  digitalWrite(soilPower, LOW); //set to LOW so no power is flowing through the sensor
}

void loop(){
  Serial.print("Soil Moisture = ");    
  // get soil moisture value from the function below and print it to serial monitor
  Serial.println(readSoil());

  // This 1 second timefrme is used so you can test the sensor and see it change in real-time.
  // For in-plant applications, you will want to take readings much less frequently.
  delay(1000);  // take a reading every second
}

//This is a function used to get the soil moisture content
int readSoil(){
  digitalWrite(soilPower, HIGH); // turn D7 "On"
  delay(10); // wait 10 milliseconds 
  val = analogRead(soilPin);  // read the SIG (signal) value form sensor 
  digitalWrite(soilPower, LOW); // turn D7 "Off"
  return val; // send current moisture value
}