IoT based Soil Moisture Monitoring System using ESP32

IoT based Soil Moisture Monitoring System using ESP32

We previously used a soil moisture sensor with ESP8266 to build a smart irrigation system. Today we used soil moisture sensor with ESP32 to build an IoT based moisture monitoring System, where the soil moisture will be displayed in percentage (%) on Adafruit dashboard in form of graph as well as on OLED display in form of numbers.

 

Components Required

  • ESP32
  • Soil Moisture Sensor
  • OLED Display
  • Connecting Wires

 

OLED Display

OLED

The OLED displays are one of the most common and easily available displays for a microcontroller. This display can easily be interfaced with microcontroller using IIC or using SPI communication and has a good view angle and pixel density which makes it reliable for displaying small level graphics. It is compatible with any 3.3V-5V microcontroller, such as Arduino. The OLED display comes with a powerful single-chip CMOS OLED driver controller – SSD1306 that handles the entire RAM buffering. The SSD1306 driver has a built-in 1KB Graphic Display Data RAM (GDDRAM). We previously interfaced OLED with ESP32.

 

Specifications

  • OLED Driver IC: SSD1306
  • Resolution: 128 x 64
  • Visual Angle: >160°
  • Input Voltage: 3.3V ~ 6V
  • Pixel Colour: Blue
  • Working temperature: -30°C ~ 70°C

 

Circuit Diagram

Circuit Diagram for ESP32 Moisture Sensor is given below.

ESP32 Moisture Sensor Circuit Diagram

We are interfacing the ESP32 with Soil Moisture Sensor and OLED Display. Vcc and GND pin of the Soil Moisture sensor is connected to 3.3V and GND of ESP32, while the Analog pin of Moisture sensor is connected to the VP pin of ESP32. I2C mode is used to connect the OLED display Module (SSD1306) with ESP32. Connections between ESP32 and OLED Display are given as:

OLED Pin

ESP32 Pin

Vcc

3.3v

GND

GND

SCL

D22

SDA

D21

ESP32 Moisture Monitoring System

 

Adafruit IO Setup for ESP32 Soil Moisture Sensor

Adafruit IO is an open data platform that allows you to aggregate, visualize, and analyze live data on the cloud. Using Adafruit IO, you can upload, display, and monitor your data over the internet, and make your project IoT enabled. You can control motors, read sensor data, and make cool IoT applications over the internet using Adafruit IO. We previously used Adafruit with ESP32 and also built many IoT based applications using Adafruit.

 

To use Adafruit IO, first, you have to create an account on Adafruit IO. To do this, go to the Adafruit IO website and click on ‘Get started for Free’ on the top right of the screen.

Adafruit IO

 

After finishing the account creation process, log in to your account and click on ‘View AIO Key’ on the top right corner to get your account username and AIO key.

AIO Key

 

When you click on ‘AIO Key,’ a window will pop up with your Adafruit IO AIO Key and username. Copy this key and username, it will be needed later in the code.

Adafruit IO Key

 

Now after this, you need to create a feed. To create a feed, click on ‘Feed.’ Then click on ‘Actions’, you will see some options, from them, click on ‘Create a New Feed.’

Create A New Feed For Adafruit

 

After this, a new window will open where you need to input the Name and Description of your feed. The writing description is optional.

Adafruit Feed

Click on ‘Create’ and you will be redirected to your newly created feed.

After creating the feed, now we will create an Adafruit IO dashboard to visualize the feed data. To create a dashboard, click on the Dashboard option and then click on the ‘Action’ and after this, click on ‘Create a New Dashboard’.

 

In the next window, enter the name for your dashboard and click on ‘Create’.

Create New Dashboard For Adafruit

 

As our dashboard is created, now we will add some visualization blocks in the dashboard. To add a block, click on the ‘+’ in the top right corner.

Adafruit Add Blocks

Here we are going to use a link chart to visualize our Moisture data in Graph format.

 

To add a Line chart on the dashboard, select the line chart block.

New Blocks In AIO

 

In the next window, it will ask you to choose the feed, so click on Agriculture data feed.

Moisture Monitoring Feed

After this, click on ‘Next step’ and then enter the X-axis and Y-axis label names. With this step, your dashboard is ready to visualize the Moisture data.

 

