OTHER PROJECTS

ESP32 Smart Agriculture Monitoring System

Watering plants at the wrong time, or forgetting to water them at all, is one of the biggest problems in any garden or farm. In this project, we build a Smart Agriculture Monitoring System using an ESP32. It keeps an eye on the soil, the light, the temperature and the humidity, shows everything on a 20×4 LCD, and turns on a water pump by itself when the soil gets too dry.

The system also keeps track of the date and time with a DS1307 real-time clock and prints every reading on the Serial Monitor. A red LED lights up when the light level is low, so you can see at a glance when your plants need more light.

What You Will Learn :

  • How to connect many sensors to one ESP32
  • How to share the I2C pins between an LCD and an RTC module
  • How to read temperature and humidity with a DHT22 sensor
  • How to read light levels with an LDR and convert them to lux
  • How to measure soil moisture and decide when to water
  • How to switch a water pump using a relay module
  • How to create your own simple library files for the Arduino IDE

Components Required :

ComponentQuantity
ESP32 DevKit1
20×4 I2C LCD Display1
DS1307 RTC Module1
DHT22 Temperature and Humidity Sensor1
LDR Light Sensor Module1
FC-28 Soil Moisture Sensor (potentiometer in simulation)1
1 Channel Relay Module1
Water Pump (orange LED in simulation)1
Red LED1
220 Ohm Resistor1
Breadboard1
Jumper WiresSeveral
USB Cable (to upload code)1

Libraries Required :

LibraryPurpose
LiquidCrystal I2CControls the 20×4 I2C LCD
DHT sensor libraryReads the DHT22 sensor
RTClibReads the DS1307 real-time clock
WireI2C communication (built into Arduino IDE)

Install the first three libraries from Sketch → Include Library → Manage Libraries in the Arduino IDE. Accept the prompts to install Adafruit Unified Sensor and Adafruit BusIO, which the DHT and RTC libraries need. If you have not added ESP32 support yet, open Tools → Board → Boards Manager, search for esp32 and install the package.

This project also uses two small custom files, FC28.h and FC28.cpp, for the soil moisture sensor. You do not install them. You create them as extra tabs in your sketch, as explained in the code section below.

Circuit Diagram :

Wiring Table :

Sensors and Modules → ESP32

PartPart PinESP32 Pin
DHT22SDA (data)GPIO 15
DHT22VCC / GND3V3 / GND
LDR ModuleAO (analog)GPIO 35
LDR ModuleVCC / GND3V3 / GND
Soil Sensor (Potentiometer)SIGGPIO 34
Soil Sensor (Potentiometer)VCC / GND3V3 / GND

Outputs → ESP32

PartPart PinESP32 Pin
Red LED (with 220 ohm resistor)Resistor endGPIO 33
Red LEDCathodeGND
Relay ModuleINGPIO 18
Relay ModuleVCC / GND3V3 / GND

I2C Devices → ESP32 (both share the same two wires)

PartPart PinESP32 Pin
20×4 I2C LCDSDAGPIO 21
20×4 I2C LCDSCLGPIO 22
20×4 I2C LCDVCC / GND3V3 / GND
DS1307 RTCSDAGPIO 21
DS1307 RTCSCLGPIO 22
DS1307 RTC5V / GNDVIN / GND

Relay Output (Water Pump)

Relay TerminalConnection
COMPump (or orange LED cathode in simulation)
NOGND

In the simulation, the orange LED stands in for the water pump. Its anode connects to 3V3, its cathode connects to the relay’s COM terminal, and the relay’s NO terminal goes to GND. When the relay switches on, the LED lights up.

Notes:

  • The simulation uses a potentiometer in place of the FC-28 soil moisture sensor. Turn the knob to change the soil reading. In a real build, connect the FC-28 analog output to GPIO 34.
  • The simulation powers the LCD from 3V3, but many 20×4 I2C LCD modules need 5V on their VCC pin. Check the specification of your module.
  • For a real water pump, use a separate power source for the pump and connect it only through the relay’s COM and NO terminals. Never power a pump from the ESP32 pins, and be very careful with any mains voltage.

How It Works :

The ESP32 repeats the same cycle every 3 seconds. It reads all the sensors, works out a simple status for each one, shows the results on the LCD and controls the pump and the LED.

SensorWhat the System Shows
Soil moistureWet (below 33.33%), Normal, or Dry (above 66.66%)
Light (LDR)Low (below 807 lux), Medium, or High
DHT22Temperature in °C and humidity in %
DS1307 RTCDate and time, printed on the Serial Monitor

Two actions happen automatically :

ConditionAction
Soil is DryThe LCD shows “Soil is DRY!”, and the relay turns the pump on
Soil is Wet or NormalThe relay turns the pump off
Light level is LowThe red LED turns on
Light level is OKThe red LED turns off

