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

I am only writing to let you understand of the fabulous experience my princess encountered checking your blog. She noticed plenty of pieces, not to mention what it's like to possess a marvelous coaching mood to make certain people effortlessly know just exactly chosen very confusing subject matter. You undoubtedly did more than people's expectations. Thanks for displaying such important, safe, educational not to mention fun tips on your topic to Lizeth.

I and also my friends were actually reading through the great information and facts on your web page and instantly came up with a terrible suspicion I had not expressed respect to the site owner for those tips. All of the boys were definitely for that reason joyful to see all of them and have in fact been using these things. We appreciate you turning out to be really kind as well as for pick out these kinds of magnificent useful guides most people are really desirous to learn about. Our own honest apologies for not expressing gratitude to you sooner.

I'm just writing to let you be aware of of the perfect encounter my girl undergone studying your webblog. She even learned several issues, with the inclusion of what it is like to possess a marvelous helping style to have most people clearly learn about specific extremely tough matters. You really exceeded our own expectations. Many thanks for rendering those warm and friendly, dependable, informative as well as unique tips about the topic to Ethel.

I not to mention my pals have been checking the good solutions found on your web site then unexpectedly got a horrible feeling I had not expressed respect to you for those tips. The men had been as a result joyful to study all of them and have in effect in reality been taking advantage of these things. Many thanks for indeed being indeed accommodating as well as for choosing varieties of perfect tips most people are really needing to learn about. My very own sincere regret for not expressing gratitude to you sooner.

I needed to write you a bit of word to thank you very much yet again for your fantastic techniques you've provided at this time. It is certainly strangely generous with people like you to grant extensively precisely what most of us could have offered for sale for an e book to help with making some money on their own, specifically given that you might have done it if you ever considered necessary. The guidelines as well worked to be the fantastic way to know that the rest have the identical interest the same as my very own to know the truth a little more with reference to this condition. I am certain there are some more pleasant opportunities ahead for individuals that view your site.

My husband and i got absolutely glad that Jordan managed to carry out his studies using the ideas he discovered using your web page. It is now and again perplexing to simply happen to be making a gift of strategies that many others have been trying to sell. We really already know we now have the writer to thank for this. All of the illustrations you've made, the simple site menu, the friendships you help to foster - it is most overwhelming, and it's letting our son and the family imagine that this subject matter is amusing, which is certainly highly mandatory. Thank you for all!

I am just commenting to let you be aware of of the notable discovery my friend's daughter obtained visiting your site. She came to understand many issues, with the inclusion of what it's like to have a great coaching mindset to have many people easily learn certain impossible topics. You really exceeded people's desires. I appreciate you for showing these helpful, trusted, edifying and as well as unique tips about this topic to Emily.

I enjoy you because of your own effort on this site. Kim really likes managing research and it's really simple to grasp why. My partner and i know all relating to the powerful tactic you present functional secrets via the blog and invigorate response from other people on this article and my girl is actually understanding a whole lot. Enjoy the remaining portion of the year. You are always doing a fabulous job.

I have to show some thanks to this writer for rescuing me from such a difficulty. Just after browsing throughout the world-wide-web and getting tips which were not beneficial, I believed my life was over. Living devoid of the solutions to the issues you've fixed as a result of the site is a serious case, as well as those that could have in a negative way damaged my career if I hadn't come across your web blog. The mastery and kindness in maneuvering almost everything was helpful. I am not sure what I would have done if I had not come upon such a thing like this. I'm able to at this point look forward to my future. Thank you so much for this reliable and amazing help. I will not be reluctant to propose your web blog to any individual who should receive direction about this topic.

I simply had to say thanks all over again. I'm not certain the things that I might have gone through without those creative concepts documented by you over my subject. This has been a distressing difficulty in my circumstances, nevertheless finding out your specialised tactic you processed it took me to weep over fulfillment. I am just happier for the work and then expect you recognize what a great job you happen to be undertaking instructing many people using your webblog. Most likely you have never come across all of us.

Thank you for all your labor on this blog. My niece delights in setting aside time for research and it is simple to grasp why. Many of us notice all concerning the dynamic mode you give advantageous tactics via the web site and as well as recommend contribution from other individuals on that issue then our princess is really becoming educated a whole lot. Have fun with the remaining portion of the year. You have been carrying out a stunning job.

A lot of thanks for each of your labor on this website. Betty take interest in participating in internet research and it's really simple to grasp why. A lot of people hear all concerning the powerful tactic you make valuable things on this blog and even increase contribution from some others about this area of interest so our own child is without question learning a lot. Take advantage of the remaining portion of the new year. You are always performing a glorious job.

I precisely wished to thank you so much yet again. I am not sure the things that I might have used in the absence of the techniques revealed by you regarding my industry. It was before the frightening circumstance in my position, but looking at this professional avenue you dealt with it forced me to jump with fulfillment. Now i am thankful for the help and even expect you really know what a great job that you are putting in educating many people thru your webpage. I know that you've never got to know any of us.

