IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

by Dec 13, 2022MQTT, nodemcu projects, Projects

Gardening is always a very calming pastime. However, our gardens’ plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article, we’ll use the ESP8266, MQTT, and Adafruit IO to build an IoT-based smart gardening system.

A technology for monitoring the plant environment and soil moisture levels, also to controlling the water pump, is used in this smart garden project. I used two plants in this example, and two analog sensor readings were done. LED Stripes are installed on the background to notify the moisture level for the overall plants. This technology may also be built up and expanded to automate the gardening operation fully.

Hardware Requirements

  1. ESP8266 ( I used ESP8266 Adafruit Huzzah)
  2. Soil Moisture Sensor
  3. ADC Module – ( I have used MCP3008)
  4. Relay Module
  5. 12V DC Adapter
  6. 12V Low Voltage Pump
  7. Breadboard and Jumper Wires
  8. RGB LED Stripes
  9. 2 small Indoor plants (for installation)

Software Requirements

  • Arduino IDE with required libraries (see below)
  • Adafruit IO

Pre-requisites

For the connections and wiring of MCP3008 and the soil moisture sensor with ESP8266, follow the tutorial below.

Click here for the tutorial.

Recap:

We will choose Plant A and Plant B with different Moisture content. Gently place the module inside the soil. The module sensitivity can be adjusted with an onboard potentiometer. Moving the potentiometer shaft in the clockwise direction increases sensitivity. Moving the shaft of the potentiometer in the counterclockwise direction decreases the sensitivity of the module.

The Hygrometer module consists of two boards, the sensor board, and the control board. The sensor board has two pins, and the control board has six pins.

We will use D5, D5, D6 and D7 digital pins from the ESP8266, connect the digital pins to the MCP3008 as below:

  • D5 –> CLK
  • D6 –> D_OUT
  • D7 –> D_IN
  • D8 –> CS / CHIP SELECT

Wiring

We will use the same circuit from the previous tutorial; additionally, we will use a Relay module, a 12V DC adapter, and a 12 V DC water pump to water the plants.

Besides that, we will install RGB LED stripes to indicate the moisture level of the plants.

Wiring – Smart Gardening system

Follow the above circuit to connect your components to the ESP module.

The relay module is connected via Normally Open Mode (NO).

Setting up the Adafruit IO

  • First of all, create an account on the adafruit.io
  • Then, create a new dashboard with a unique name. Then, start creating blocks inside the layout.
  • For every block you create, there is unique information you provide which is called a feed.
  • Your feed name is important to integrate with your code.
  • Your username and AIO Key will also be generated for every individual account in Adafruit.io, which is also essential to your code
Feeds in adafruit.io

For more information on adafruit.io, follow this tutorial.

Code

Copy the following code into your Arduino IDE, set up your ESP module, and provide the correct COM port.

#include <Adafruit_NeoPixel.h>
#define PIN  2
#define NUMPIXELS      150
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

const int relay = 5;

#include <MCP3008.h>


// define pin connections
#define CS_PIN 15
#define CLOCK_PIN 14
#define MOSI_PIN 13
#define MISO_PIN 12

// put pins inside MCP3008 constructor
MCP3008 adc(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN);

int delayval = 50;
#define BRIGHTNESS 100
#include <ESP8266WiFi.h>

#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
 
#define WLAN_SSID       "your ssid"
#define WLAN_PASS       "your password"
#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                  
#define AIO_USERNAME    "your username"
#define AIO_KEY         "your aio key"
 

int sensor =A0;

int led= LOW;
 
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
 
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
 
/****************************** Feeds ***************************************/
 
// i am going to publish my data alone. no need of subscription, so feed is enough
 
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish moisture_level = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/moisture_level");

Adafruit_MQTT_Publish moisture_level_B = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/moisture_level_B");

Adafruit_MQTT_Subscribe LED = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/ledcolorpicker");