Programming ESP32 for Moisture Monitoring

The complete code for the ESP32 Soil Moisture Monitoring System is given at the end of the article. Here we are explaining some important parts of code. Here few libraries are used (Wire.h, SH1106.h, and Adafruit_MQTT.h) which can be downloaded from below links:

 

So as usual, start the code by including all the required libraries.

#include <WiFi.h>
#include <Wire.h>
#include<SH1106.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

 

Then include the WiFi and Adafruit IO credentials that are copied from the Adafruit IO server. These will include the MQTT server, Port No, User Name, and AIO Key.

const char *ssid =  "WiFi Name";     // Enter your WiFi Name
const char *pass =  "Password";  // Enter your WiFi Password
#define MQTT_SERV "io.adafruit.com"
#define MQTT_PORT 1883
#define MQTT_NAME "User Name"
#define MQTT_PASS "AIO Key"

 

After that define all the pins where you have connected the OLED display and create an instance for the display.

SH1106 display(0x3c, 21, 22);

Also, define the pin where the Soil Moisture sensor is connected. The soil moisture sensor is connected to the VP pin of ESP32.

const int moisturePin = A0;

 

Then setup the Adafruit IO feed to publish the Moisture data. Here AgricultureData is the feed name.

Adafruit_MQTT_PublishAgricultureData = Adafruit_MQTT_Publish(&mqtt,MQTT_NAME "/f/AgricultureData");

 

Inside the setup() function, initialize the Serial Monitor at a baud rate of 115200 for debugging purposes and also initialize the OLED display with the begin() method.

void setup()
{
  Serial.begin(115200);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
   }
  Serial.println("WiFi connected");
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
}

 

Inside the loop() function, read the moisture data from the sensor and print the readings on the OLED display.

moisturePercentage = ( 100.00 - ( (analogRead(moisturePin) / 1023.00) * 100.00 ) );
Serial.print(moisturePercentage);
Serial.println("%");
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.setFont(ArialMT_Plain_24);
display.drawString(50, 0, "Soil");
display.drawString(25, 20, "Moisture");
String data1 = String(moisturePercentage);
display.drawString(45, 40, data1);
display.drawString(60, 40, "0 %");
  }

 

Once the hardware and the program are ready, it is time to upload the program into your ESP32 Board. Here Arduino IDE is used to upload the Moisture Monitoring code to ESP32 board, so connect the ESP32 to your laptop with a Micro USB Cable and hit the upload button. Once the code is uploaded, the OLED Display and Adafruit IO will start showing the soil moisture value in percentage (%) as shown in the below figure.

Soil Moisture Monitoring System Working

Moisture Monitoring

The complete code and working video for this ESP32 Soil Moisture Sensor project are given below.

Code

#include <WiFi.h>
#include <Wire.h>               // Only needed for Arduino 1.6.5 and earlier
#include<SH1106.h>      // legacy: #include "SSD1306.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
const char *ssid =  "Galaxy-M20";     // Enter your WiFi Name
const char *pass =  "ac312129"; // Enter your WiFi Password
SH1106 display(0x3c, 21, 22);
WiFiClient client;
#define MQTT_SERV "io.adafruit.com"
#define MQTT_PORT 1883
#define MQTT_NAME "choudharyas" // Your Adafruit IO Username
#define MQTT_PASS "988c4e045ef64c1b9bc8b5bb7ef5f2d9" // Adafruit IO AIO key
const int moisturePin = A0;             // moisteure sensor pin
int moisturePercentage;              //moisture reading
//Set up the feed you're publishing to
Adafruit_MQTT_Client mqtt(&client, MQTT_SERV, MQTT_PORT, MQTT_NAME, MQTT_PASS);
Adafruit_MQTT_Publish AgricultureData = Adafruit_MQTT_Publish(&mqtt,MQTT_NAME "/f/AgricultureData");  // AgricultureData is the feed name where you will publish your data
void setup()
{
  Serial.begin(115200);
  delay(10);
  Serial.println("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");              // print ... till not connected
  }
  Serial.println("");
  Serial.println("WiFi connected");
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
}
 void loop()
{
    MQTT_connect();
  moisturePercentage = ( 100 - ( (analogRead(moisturePin) / 1023.00) * 100 ) );
  Serial.print("Soil Moisture is  = ");
  Serial.print(moisturePercentage);
  Serial.println("%");
  display.clear();
  display.setTextAlignment(TEXT_ALIGN_RIGHT);
  display.drawString(10, 128, String(millis()));
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(ArialMT_Plain_24);
  display.drawString(50, 0, "Soil");
  display.drawString(25, 20, "Moisture");
  //display.setFont(ArialMT_Plain_24);
  String data1 = String(moisturePercentage);
  display.drawString(45, 40, data1);
  display.drawString(60, 40, "0 %");
  display.display();
       if (! AgricultureData.publish(moisturePercentage)) //This condition is used to publish the Variable (moisturePercentage) on adafruit IO. Change thevariable according to yours.
       {                     
         delay(5000);   
          }
 delay(6000);
}
void MQTT_connect() 
{
  int8_t ret;
  // Stop if already connected.
  if (mqtt.connected()) 
  {
    return;
  }
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) // connect will return 0 for connected
  { 
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) 
       {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
}