I intended to create you that very small remark to finally give many thanks yet again for those extraordinary knowledge you've discussed on this page. It's certainly strangely open-handed with you to supply unreservedly what many people would've advertised for an ebook to get some bucks on their own, notably now that you could possibly have done it if you ever decided. Those tactics likewise acted to provide a good way to be certain that other people have the identical interest really like my personal own to realize more around this condition. Certainly there are millions of more enjoyable sessions up front for folks who read through your site.

I would like to show my appreciation to this writer for rescuing me from such a problem. After exploring through the internet and getting proposals which were not pleasant, I thought my life was gone. Existing devoid of the solutions to the difficulties you've resolved as a result of your good guide is a serious case, and the kind that might have in a negative way affected my entire career if I had not discovered the website. The capability and kindness in handling all the details was excellent. I'm not sure what I would've done if I had not come across such a stuff like this. I'm able to now look forward to my future. Thanks a lot so much for this high quality and effective guide. I won't think twice to propose your web sites to anybody who would like counselling about this matter.

I wanted to compose a quick remark to be able to say thanks to you for all the stunning pointers you are giving on this website. My extended internet search has finally been compensated with incredibly good ideas to share with my friends and classmates. I would repeat that many of us site visitors are definitely endowed to live in a superb place with very many lovely professionals with interesting tactics. I feel pretty fortunate to have used your webpages and look forward to so many more pleasurable minutes reading here. Thank you once more for everything.

I have to express my appreciation to this writer just for bailing me out of this condition. Because of searching throughout the search engines and obtaining views that were not helpful, I thought my life was over. Living without the presence of strategies to the problems you have solved all through your short article is a crucial case, and those that would have in a wrong way affected my entire career if I hadn't encountered your web page. Your own capability and kindness in controlling the whole lot was invaluable. I don't know what I would've done if I hadn't come across such a point like this. I can at this time look forward to my future. Thanks very much for the specialized and effective help. I will not hesitate to endorse your web sites to anybody who would like assistance about this matter.

I simply had to thank you very much once more. I'm not certain the things that I could possibly have sorted out without the entire aspects shared by you about my field. It absolutely was the horrifying concern for me, however , taking a look at the well-written strategy you solved it forced me to jump over delight. I'm happier for the guidance and even sincerely hope you recognize what an amazing job you are always accomplishing training people today with the aid of a blog. Probably you have never encountered all of us.

Thanks a lot for giving everyone an extremely spectacular opportunity to discover important secrets from this website. It really is very cool and also jam-packed with a good time for me and my office colleagues to visit your site at the very least three times in a week to find out the new tips you will have. And of course, I'm so usually motivated with the sensational suggestions you serve. Selected 2 ideas in this posting are really the best we have had.

I needed to compose you that little observation to finally thank you again for those fantastic principles you have contributed in this article. It has been simply wonderfully open-handed with people like you in giving easily just what a few individuals could have marketed for an e book to get some bucks for their own end, and in particular considering the fact that you could have done it in case you wanted. The smart ideas likewise worked like a good way to know that the rest have the same fervor much like my very own to grasp great deal more on the topic of this problem. I believe there are a lot more enjoyable situations up front for individuals that read through your website.

Thank you so much for giving everyone a very brilliant possiblity to check tips from this website. It is always very excellent and as well , stuffed with amusement for me and my office fellow workers to visit the blog on the least three times per week to see the newest issues you have got. And definitely, we are always happy with your amazing principles you serve. Selected two ideas in this posting are absolutely the best we have all had.

I抦 impressed, I need to say. Really rarely do I encounter a weblog that抯 each educative and entertaining, and let me let you know, you have hit the nail on the head. Your concept is outstanding; the problem is something that not sufficient persons are talking intelligently about. I'm very comfortable that I stumbled throughout this in my seek for one thing referring to this.

I wish to point out my gratitude for your generosity supporting those people that have the need for help on this area of interest. Your very own commitment to passing the solution along came to be extraordinarily interesting and has without exception encouraged associates much like me to achieve their goals. The warm and friendly publication signifies much to me and still more to my office workers. Thank you; from everyone of us.

I am just commenting to let you be aware of of the awesome experience my girl gained reading your webblog. She realized such a lot of pieces, including how it is like to possess an awesome coaching mood to get the others with no trouble comprehend certain tortuous issues. You really exceeded my desires. I appreciate you for imparting those beneficial, trustworthy, educational and even cool tips about your topic to Janet.

Good post. I learn something more challenging on completely different blogs everyday. It'll all the time be stimulating to learn content from other writers and apply a bit something from their store. I抎 desire to make use of some with the content material on my weblog whether you don抰 mind. Natually I抣l offer you a hyperlink on your internet blog. Thanks for sharing.