Adafruit_MQTT_Subscribe relay_pump = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay_pump");


 
/*************************** Sketch Code ************************************/
void setup() 
{
  Serial.begin(115200);
   
   pixels.begin();
   pixels.setBrightness(BRIGHTNESS);
   pinMode(relay, OUTPUT);
   digitalWrite(relay, LOW);
 
  // Connect to WiFi access point.
  Serial.print("\n\n\nConnecting to ");
  Serial.println(WLAN_SSID);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
  
   
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(">>");
    delay(5000);
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());
 mqtt.subscribe(&LED);
 mqtt.subscribe(&relay_pump);
}
 
void loop()
{
   MQTT_connect();

  int plant_a = adc.readADC(0); // read Chanel 0 from MCP3008 ADC
  Serial.print("Plant A: ");
  Serial.println(plant_a);
  delay(1000);
  Serial.print("Plant B: ");
  int plant_b = adc.readADC(1); // read Chanel 0 from MCP3008 ADC
  Serial.println(plant_b);
  
   
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.

Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    
    
    if (subscription == &LED) {
      Serial.print(F("Got: "));
      Serial.println((char *)LED.lastread);
      String hexstring = (char *)LED.lastread;


    // String hexstring = "B787B7";
    long number = (long) strtol( &hexstring[1], NULL, 16);
    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;

    Serial.print("red is ");
    Serial.println(r);
    Serial.print("green is ");
    Serial.println(g);
    Serial.print("blue is ");
    Serial.println(b);     
    for(int i=0;i<NUMPIXELS;i++){
    pixels.setPixelColor(i, pixels.Color(r,g,b)); // Moderately bright green color.
    pixels.show(); // This sends the updated pixel color to the hardware.
    delay(delayval); // Delay for a period of time (in milliseconds).
        }  
    }

   if (subscription == &relay_pump) {
      Serial.print(F("Got: "));
      Serial.println((char *)relay_pump.lastread);
      //String hexstring = (char *)LED.lastread;
      String relaypump = (char *)relay_pump.lastread;
        if (relaypump == "ON")
        {
            digitalWrite(relay, HIGH);                                                                                                                                                                                             
            Serial.println("Pump ON");
        }
        else {
            digitalWrite(relay, LOW);                                                                                                                                                                                             
            Serial.println("Pump OFF");
        }
  }
  
  }

if ((plant_a > 700) || (plant_b > 700))

{
    for(int i=0;i<NUMPIXELS;i++)
    
    {
    pixels.setPixelColor(i, pixels.Color(255,0,0)); // Moderately bright green color.
    pixels.show(); // This sends the updated pixel color to the hardware.
    delay(delayval); // Delay for a period of time (in milliseconds).
    String low_moisture = "ff7f00";  
    
}
}

else
{
 for(int i=0;i<NUMPIXELS;i++){
    pixels.setPixelColor(i, pixels.Color(0,255,0)); // Moderately bright green color.
    pixels.show(); // This sends the updated pixel color to the hardware.
    delay(delayval); // Delay for a period of time (in milliseconds).
    String high_moisture = "00ff00";
}
}

  // Now we can publish stuff to the feeds

  
  Serial.print(F("\nSending analog val "));
  Serial.print(plant_a);
  
  if (! moisture_level.publish(plant_a++)) {
    Serial.println(F("\nFailed"));
  } else {
    Serial.println(F("\nOK!"));
  }
  
  if (! moisture_level.publish(plant_a++)) {
    Serial.println(F("\nFailed"));
  } else {
    Serial.println(F("\nOK!"));
    delay (500);
  }

  Serial.print(F("\nSending analog val "));
  Serial.print(plant_b);
  
  if (! moisture_level_B.publish(plant_b++)) {
    Serial.println(F("\nFailed"));
  } else {
    Serial.println(F("\nOK!"));
  }
  
  if (! moisture_level_B.publish(plant_b++)) {
    Serial.println(F("\nFailed"));
  } else {
    Serial.println(F("\nOK!"));
    delay (500);
  }
}
 
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.