Video

145 Comments

Sir I need your help on iot health monitoring system using esp32 source code.
As you proceed to my request may almighty God help you sir. remain blessed.

A powerful share, I just given this onto a colleague who was doing a little bit analysis on this. And he in actual fact purchased me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to debate this, I really feel strongly about it and love reading extra on this topic. If doable, as you become experience, would you mind updating your blog with extra details? It is highly helpful for me. Big thumb up for this blog put up!

Thank you for all of the efforts on this site. My daughter enjoys making time for investigation and it's easy to understand why. Many of us know all regarding the dynamic mode you convey both useful and interesting secrets by means of the website and as well foster response from others on that matter while my princess is undoubtedly understanding a whole lot. Take advantage of the remaining portion of the new year. You're the one doing a superb job.

hi team, i am trying to connect esp32 to moisture sensor but not getting the value in + % instead getting -300% when openly kept, about -70 when kept in water and in dry soil around -250% is visible on moniter. when running the same code on esp8266 it is working fine. I don't know why. Can you suggest something how to get accurate value from esp32. (same pin config)

I enjoy you because of all your efforts on this blog. Kim really likes doing research and it is obvious why. My partner and i know all about the powerful form you present informative steps by means of your blog and encourage contribution from some others about this subject matter plus my child is truly being taught a whole lot. Enjoy the remaining portion of the year. You are carrying out a very good job.

I and also my guys appeared to be following the best recommendations on your web site then before long developed an awful feeling I never thanked the website owner for those strategies. All of the women happened to be for this reason passionate to read all of them and now have very much been using those things. Thank you for genuinely well kind and then for deciding upon these kinds of wonderful topics millions of individuals are really needing to be aware of. My personal sincere regret for not expressing gratitude to you sooner.

Hi, I do believe this is a great web site. I stumbledupon it ;) I may come back yet again since i have bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to guide others.|

The subsequent time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I mean, I know it was my option to learn, however I really thought youd have one thing fascinating to say. All I hear is a bunch of whining about something that you could fix if you happen to werent too busy searching for attention.

I wanted to jot down a brief note so as to say thanks to you for some of the lovely facts you are sharing on this website. My rather long internet investigation has finally been paid with high-quality points to write about with my companions. I would say that many of us site visitors actually are undeniably fortunate to live in a magnificent site with so many lovely people with useful methods. I feel rather blessed to have discovered the web site and look forward to so many more thrilling minutes reading here. Thank you once more for all the details.

Thanks for each of your effort on this site. Ellie really loves doing internet research and it's simple to grasp why. A number of us notice all concerning the compelling method you make sensible secrets by means of this blog and as well strongly encourage participation from website visitors on the subject while our own daughter is without a doubt starting to learn a lot. Take pleasure in the rest of the year. You have been performing a fabulous job.

I intended to compose you a very small observation in order to say thanks once again for those splendid methods you have contributed in this case. It is certainly surprisingly open-handed of you in giving openly all that most of us would have made available for an e-book to help make some bucks on their own, principally seeing that you could have done it in case you decided. Those tricks in addition served to become easy way to realize that other people have a similar desire the same as my own to grasp many more when it comes to this matter. Certainly there are some more pleasant periods ahead for those who check out your site.

