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

255 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.

I'm also commenting to make you know of the nice encounter my cousin's girl developed going through the blog. She mastered a good number of issues, including what it is like to possess an excellent helping character to have many more smoothly know just exactly specific grueling topics. You really surpassed people's expected results. Thanks for giving these necessary, healthy, revealing and cool tips on this topic to Jane.

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 valuable labor on this site. Kate really likes participating in research and it is easy to understand why. Many of us notice all relating to the dynamic ways you present useful strategies on the web blog and as well as inspire participation from people on this point while our own daughter is really learning a great deal. Take advantage of the rest of the year. Your performing a fabulous job.

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 intended to post you this very small word to help say thanks a lot over again for all the marvelous secrets you have provided in this article. It is simply shockingly generous of people like you to supply extensively all that many individuals would've offered for an ebook to end up making some profit for themselves, most notably considering that you might have done it in case you wanted. The techniques also acted to provide a good way to understand that other individuals have a similar eagerness similar to my personal own to know the truth great deal more around this condition. I'm sure there are a lot more pleasurable times in the future for folks who check out your blog post.

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.

I truly wanted to construct a word to be able to say thanks to you for the magnificent tips and hints you are writing on this website. My considerable internet lookup has at the end been rewarded with excellent ideas to write about with my close friends. I would believe that many of us readers are very fortunate to live in a fantastic site with so many marvellous people with good techniques. I feel really lucky to have come across the web pages and look forward to plenty of more amazing times reading here. Thanks once more for everything.

Thank you a lot for giving everyone an extraordinarily marvellous chance to read from this website. It really is very amazing and as well , stuffed with fun for me and my office fellow workers to search your site more than three times in one week to see the new secrets you will have. And indeed, I'm actually satisfied for the superb knowledge served by you. Selected 1 facts in this posting are absolutely the simplest we have had.

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.

I intended to send you a very little observation to thank you so much as before regarding the extraordinary views you've shown above. It's simply strangely generous of people like you to grant easily precisely what most of us would have supplied as an ebook to help with making some profit on their own, specifically since you might well have done it in case you desired. The smart ideas likewise acted as a good way to fully grasp that someone else have a similar desire the same as mine to grasp a good deal more with respect to this problem. I am sure there are millions of more enjoyable situations in the future for individuals that browse through your site.

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.

A lot of thanks for your whole effort on this site. My mum enjoys participating in internet research and it is obvious why. Most of us hear all of the dynamic tactic you make advantageous items on your blog and even recommend contribution from some other people on the topic then our favorite girl is really starting to learn a great deal. Take advantage of the remaining portion of the year. You're carrying out a superb job.

My husband and i have been absolutely joyous that Jordan managed to finish off his analysis using the precious recommendations he was given from your blog. It is now and again perplexing to just always be releasing solutions some people may have been selling. We really remember we have the website owner to appreciate for that. Those explanations you've made, the simple website navigation, the friendships you can help to promote - it is all astounding, and it's assisting our son and our family reason why that theme is awesome, which is certainly incredibly vital. Thank you for all the pieces!

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 wanted to construct a quick comment so as to say thanks to you for the remarkable secrets you are showing on this site. My extended internet search has now been rewarded with pleasant facts and techniques to go over with my pals. I would say that we visitors actually are really endowed to exist in a perfect website with very many wonderful individuals with valuable hints. I feel truly blessed to have encountered your entire webpage and look forward to plenty of more brilliant times reading here. Thanks once more for a lot of things.

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!

Thanks for all of the hard work on this web site. Kim take interest in carrying out investigations and it's simple to grasp why. Most of us know all concerning the lively mode you provide efficient information via this web blog and strongly encourage contribution from other people on this situation then our favorite child is without question starting to learn so much. Have fun with the remaining portion of the new year. You're conducting a powerful job.

I precisely desired to thank you very much yet again. I do not know the things that I would've worked on in the absence of the actual creative concepts shown by you about that field. It was before the distressing scenario for me, nevertheless considering a specialized avenue you resolved it forced me to cry over delight. I am happier for your service and believe you are aware of a powerful job your are providing educating the mediocre ones all through your websites. I'm certain you have never got to know all of us.

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.

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.