Soil Moisture Monitoring System Using ESP32 and MQTT (Beginner Guide)

Soil Moisture Monitoring System Using ESP32 and MQTT (Beginner Guide)

Soil Moisture Monitoring System Using ESP32 and MQTT | Complete Beginner Guide

Monitoring soil moisture is essential for maintaining healthy plants and improving water efficiency. Instead of checking the soil manually every day, you can build a simple IoT based Soil Moisture Monitoring System using an ESP32, a soil moisture sensor, and the MQTT protocol. This project measures the moisture level in the soil and sends the data to an MQTT broker, allowing you to monitor it from a dashboard or mobile application in real time.

In this beginner-friendly tutorial, you’ll learn how to build a soil moisture monitoring system using ESP32, connect it to Wi-Fi, publish sensor readings using MQTT, and visualize the data on an MQTT dashboard.

What is a Soil Moisture Monitoring System?

A Soil Moisture Monitoring System is an IoT project that measures the water content in soil using a soil moisture sensor. The sensor readings are collected by an ESP32 micro-controller and transmitted to an MQTT broker over Wi-Fi. You can then monitor the moisture level from anywhere using an MQTT dashboard.

This project is useful for home gardens, farms, greenhouses, and smart irrigation systems.

How Does This Project Work?

The working process is simple:

  1. The soil moisture sensor measures the moisture level.
  2. ESP32 reads the analog value from the sensor.
  3. ESP32 connects to your Wi-Fi network.
  4. The moisture reading is published to an MQTT broker.
  5. An MQTT dashboard receives and displays the live data.

Flow Diagram

Soil Moisture Monitoring System Using ESP32 and MQTT (Beginner Guide)

Components Required

  • ESP32 Development Board
  • Capacitive Soil Moisture Sensor
  • Jumper Wires
  • Breadboard
  • USB Cable
  • Wi-Fi Connection
  • MQTT Broker (HiveMQ or Mosquitto)

Why Use a Capacitive Soil Moisture Sensor?

There are two common types of soil moisture sensors:

  • Resistive Soil Moisture Sensor
  • Capacitive Soil Moisture Sensor

For beginners, a capacitive soil moisture sensor is recommended because:

  • It lasts longer.
  • It is more accurate.
  • It does not corrode easily.
  • It provides stable readings.

Circuit Diagram Connections

Connect the soil moisture sensor to the ESP32 as shown below.

Soil Sensor Pin ESP32 Pin
VCC 3.3V
GND GND
AOUT GPIO34 (D34)

GPIO34 is an analog input pin used to read the sensor value.

Installing Required Libraries

Open the Arduino IDE.

Go to: Sketch → Include Library → Manage Libraries

Install the following library:

PubSubClient

The WiFi library is already included with the ESP32 board package.

MQTT Configuration

Broker:

broker.hivemq.com

Topic:

garden/soilmoisture

Calibrating the Soil Moisture Sensor

Before using the soil moisture sensor, it is recommended to calibrate it. Calibration helps you determine the sensor values for dry soil and wet soil, making the readings more meaningful.

Why is Calibration Necessary?

Different soil types (sand, clay, garden soil, etc.) and different sensors produce different analog values. By calibrating the sensor, you can convert the raw readings into a percentage or determine when the soil needs watering.

Step 1: Measure the Dry Soil Value

  1. Connect the sensor to the ESP32.
  2. Keep the sensor completely out of the soil or insert it into completely dry soil.
  3. Upload the code and open the Serial Monitor.
  4. Note the displayed analog value.

For example:

Dry Soil Value: 3200

Step 2: Measure the Wet Soil Value

  1. Place the sensor in fully wet soil or dip only the sensing part into water.
  2. Wait for a few seconds until the readings stabilize.
  3. Note the analog value.

For example:

Wet Soil Value: 1400

Step 3: Record the Calibration Values

Suppose your readings are:

Soil Condition Sensor Value
Dry Soil 3200
Wet Soil 1400

These values will be different for every sensor and soil type.