I in addition to my guys came digesting the nice tricks found on the website while all of a sudden I got a horrible suspicion I had not thanked the website owner for those secrets. All of the men appeared to be consequently very interested to learn them and have unquestionably been making the most of those things. Thank you for getting considerably thoughtful and also for considering this sort of exceptional tips most people are really eager to be informed on. My sincere apologies for not expressing appreciation to sooner.

I and my buddies were found to be analyzing the excellent ideas found on your site and so the sudden came up with a terrible suspicion I never thanked you for those strategies. Those young men appeared to be joyful to see all of them and have definitely been making the most of these things. We appreciate you really being very helpful and then for choosing this sort of excellent things millions of individuals are really desirous to know about. Our own sincere regret for not expressing appreciation to sooner.

I would like to point out my love for your generosity in support of people who have the need for help on this important study. Your very own commitment to getting the message along ended up being exceptionally insightful and have specifically made ladies just like me to get to their goals. Your entire interesting guide implies a whole lot a person like me and especially to my peers. Best wishes; from all of us.

I enjoy you because of each of your effort on this web page. Kim delights in working on internet research and it's simple to grasp why. I notice all relating to the powerful mode you provide helpful thoughts through this website and therefore attract participation from the others on the content while our own simple princess is now starting to learn a great deal. Take pleasure in the rest of the new year. You're carrying out a fantastic job.

Thank you so much for providing individuals with such a remarkable opportunity to read articles and blog posts from this blog. It can be so useful and jam-packed with a good time for me personally and my office friends to search the blog minimum 3 times in 7 days to study the newest guidance you will have. And of course, I'm so usually contented with your good ideas you give. Selected 1 areas on this page are unequivocally the most suitable we have ever had.

My husband and i felt very cheerful when Emmanuel could conclude his survey via the ideas he gained from your own web page. It is now and again perplexing just to always be giving away steps which often men and women may have been trying to sell. And we also know we've got the blog owner to be grateful to because of that. Most of the explanations you've made, the easy blog navigation, the friendships you aid to engender - it is all astonishing, and it is making our son and us feel that this matter is fun, and that is highly essential. Many thanks for all!

I simply desired to appreciate you all over again. I do not know the things I might have made to happen in the absence of those basics shared by you over that theme. It had been a real scary matter in my position, nevertheless discovering this professional technique you resolved that made me to cry over delight. I am happier for this information and thus trust you realize what an amazing job you were putting in educating some other people with the aid of a web site. I know that you haven't come across all of us.

A powerful share, I just given this onto a colleague who was doing just a little evaluation on this. And he actually purchased me breakfast because I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying extra on this topic. If possible, as you change into experience, would you thoughts updating your blog with extra particulars? It is extremely helpful for me. Big thumb up for this weblog submit!

I precisely desired to thank you so much yet again. I am not sure the things I would have created in the absence of these creative ideas discussed by you about my industry. It was actually an absolute horrifying circumstance in my view, however , taking note of a new specialised strategy you processed it made me to leap over fulfillment. Now i am thankful for the assistance and sincerely hope you find out what a great job you have been undertaking instructing others through your web blog. Most likely you have never met any of us.

I'm just writing to make you know what a brilliant discovery my cousin's child undergone studying your web site. She came to understand so many issues, most notably how it is like to possess an awesome giving nature to have men and women just know precisely specific impossible things. You actually did more than our expectations. Thanks for distributing such informative, safe, informative and in addition cool tips on the topic to Evelyn.

I and also my friends have been looking at the best items found on your site and all of a sudden developed an awful suspicion I never expressed respect to the site owner for them. All of the people came for this reason very interested to learn all of them and have pretty much been using these things. We appreciate you actually being indeed thoughtful and then for finding this sort of marvelous useful guides millions of individuals are really desirous to learn about. Our own sincere apologies for not expressing gratitude to sooner.

I am glad for commenting to let you be aware of what a really good encounter our daughter found reading your web page. She noticed lots of details, which include what it is like to possess an ideal teaching character to let most people completely comprehend chosen complicated topics. You truly surpassed our expected results. Many thanks for presenting those warm and friendly, dependable, educational and cool tips on that topic to Sandra.

