Soil Moisture Sensor
soil_moisture_sensor.ino
/*
Project: Internet of Things
Circuit: Soil Moisture Sensor
Boards Supported: UNO R3/R4, Nano, ESP32
Function: This project read the value from a soil moisture sensor.
Author: STEMVentor Educonsulting
This code is copyrighted. Please do not reuse or share for any purpose other than for learning with subscribed STEMVentor programs. This code is for educational purposes only and is not for production use.
*/
// LIBRARIES
// PIN DEFINITIONS
#define SOIL_MOISTURE_SENSOR_DIGITAL_PIN 2
#define SOIL_MOISTURE_SENSOR_ANALOG_PIN A0
// We will be programmatically turning the sensor on and off with this pin.
#define SOIL_MOISTURE_SENSOR_POWER_PIN 1
// GLOBAL CONSTANTS
// GLOBAL VARIABLES
// INITIALIZE OBJECTS
// LOCAL FUNCTIONS
// THE setup FUNCTION RUNS ONCE WHEN YOU PRESS RESET OR POWER THE BOARD.
void soilMoistureSensorSetup() {
pinMode(SOIL_MOISTURE_SENSOR_DIGITAL_PIN, INPUT);
pinMode(SOIL_MOISTURE_SENSOR_POWER_PIN, OUTPUT);
// You don't need to set pin mode for analog pins.
// Make sure the sensor starts turned off.
digitalWrite(SOIL_MOISTURE_SENSOR_POWER_PIN, LOW);
Serial.println("The Soil Moisture sensor is ready!");
}
// Read Soil Moisture sensor values.
void readSoilMoistureSensorValues()
{
digitalWrite(SOIL_MOISTURE_SENSOR_POWER_PIN, HIGH); // Turn the sensor ON
delay(300); // Allow power to settle
// The analog signal from the sensor pad is compared
// to a threshold (reference voltage) set by a potentiometer on the module.
// If the amount of water on the sensing pad is below the set threshold,
// the comparator gives a HIGH digital output signal at the digital pin (DO)
// else gives a LOW signal.
uint8_t is_soil_moisture_low = digitalRead(SOIL_MOISTURE_SENSOR_DIGITAL_PIN);
Serial.println("Digital Value: " + gas_sensor_digital_value);
// Read the analog value.
// The analog value returns an actual voltage value between 0 and 1024.
// You can programmatically decide what is the threshold for triggering some action.
uint8_t soil_moisture_sensor_analog_value = analogRead(SOIL_MOISTURE_SENSOR_ANALOG_PIN);
Serial.println("Analog Value: " + soil_moisture_sensor_analog_value);
// Convert the analog value to a % value using the map function.
uint8_t soil_moisture_sensor_percent_value = map(soil_moisture_sensor_analog_value, 0, 1024, 0, 100);
Serial.println("Percent Value: " + soil_moisture_sensor_percent_value);
digitalWrite(SOIL_MOISTURE_SENSOR_POWER_PIN, LOW); // Turn the sensor OFF
// Here you can either rely on the digital HIGH/LOW value based on the sensor setting
// or check the analog value and decide based on that. Or check for both.
if(is_soil_moisture_low == LOW || soil_moisture_sensor_percent_value < 25){
Serial.println("Soil moisture low! Start pump.");
}else{
Serial.println("Soil moisture ok. Stop pump.");
// No need to read or print the intensity.
}
}