Step 4: Convert the Reading to Moisture Percentage

Instead of displaying raw analog values, convert them into a percentage using the Arduino map() function.

// These values with your calibrated readings

int moisturePercent = map(sensorValue, 3200, 1400, 0, 100);

// Limiting the value between 0 and 100

moisturePercent = constrain(moisturePercent, 0, 100);

Now moisturePercent will be published instead of sensorValue.

Example output:

Soil Moisture: 72%

This is much easier for users to understand than raw analog values.

Recommended Moisture Levels

Moisture Percentage Soil Condition
0–20% Very Dry
21–40% Dry
41–60% Moderate
61–80% Moist
81–100% Very Wet

Tips for Accurate Readings

  • Use a capacitive soil moisture sensor, as it is more reliable than a resistive sensor.
  • Avoid inserting the sensor too deep into the soil.
  • Calibrate the sensor again if you change the soil type.
  • Take multiple readings and calculate the average for improved accuracy.
  • Avoid leaving the sensor submerged in water for long periods.

This approach is more practical for readers because seeing “68% moisture” is much more intuitive than interpreting a raw ADC value like 1847. It also makes your tutorial more professional and ready for future enhancements such as automatic irrigation based on a moisture threshold.

ESP32 Soil Moisture Monitoring Code

Copy and past the entire code in a new arduino file and auto format it by clicking Ctrl + T

Save it.