I am only writing to make you know what a wonderful experience my girl obtained using your web page. She even learned so many pieces, with the inclusion of what it is like to have a marvelous giving heart to make many more completely learn some problematic issues. You really did more than our own desires. Thanks for distributing the necessary, safe, edifying and also easy guidance on that topic to Emily.

Thanks so much for providing individuals with an extraordinarily special possiblity to read articles and blog posts from this blog. It's always so fantastic and also stuffed with fun for me personally and my office acquaintances to search your site really 3 times every week to learn the new things you have got. Of course, I am also always contented with the excellent things you serve. Selected 2 tips in this article are completely the most efficient we have all had.

I am just commenting to let you be aware of what a fine encounter our princess undergone studying your site. She figured out lots of issues, which include how it is like to have an awesome teaching character to make men and women very easily completely grasp several very confusing matters. You really exceeded my expectations. I appreciate you for offering those good, trusted, informative and easy thoughts on this topic to Evelyn.

A formidable share, I just given this onto a colleague who was doing a little evaluation on this. And he in actual fact bought me breakfast because I discovered it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying extra on this topic. If attainable, as you change into expertise, would you mind updating your blog with more particulars? It is extremely useful for me. Big thumb up for this blog submit!

I have to voice my affection for your kind-heartedness giving support to folks that absolutely need guidance on your study. Your personal dedication to passing the solution all-around had been quite functional and have specifically enabled men and women like me to get to their goals. The useful instruction signifies a whole lot to me and even more to my peers. Thanks a ton; from all of us.

Thanks so much for providing individuals with an extremely wonderful chance to discover important secrets from this web site. It really is so awesome and as well , stuffed with a good time for me and my office acquaintances to search your website at the very least thrice in a week to study the latest guides you have. And of course, I'm at all times astounded with the terrific concepts you serve. Certain 2 points in this posting are definitely the simplest we've had.

I not to mention my buddies have been examining the great techniques found on the blog while instantly I got a horrible feeling I had not expressed respect to you for those strategies. Most of the young boys are actually for this reason joyful to read all of them and have simply been making the most of these things. Appreciate your simply being indeed helpful and for selecting this sort of helpful information most people are really desirous to discover. My personal sincere apologies for not saying thanks to you sooner.

I'm also commenting to let you be aware of what a fabulous discovery my wife's daughter gained using your site. She picked up several things, not to mention what it's like to have a great teaching nature to have many people with ease know chosen advanced subject matter. You actually surpassed visitors' expectations. I appreciate you for rendering such priceless, trustworthy, explanatory not to mention easy guidance on this topic to Kate.

I must express my affection for your generosity for persons that should have help with that content. Your personal commitment to passing the solution all over ended up being particularly helpful and has continuously permitted associates like me to realize their aims. Your new useful report denotes a great deal a person like me and still more to my office workers. Thanks a lot; from each one of us.

I am also commenting to let you know of the really good encounter my friend's girl encountered browsing yuor web blog. She came to understand numerous things, which included how it is like to possess a very effective teaching mindset to have many others quite simply gain knowledge of various specialized topics. You actually did more than our expectations. Many thanks for imparting the practical, trusted, edifying as well as easy tips about this topic to Janet.

I want to express my admiration for your kind-heartedness in support of people that actually need assistance with the niche. Your personal dedication to passing the solution all-around appears to be surprisingly useful and have in most cases encouraged most people just like me to reach their targets. The warm and friendly useful information entails a great deal a person like me and a whole lot more to my office colleagues. Thank you; from everyone of us.

My husband and i have been happy Emmanuel could finish off his web research through the ideas he grabbed using your web site. It's not at all simplistic just to continually be giving freely hints that the rest have been trying to sell. We fully grasp we have the writer to give thanks to for this. The main illustrations you made, the simple blog navigation, the relationships you can make it possible to foster - it is all fantastic, and it's really helping our son in addition to the family recognize that this matter is awesome, which is incredibly vital. Thanks for all the pieces!

I in addition to my guys came reviewing the excellent strategies found on the website and so all of the sudden I had a horrible feeling I never thanked the blog owner for those tips. All the ladies happened to be as a result excited to learn all of them and have pretty much been taking advantage of these things. Many thanks for actually being indeed kind and for choosing this kind of extraordinary ideas millions of individuals are really desperate to be informed on. Our honest regret for not saying thanks to you earlier.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.