The 20×4 LCD has four rows, so it shows the soil condition, the light level, the temperature and the humidity, one on each row. The date, the time and the exact numbers, such as the soil moisture percentage and the lux value, are printed on the Serial Monitor.

Circuit Simulation :

Turn the potentiometer to change the soil moisture and watch the pump LED switch on and off!

****

Arduino Code :

This project uses three files. In the Arduino IDE, click the small arrow next to the sketch tab, choose New Tab and create FC28.h and FC28.cpp. Keep all three files in the same sketch folder.

Main sketch:

#include <Wire.h>
#include "LiquidCrystal_I2C.h"
#include "DHT.h"
#include <RTClib.h>
#include "FC28.h"


RTC_DS1307 rtc;


#define relayPin 18
#define ldrPin 35
#define DHT_PIN 15
#define LED_PIN 33
#define SensorFC28_Pin 34


DHT dht(DHT_PIN, DHT22);
LiquidCrystal_I2C lcd(0x27, 20, 4);
FC28Sensor mySensor;


float soil_moisture;
const float gama = 0.7;
const float rl10 = 50;


String soilCondition;
String lightLevel;
float humidity;
float temperature;
float lux;


void setup() {
  Serial.begin(9600);
  pinMode(ldrPin, INPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(relayPin, OUTPUT);
  mySensor.initFC28Sensor(115200, SensorFC28_Pin);


  Wire.begin();
  if (!rtc.begin()) {
    Serial.println("RTC Not Connected");
    lcd.setCursor(0, 0);
    lcd.print("RTC Not Connected");
    while (1);
  }


  dht.begin();
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Welcome to");
  lcd.setCursor(0, 1);
  lcd.print("Smart Agriculture");
  lcd.setCursor(0, 2);
  lcd.print("Monitoring System");
  delay(2000);
  lcd.clear();
  Serial.println("Smart Agriculture System Initialized");
}


void loop() {
  DateTime now = rtc.now();
  Serial.println("Date               : " + String() + now.day() + "/" + now.month() + "/" + (now.year() % 100));
  Serial.println("Time               : " + String() + now.hour() + ":" + now.minute() + ":" + now.second());


  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  int ldrValue = analogRead(ldrPin);
  ldrValue = map(ldrValue, 4095, 0, 1024, 0);
  float ldrVoltage = ldrValue / 1024.0 * 5;
  float ldrResistance = 2000 * ldrVoltage / (1 - ldrVoltage / 5);
  lux = pow(rl10 * 1e3 * pow(10, gama) / ldrResistance, (1 / gama));
  soil_moisture = mySensor.getSoilMoisture();


  soilCondition = soil_moisture < 33.33 ? "Wet" : soil_moisture > 66.66 ? "Dry" : "Normal";
  lightLevel = lux < 807 ? "Low" : (lux > 808 && lux < 1614 ? "Medium" : "High");


  displaySoilStatus();
  displayLightStatus();
  displayEnvironment();
  controlPump();


  Serial.println("------------------------");
  delay(3000);
  lcd.clear();
}


void displaySoilStatus() {
  lcd.setCursor(0, 0);
  lcd.print("Soil        :");
  lcd.setCursor(13, 0);
  lcd.print(soilCondition);
  Serial.println("Soil Moisture      : " + String(soil_moisture, 2) + " % (" + soilCondition + ")");
}


void displayLightStatus() {
  lcd.setCursor(0, 1);
  lcd.print("Light       :");
  lcd.setCursor(13, 1);
  lcd.print(lightLevel);
  Serial.println("Light Intensity    : " + String(lux, 1) + " Lux (" + lightLevel + ")");


  if (lux < 807) {
    digitalWrite(LED_PIN, HIGH);
    Serial.println("Light Level Low - LED ON");
  } else {
    digitalWrite(LED_PIN, LOW);
    Serial.println("Light Level OK - LED OFF");
  }
}


void displayEnvironment() {
  lcd.setCursor(0, 2);
  lcd.print("Temp        :");
  lcd.setCursor(13, 2);
  lcd.print(temperature, 1);
  lcd.setCursor(19, 2);
  lcd.print("C");


  lcd.setCursor(0, 3);
  lcd.print("Humidity    :");
  lcd.setCursor(13, 3);
  lcd.print(humidity, 1);
  lcd.setCursor(19, 3);
  lcd.print("%");


  Serial.println("Temperature        : " + String(temperature, 1) + " °C");
  Serial.println("Humidity           : " + String(humidity, 1) + " %");
}


void controlPump() {
  if (soil_moisture > 66.66) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Soil is DRY!");
    lcd.setCursor(0, 1);
    lcd.print("Dry and a pumping");
    digitalWrite(relayPin, HIGH);
    Serial.println("Soil is dry - Water Pump ON");
    delay(3000);
    lcd.clear();
  } else {
    digitalWrite(relayPin, LOW);
    Serial.println("Soil moisture adequate - Pump OFF");
  }
}