#include <WiFi.h>
#include <PubSubClient.h>
/* Wi-Fi Credentials */
const char* ssid = “arabindo2g”;
const char* password = “@R@b!nd0”;
/* MQTT Broker Details */
const char* mqtt_server = “broker.hivemq.com”;
const int mqtt_port = 1883;
const char* mqtt_topic = “garden/soilmoisture”;
/* Soil Moisture Sensor Pin */
const int sensorPin = 34;
/* Sensor Calibration Values
Replace these values with your own calibration readings */
const int dryValue = 3200;
const int wetValue = 1400;
WiFiClient espClient;
PubSubClient client(espClient);
/* Connect to Wi-Fi */
void connectWiFi() {
Serial.print(“Connecting to Wi-Fi”);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println(“\nWi-Fi Connected”);
Serial.print(“IP Address: “);
Serial.println(WiFi.localIP());
}
/* Connect to MQTT Broker */
void reconnectMQTT() {
while (!client.connected()) {
Serial.print(“Connecting to MQTT Broker…”);
if (client.connect(“ESP32SoilSensor”)) {
Serial.println(“Connected”);
} else {
Serial.print(“Failed, Error Code: “);
Serial.print(client.state());
Serial.println(” | Retrying in 5 seconds”);
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
connectWiFi();
client.setServer(mqtt_server, mqtt_port);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
if (!client.connected()) {
reconnectMQTT();
}
client.loop();
// Read sensor value
int sensorValue = analogRead(sensorPin);
// Convert raw value to moisture percentage
int moisturePercent = map(sensorValue, dryValue, wetValue, 0, 100);
// Keep value between 0 and 100
moisturePercent = constrain(moisturePercent, 0, 100);
// Convert integer to string
charmoistureString[8];
sprintf(moistureString, “%d”, moisturePercent);
// Publish to MQTT
client.publish(mqtt_topic, moistureString);
// Display values on Serial Monitor
Serial.println(“—————————-“);
Serial.print(“Raw Sensor Value : “);
Serial.println(sensorValue);
Serial.print(“Soil Moisture : “);
Serial.print(moisturePercent);
Serial.println(“%”);
Serial.println(“Data Published to MQTT”);
Serial.println();
delay(5000);
}

Uploading the Code

Follow these steps carefully to upload the program to your ESP32 board.

Step 1: Install the Arduino IDE

The Arduino IDE is the software used to write, edit, compile, and upload code to the ESP32.

  1. Download the latest version of the Arduino IDE from the official Arduino website.
  2. Install the software by following the installation wizard.
  3. Once the installation is complete, open the Arduino IDE.

Note: Make sure you install the latest stable version for the best compatibility with ESP32 boards.

Step 2: Install the ESP32 Board Package

By default, the Arduino IDE does not support ESP32 boards. You need to install the ESP32 board package.

Add the ESP32 Board Manager URL

  1. Open the Arduino IDE.
  2. Go to File → Preferences.
  3. Locate the Additional Boards Manager URLs field.
  4. Paste the following URL:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
  1. Click OK to save the settings.

Install the ESP32 Board

  1. Go to Tools → Board → Boards Manager.
  2. Search for ESP32.
  3. Select ESP32 by Espressif Systems.
  4. Click Install.
  5. Wait for the installation to complete.

Once installed, the Arduino IDE can compile and upload programs for ESP32 boards.

Step 3: Install the PubSubClient Library

The PubSubClient library enables the ESP32 to communicate with an MQTT broker.

To install it:

  1. Open the Arduino IDE.
  2. Go to Sketch → Include Library → Manage Libraries.
  3. In the search box, type PubSubClient.
  4. Find PubSubClient by Nick O’Leary.
  5. Click Install.
  6. Wait for the installation to finish.

After installation, the library is ready to use in your project.

Step 4: Open the Project Code

  1. Copy the ESP32 Soil Moisture Monitoring code from this tutorial.
  2. Open the Arduino IDE.
  3. Create a new sketch by clicking File → New.
  4. Replace the default code with the project code.

Step 5: Update Your Wi-Fi Credentials

Locate the following lines in the code:

const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";

Replace:

YOUR_WIFI_NAME with your Wi-Fi network name.
YOUR_WIFI_PASSWORD with your Wi-Fi password.

For example:

const char* ssid = "HomeWiFi";
const char* password = "mypassword123";

Make sure the ESP32 connects to a 2.4 GHz Wi-Fi network, as most ESP32 boards do not support 5 GHz Wi-Fi.

Step 6: Connect the ESP32 to Your Computer

  1. Connect the ESP32 board to your computer using a USB cable.
  2. Wait for your computer to detect the board.
  3. If the board is not detected, install the required USB-to-Serial driver (CP210x or CH340), depending on your ESP32 board model.

Step 7: Select Your ESP32 Board

In the Arduino IDE:

  1. Click Tools -> Board.
  2. Under the ESP32 Arduino section, select your board.

For most development boards, choose:

ESP32 Dev Module

Step 8: Select the Correct COM Port

  1. Go to Tools → Port.
  2. Select the COM port where your ESP32 is connected.

If you’re unsure which port to choose:

  • Disconnect the ESP32.
  • Check the available ports.
  • Reconnect the ESP32.
  • The newly appeared port is your ESP32.

Step 9: Verify the Code

Before uploading, it’s a good practice to compile the program.

  1. Click the Verify (✓) button in the Arduino IDE.
  2. Wait for the compilation to finish.
  3. If there are no errors, proceed to upload the code.

If any errors appear, check your code for missing libraries or syntax mistakes.

Step 10: Upload the Code

  1. Click the Upload (→) button.
  2. The Arduino IDE will compile the sketch and upload it to the ESP32.
  3. Wait until you see the message:
Done Uploading

If the upload fails, press and hold the BOOT button on the ESP32 while the upload starts, then release it once the upload begins.

Step 11: Open the Serial Monitor

To verify that the ESP32 is working correctly:

  1. Go to Tools → Serial Monitor.
  2. Set the baud rate to: 115200

You should see output similar to:

Connecting to Wi-Fi...
Wi-Fi Connected
MQTT Connected
Moisture: 1825
Moisture: 1832
Moisture: 1818

These values indicate that the ESP32 is successfully reading the soil moisture sensor and publishing the readings to the MQTT broker.

Viewing Soil Moisture Data Using MQTT Explorer

Once you have uploaded the code to the ESP32, you can monitor the soil moisture readings using MQTT Explorer, a free desktop application for Windows, macOS, and Linux.

MQTT Explorer allows you to view MQTT messages in a user-friendly interface without writing any additional code.

Step 1: Download MQTT Explorer

Download and install MQTT Explorer on your computer from its official website.

Step 2: Open MQTT Explorer

Launch the application after installation.

You will see the New Connection window.

Step 3: Configure the MQTT Connection

Enter the following details:

Host broker.hivemq.com
Port 1883
Protocol MQTT

Soil Moisture Monitoring System Using ESP32 and MQTT (Beginner Guide)

Now click on ADVANCED and enter the following details for subscription.

Enter the topic name “garden/soilmoisture” and select the QoS.

And click on ADD

Soil Moisture Monitoring System Using ESP32 and MQTT (Beginner Guide)

Now go back and click CONNECT.

Step 4: Subscribe to the MQTT Topic

After connecting, MQTT Explorer automatically displays all available topics.

Expand the topic tree and look for:

garden
└── soilmoisture

If the topic does not appear immediately, wait a few seconds until the ESP32 publishes new sensor data.

Step 5: View the Sensor Data

Every five seconds, the ESP32 publishes the current soil moisture percentage.

Example output:

45
58
71
82

These values represent the current soil moisture level as a percentage.

  • 0% → Completely Dry Soil
  • 50% → Moderately Moist Soil
  • 100% → Fully Wet Soil

As the soil becomes wetter or drier, the values in MQTT Explorer will automatically update in real time.

Expected Output

You should see the topic structure similar to:

Soil Moisture Monitoring System Using ESP32 and MQTT (Beginner Guide)

This indicates that the ESP32 is successfully publishing the soil moisture percentage to the MQTT broker.

Why MQTT Explorer?

  • Beginner-friendly interface
  • Free and open-source
  • Available for Windows, macOS, and Linux
  • No mobile app configuration required
  • Automatically displays MQTT topics and messages
  • Great for learning and debugging MQTT projects

Every five seconds, the ESP32 publishes the latest soil moisture value, which is displayed on the dashboard.

Applications

  • Smart Irrigation Systems
  • Home Gardening
  • Greenhouses
  • Precision Agriculture
  • Indoor Plant Monitoring
  • Agricultural Research
  • IoT Farming Projects

Advantages

  • Real-time monitoring
  • Low-cost hardware
  • Wireless communication
  • Easy to expand
  • Low power consumption
  • Beginner-friendly
  • Supports cloud monitoring

Troubleshooting

ESP32 does not connect to Wi-Fi

  • Check your Wi-Fi name and password.
  • Ensure the router is powered on.
  • Restart the ESP32.

MQTT connection fails

  • Verify the broker address.
  • Check your internet connection.
  • Confirm the broker port is 1883.

Sensor readings do not change

  • Verify the wiring.
  • Insert the sensor fully into the soil.
  • Use GPIO34 or another analog-capable pin.
  • Avoid powering the sensor with 5V if it is designed for 3.3V.

Future Improvements

This project can be upgraded by adding:

  • Automatic water pump control
  • Relay module
  • Water level sensor
  • OLED display
  • Blynk mobile app
  • Home Assistant integration
  • Email or Telegram alerts
  • Multiple soil moisture sensors

Frequently Asked Questions (FAQs)

Can I use ESP8266 instead of ESP32?

Yes. The code can be modified for ESP8266 with minor changes.

Which soil moisture sensor is better?

A capacitive soil moisture sensor is generally better because it offers improved durability and more stable readings.

Can I monitor multiple plants?

Yes. Connect additional sensors to available analog input pins or use an analog multiplexer.

Can I build an automatic irrigation system?

Yes. Add a relay module and a water pump to automatically water plants when the soil becomes dry.

Conclusion

Building a Soil Moisture Monitoring System using ESP32 and MQTT is an excellent beginner IoT project that teaches sensor interfacing, Wi-Fi communication, and MQTT messaging. It provides real-time soil moisture data that can be monitored from anywhere through an MQTT dashboard. Once you understand this project, you can easily extend it into a fully automated smart irrigation system by adding a relay and water pump.

Related MQTT Tutorials:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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