void MQTT_connect()
 
{
  int8_t ret;
 
  // Stop if already connected.
  if (mqtt.connected())
  {
    return;
  }
 
  Serial.print("Connecting to MQTT... ");
 
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 3 seconds...");
       mqtt.disconnect();
       delay(3000);  // wait 3 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}

Code Explanation

  1. Include the required libraries such as NeoPixels, MCP3008, ESPWiFi, and MQTT clients.

2. Create the Feeds in the adafruit io, and then add them in the code with variables.

Adafruit_MQTT_Publish moisture_level = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME “/feeds/moisture_level”);

Adafruit_MQTT_Publish moisture_level_B = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME “/feeds/moisture_level_B”);

Adafruit_MQTT_Subscribe LED = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME “/feeds/ledcolorpicker”);

Adafruit_MQTT_Subscribe relay_pump = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME “/feeds/relay_pump”);

3. Write a function to connect to the MQTT. This function waits every 3 seconds and returns 0 when connected.

4. In the void loop(), start with reading the sensor data from the soil moisture sensor (Analog values).

5. Next, publish and subscribe these values to the feeds.

6. In this tutorial, I have created various gauges and graphs under the same name feed to gather the same information.

You can integrate a single feed name into different blocks!

Installation

Place the pump into the water and the dripping parts inside the pot. Also, install the soil moisture sensor into the mud of the pots to sense the moisture level. The pump is manually operated using a toggle. When both of the plants have enough moisture level, then the LED strips are green; also, when one of the plants doesn’t have moisture, the LED strips turn red.

The code above also offers a special widget for picking a color of your own using a color picker widget.

Place the pump inside the water.

Dashboard

1. When both plants have enough moisture, the LED strips stay green
2. When one of the plants doesn’t have enough moisture, the LED strips turn red

Main Dashboard

Final output

You can also install this system in your home or office with some indoor plants and monitor them on a regular basis.

Happy learning!

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

How to use MQTTBox to debug MQTT messages?

How to use MQTTBox to debug MQTT messages?

MQTTBox is a versatile MQTT (Message Queuing Telemetry Transport) client tool that facilitates testing and debugging of MQTT-based applications. MQTT is a lightweight messaging protocol commonly used in IoT (Internet of Things) and other scenarios where low-bandwidth,...

How to enable Mosquitto MQTT over WebSocket on Windows

How to enable Mosquitto MQTT over WebSocket on Windows

WebSocket is one of the communication protocols which provides full duplex communication over a single TCP/IP connection. It uses HTTP as a intial connection establishment. The WebSocket enables the communication from the web browser (client) to the server, in which...

MQTT Mosquitto Broker on Windows via Windows PowerShell

MQTT Mosquitto Broker on Windows via Windows PowerShell

Eclipse Mosquitto is an open-source message broker (EPL/EDL licensed) that supports MQTT versions 5.0, 3.1.1, and 3.1. The MQTT protocol uses a publish/subscribe method to deliver a lightweight messaging method. This makes it outstanding for Internet of Things (IoT)...

How to Install the Mosquitto MQTT Broker on Linux (Ubuntu)?

How to Install the Mosquitto MQTT Broker on Linux (Ubuntu)?

With IoT becoming a leading name in the market, businesses are keen to import it in their strategy. Due to the increasing demand, many people seek to learn the use of Mosquitto MQTT broker Linux to pump up their IoT productivity. Eclipse Mosquitto is an open-source...

How to Simulate IoT projects using Cisco Packet Tracer

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

How to build an MQTT Server using Raspberry Pi

installing-and-testing-MQTT-on-Raspberry_Pi What is MQTT ? MQTT stands for Message Queuing Telemetry Transport and is a network messaging protocol commonly used for messaging between IoT devices. MQTT is a publish/subscribe protocol that allows edge-of-network devices...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....