I precisely had to say thanks yet again. I am not sure the things that I could possibly have done in the absence of those tips provided by you directly on such question. This has been the traumatic matter in my opinion, however , witnessing the well-written tactic you handled the issue forced me to jump over joy. I am just happy for your support and even trust you realize what a great job that you are putting in instructing the rest using your site. Probably you have never got to know any of us.

I wish to convey my passion for your kindness in support of women who must have help with this important topic. Your very own commitment to passing the message all over was really powerful and have continuously allowed women much like me to realize their pursuits. Your own helpful key points denotes much a person like me and still more to my mates. Many thanks; from each one of us.

My spouse and i got more than happy when Jordan managed to round up his survey through the ideas he came across out of the blog. It is now and again perplexing just to continually be handing out information which usually many people have been making money from. We figure out we've got the blog owner to appreciate for that. The specific illustrations you made, the straightforward web site menu, the friendships you will make it possible to promote - it's got all superb, and it is making our son in addition to our family imagine that that situation is excellent, and that's rather pressing. Thank you for all!

Thank you so much for providing individuals with an extraordinarily pleasant chance to read articles and blog posts from this website. It is always very pleasing and also full of a lot of fun for me personally and my office friends to visit the blog at least three times in one week to read through the latest guidance you will have. And lastly, I am actually happy with your great principles served by you. Some 3 points in this posting are honestly the most efficient I have ever had.

I want to show my thanks to the writer just for rescuing me from such a issue. Because of scouting through the search engines and coming across solutions that were not helpful, I figured my life was over. Living without the presence of approaches to the issues you've resolved through this review is a serious case, as well as the kind that would have badly affected my entire career if I had not come across the website. Your good capability and kindness in taking care of almost everything was crucial. I am not sure what I would have done if I had not come across such a thing like this. I am able to at this time look ahead to my future. Thank you so much for your professional and sensible help. I won't be reluctant to recommend the sites to anybody who would like tips on this subject matter.

I must show some appreciation to the writer for bailing me out of this type of dilemma. Right after researching throughout the world-wide-web and coming across notions which were not pleasant, I was thinking my life was done. Being alive without the strategies to the difficulties you've fixed by way of your entire blog post is a crucial case, as well as the kind which may have badly damaged my career if I hadn't come across your blog post. Your actual talents and kindness in taking care of all the things was valuable. I don't know what I would have done if I hadn't come across such a thing like this. It's possible to at this time look ahead to my future. Thanks very much for this reliable and amazing help. I won't think twice to endorse your site to anyone who needs and wants support on this subject.

I must express my appreciation to this writer for rescuing me from this particular trouble. Because of searching throughout the internet and coming across principles that were not beneficial, I figured my life was gone. Being alive minus the solutions to the difficulties you've fixed through your main guideline is a serious case, and those which may have in a negative way affected my career if I hadn't noticed your web page. That capability and kindness in taking care of the whole lot was useful. I'm not sure what I would have done if I had not come across such a solution like this. I can at this moment look forward to my future. Thanks very much for the skilled and sensible help. I will not be reluctant to refer the website to any individual who desires recommendations on this subject matter.

Thank you a lot for giving everyone an extremely splendid possiblity to read from this web site. It's usually so brilliant and packed with amusement for me personally and my office fellow workers to visit the blog particularly three times every week to read through the new items you will have. Not to mention, I'm also always motivated concerning the effective solutions you give. Certain 3 areas on this page are truly the very best I have ever had.

I truly wanted to write down a brief note to be able to appreciate you for those remarkable ideas you are giving here. My particularly long internet search has now been compensated with incredibly good points to exchange with my colleagues. I 'd point out that many of us site visitors actually are undeniably lucky to exist in a really good site with so many perfect individuals with helpful tips and hints. I feel quite grateful to have discovered the webpage and look forward to many more entertaining times reading here. Thank you again for everything.

I definitely wanted to develop a simple message to express gratitude to you for all of the fabulous tactics you are showing at this website. My time consuming internet investigation has now been paid with professional content to go over with my neighbours. I would say that we readers actually are undoubtedly fortunate to dwell in a magnificent community with so many awesome professionals with beneficial things. I feel very fortunate to have come across the webpages and look forward to plenty of more exciting moments reading here. Thanks once more for a lot of things.

I wish to get across my gratitude for your generosity in support of people who absolutely need help with the niche. Your real commitment to passing the message throughout had become quite good and has helped guys like me to get to their ambitions. Your new invaluable guidelines means so much to me and even more to my mates. Warm regards; from everyone of us.

Thanks a lot for giving everyone such a wonderful possiblity to discover important secrets from this site. It is often so beneficial plus stuffed with fun for me personally and my office co-workers to search your blog particularly 3 times in a week to see the new things you have got. And of course, I'm so actually impressed considering the extraordinary advice you give. Selected 2 areas in this article are unequivocally the very best I've ever had.

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.