FC28.h:

#ifndef ESP32_FC28_H
#define ESP32_FC28_H


#include <Arduino.h>


class FC28Sensor {
  public:
    void initFC28Sensor(int baudRate, int pin);
    float getSoilMoisture();


  private:
    int _pin;
    float analogFC28, value;
};


#endif

FC28.cpp:

#include "FC28.h"


void FC28Sensor::initFC28Sensor(int baudRate, int pin) {
  Serial.begin(baudRate);
  pinMode(pin, INPUT);
  _pin = pin;
}


float FC28Sensor::getSoilMoisture() {
  analogFC28 = analogRead(_pin);
  value = floor(analogFC28 / 4095.0 * 1000.0) / 10.0;
  return value;
}

Code Explanation :

Includes and Objects: The sketch includes the libraries for the LCD, the DHT22, the RTC and the custom soil sensor file. It then creates one object for each device. The LCD uses I2C address 0x27 and has 20 columns and 4 rows.

Pin Definitions: The #define lines give a name to each pin, so the code reads clearly. For example, relayPin is GPIO 18 and ldrPin is GPIO 35.

Setup: The setup() function sets the pin modes, starts the soil sensor, starts the I2C bus and checks that the RTC is connected. If the RTC is not found, the program stops and prints an error. Then it starts the DHT22 and the LCD and shows a welcome message for 2 seconds.

Reading the Time: At the start of every loop, rtc.now() gets the current date and time, and the code prints them on the Serial Monitor.

Reading the Sensors: The DHT22 gives the temperature and humidity. The LDR value is read as an analog number, converted into a voltage, then into a resistance, and finally into lux with a standard formula. The soil sensor class returns the moisture as a percentage.

Status Decisions: Two simple lines turn the numbers into words. Soil below 33.33% is “Wet”, above 66.66% is “Dry”, and anything between is “Normal”. Light below 807 lux is “Low”, values up to 1614 are “Medium”, and higher values are “High”.

displaySoilStatus(): Shows the soil condition on the first LCD row and prints the exact percentage on the Serial Monitor.

displayLightStatus(): Shows the light level on the second row. It also turns the red LED on when the light is low and off when the light is fine.

displayEnvironment(): Shows the temperature on the third row and the humidity on the fourth row.

controlPump(): When the soil moisture is above 66.66%, the LCD shows a “Soil is DRY!” message for 3 seconds and the relay turns on to start the pump. In every other case, the relay turns off.

FC28.h and FC28.cpp: These two files create a small FC28Sensor class. It reads the sensor’s analog value (0 to 4095) and converts it to a percentage with one decimal place.

Loop Timing: The delay(3000) at the end gives one full update every 3 seconds, and lcd.clear() prepares the screen for the next update.

How to Use :

  • Wire the circuit as shown in the diagram above
  • Install the LiquidCrystal I2C, DHT sensor library and RTClib libraries
  • Create the two extra tabs FC28.h and FC28.cpp and paste the code into them
  • Connect the ESP32 to your computer with a USB cable
  • Select Tools → Board and choose your ESP32 board, for example ESP32 Dev Module
  • Select the correct port under Tools → Port
  • Upload the code to the ESP32
  • Open the Serial Monitor and set the speed to 115200 baud
  • Watch the LCD show the soil, light, temperature and humidity
  • Turn the potentiometer (or dry out the real soil sensor) to see the pump switch on
  • Cover the LDR to see the red LED turn on in low light

Customisation Tips :

  • Add the time to the LCD: Show the date and time from the RTC on the screen, or add a bigger display
  • Water at set times: Use the RTC to water only in the morning or evening
  • Change the soil limits: Edit the 33.33 and 66.66 values to suit your plant type
  • Change the light limit: Edit the 807 value to decide when the red LED should switch on
  • Add WiFi monitoring: Use the ESP32 WiFi to send the readings to your phone or a cloud dashboard
  • Add more plants: Connect more soil sensors to other analog pins and water each plant separately
  • Add a water level sensor: Stop the pump when the water tank is empty
  • Add a buzzer: Sound an alert when the soil is very dry or the temperature is too high

You have successfully built a Smart Agriculture Monitoring System using an ESP32. It reads soil moisture, light, temperature, humidity and time, shows the key values on an LCD, and waters your plants automatically when the soil gets too dry. This project is a great base for a smart garden, a greenhouse or a small farm.

Try adding WiFi so you can check your plants from anywhere! Visit Tinkercircuits.com for more exciting projects!

Happy Tinkering! The Tinker Circuits Team

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button