You are on page 1of 34

IOT based Smart Irrigation System

LIST OF CONTENTS
ABSTRACT ………………………………………………………………. 6

Index Terms ……………………………………………………………… 7

Introduction ……………………………………………………………… 8

Figure 1 ……………………………………………………………… 11

Figure 2 ……………………………………………………………… 12

Major Applications ……………………………………………………………… 14

Smart Agriculture Diagram ……………………………………………………… 17

Circuit Diagram ……………………………………………………………… 18

Components ……………………………………………………………… 19

Code ……………………………………………………………… 29

References ……………………………………………………………… 35

Page | 1
ABSTRACT
Despite the perception people may have regarding the agricultural process, the reality is that
today’s agriculture industry is data-cantered, precise, and smarter than ever. The rapid
emergence of the Internet-of-Things (IoT) based technologies redesigned almost every industry
including ‘‘smart agriculture’’ which moved the industry from statistical to quantitative
approaches. Such revolutionary changes are shaking the existing agriculture methods and
creating new opportunities along a range of challenges. This article highlights the potential of
wireless sensors and IoT in agriculture, as well as the challenges expected to be faced when
integrating this technology with the traditional farming practices. IoT devices and
communication techniques associated with wireless sensors encountered in agriculture
applications are analysed in detail. What sensors are available for specific agriculture
application, like soil preparation, crop status, irrigation, insect and pest detection are listed.
How this technology helping the growers throughout the crop stages, from sowing until
harvesting, packing and transportation is explained. Furthermore, the use of unmanned aerial
vehicles for crop surveillance and other favourable applications such as optimizing crop yield
is considered in this article. State-of-the-art IoT-based architectures and platforms used in
agriculture are also highlighted wherever suitable. Finally, based on this thorough review, we
identify current and future trends of IoT in agriculture and highlight potential research
challenges.

Page | 2
INDEX TERMS
Food quality and quantity, Internet-of-Things (IoTs), smart agriculture, advanced agriculture
practices, urban farming, agriculture robots, automation, future food expectation.

Page | 3
INTRODUCTION
Most of the farmers use large portions of farming land and it becomes very difficult to reach
and track each corner of large lands. Sometime there is a possibility of uneven water sprinkles.
This result in the bad quality crops which further leads to financial losses. In this scenario the
Smart Irrigation System using Latest IoT technology is helpful and leads to ease of farming.

The Smart irrigation System has wide scope to automate the complete irrigation system. Here
we are building a IoT based Irrigation System using ESP8266 NodeMCU Module and DHT11
Sensor. It will not only automatically irrigate the water based on the moisture level in the soil
but also send the Data to ThingSpeak Server to keep track of the land condition. The System
will consist a water pump which will be used to sprinkle water on the land depending upon the
land environmental condition such as Moisture, Temperature and Humidity.

We previously build similar Automatic Plant Irrigation System which sends alerts on mobile
but not on IoT cloud. Apart from this, Rain alarm and soil moisture detector circuit can also be
helpful in building Smart Irrigation system.

Before starting, it is important to note that the different crops require different Soil Moisture,
Temperature and Humidity Condition. So in this tutorial we are using such a crop which will
require a soil moisture of about 50-55%. So when the soil loses its moisture to less than 50%
then Motor pump will turn on automatically to sprinkle the water and it will continue to sprinkle
the water until the moisture goes up to 55% and after that the pump will be turned off. The
sensor data will be sent to Thing Speak Server in defined interval of time so that it can be
monitored from anywhere in the world.

To improve the agricultural yield with fewer resources and labor efforts, substantial
innovations have been made throughout human history. Nevertheless, the high population rate
never let the demand and supply match during all these times. According to the forecasted
figures, in 2050, the world population is expected to touch 9.8 billion, an increase of
approximately 25% from the current figure. Almost the entire mentioned rise of population is
forecasted to occur among the developing countries. On the other side, the trend of urbanization

Page | 4
is forecasted to continue at an accelerated pace, with about 70% of the world’s population
predicted to be urban until 2050 (currently 49%). Furthermore, income levels will be multiples
of what they are now, which will drive the food demand further, especially in developing
countries. As a result, these nations will be more careful about their diet and food quality;
hence, consumer preferences can move from wheat and grains to legumes and, later, to meat.
In order to feed this larger, more urban, and richer population, food production should double
by 2050. Particularly, the current figure of 2.1 billion tons of annual cereal production should
touch approximately 3 billion tons, and the annual meat production should increase by more
than 200 million tons to fulfill the demand of 470 million tons. Not only for food, but crop
production is becoming equally critical for industry; indeed crops like cotton, rubber, and gum
are playing important roles in the economies of many nations. Furthermore, the food-crops-
based bioenergy market started to increase recently. Even before a decade, only the production
of ethanol utilized 110 million tons of coarse grains (approximately 10% of the world
production). Due to the rising utilization of food crops for bio-fuel production, bio-energy, and
other industrial usages, food security is at stake. These demands are resulting in a further
increase of the pressure on already scarce agricultural resources. Unfortunately, only a limited
portion of the earth’s surface is suitable for agriculture uses due to various limitations, like
temperature, climate, topography, and soil quality, and even most of the suitable areas are not
homogenous. When zooming the versatilities of landscapes and plant types, many new
differences start to emerge that can be difficult to quantify. Moreover, the available agricultural
land is further shaped by political and economic factors, like land and climate patterns and
population density, while rapid urbanization is constantly posing threats to the availability of
arable land. Over the past decades, the total agriculture land utilized for food production has
experienced a decline. In 1991, the total arable area for food production was 19.5 million square
miles (39.47% of the world’s land area), which was reduced to approximately 18.6 million
square miles (37.73% of the world’s land area) in 2013 [10]. As such, the gap between demand
and supply of food is becoming more significant and alarming with the passage of time. Further
examination showed that every crop field has different characteristics that can be measured
separately in terms of both quality and quantity. Critical characteristics, like soil type, nutrient
presence, flow of irrigation, pest resistance, etc., define its suitability and capability for a
specific crop. In most of situations, the differentiations of characteristics can exist within a
single crop field, even if the same crop is being cultivated in entire farm; hence, site-specific
analyses are required for optimal yield production. Further, adding the dimension of time,
specific crops in the same field rotate season-to-season and biologically reach different stages
Page | 5
of their cycle within a year in areas where locational and temporal differences result in specific
growth requirements to optimize the crop production. To respond to these demands with a
range of issues, farmers need new technology-based methods to produce more from less land
and with fewer hands. Considering the standard farming procedures, farmers need to visit the
agriculture sites frequently throughout the crop life to have a better idea about the crop
conditions. For this, the need of smart agriculture arises, as 70% of farming time is spent
monitoring and understanding the crop states instead of doing actual field work [11].
Considering the vastness of the agriculture industry, it incredibly demands for technological
and precise solutions with the aim of sustainability while leaving minimum environmental
impact. Recent sensing and communication technologies provide a true remote ‘‘eye in the
field’’ ability in which farmers can observe happenings in the field without being in the field.
Wireless sensors are facilitating the monitoring of crops constantly with higher accuracy and
are able to, most importantly, detect early stages of unwanted state. This is the reason why
modern agriculture involves the usage of smart tools and kits, from sowing to crop harvesting
and even during storage and transportation. Timely reporting using a range of sensors makes
the entire operation not only smart but also cost effective due to its precise monitoring
capabilities. Variety of autonomous tractors, harvesters, robotic weeders, drones, and satellites
currently complement agriculture equipment. Sensors can be installed and start collecting data
in a short time, which is then available online for further analyses nearly immediately. Sensor
technology offers crop and site-specific agriculture, as it supports precise data collection of
every site. Recently, the Internet-of-Things (IoT) is beginning to impact a wide array of sectors
and industries, ranging from manufacturing, health, communications, and energy to the
agriculture industry, in order to reduce inefficiencies and improve the performance across all
markets [12]–[16]. If looking closely, one feels that the current applications are only scratching
the surface and that the real impact of IoT and its uses are not yet witnessed. Still, considering
this progress, especially in the near past, we can predict that IoT technologies are going to play
a key role in various applications of the agriculture sector. This is because of the capabilities
offered by IoT, including the basic communication infrastructure (used to connect the smart
objects—from sensors, vehicles, to user mobile devices—using the Internet) and range of
services, such as local or remote data acquisition, cloudbased intelligent information analysis
and decision making, user interfacing, and agriculture operation automation. Such capabilities
can revolutionize the agriculture industry which probably one of most inefficient sectors of our
economic value chain today. To summarize this discussion, figure 1 provides the main drivers
of technology, while figure 2 highlights
Page | 6
figure 2 highlights

Page | 7
FIGURE 2. Major hurdle's in technology implementation for smart
agriculture.
the major hurdles of technology implementation in smart agriculture. Researchers and
engineers around the globe are proposing different methods and architectures and based on that
suggesting a variety of equipment to monitor and fetch the information regarding crop status
during different stages, considering numerous crop and _eld types. Focusing on the market
demand, many leading manufactures are providing a range of sensors, unmanned aerial
vehicles (UAVs), robots, communication devices, and other heavy machinery to deliver the
sensed data. In addition, various commissions, food and agriculture organizations, and
government bodies are developing polices and guidelines to observe and regulate the use of

Page | 8
these technologies in order to maintain food and environment safety. There are reasonable
efforts that highlight the role of the IoT in the agriculture industry, but most of the published
work focuses only on applications. Most of the existing articles either provide no insight or
show limited focus on the various IoT-based architectures, prototypes, advanced methods, the
use of IoT for food quality, and other future issues considering the latest facts and _gures. This
manuscript examines the trends in IoT-based agriculture research and reveals numerous key
issues that must be addressed in order to transform the agriculture industry by
utilizing the recent IoT developments. The major contribution of this article is to provide real
insight regarding: Expectations of the world from the agriculture industry Very recent
developments in IoT, both scholarly and in industry are highlighted and howthese
developments are helping to provide solutions to the agriculture industry. Limitations, the
agriculture industry is facing. Role of IoT to cope these limitations and other issues like
resources shortage and their precise use, food

spoilage, climate changes, environmental pollution, and urbanization. Strategies and policies
that need to be considered when implementing IoT-based technologies Critical issues that are
left to solve and possible solutions that are further required, while suggestions are provided
considering these challenges. This article is a compendium of knowledge that can help the
researchers and agriculture engineers implementing the IoT-based technologies to achieve the
desired smart agriculture. The rest of this document is organized as follows. Section II provides
a deep overview of major applications of IoT in agriculture and what we can achieve by
utilizing these technologies. Section III gives insight regarding the role of IoT in advanced
agriculture practices, like vertical farming (VF), hydroponics, and phenotyping, to manage the
issues of increased urban population. Section IV highlights various technologies and
equipment, like sensors, robots, tractors, and communication devices, being used to implement
IoT in this industry. Accepting the worth of UAVs in precision agriculture, Section V caters
application achievements that are not possible even using other latest technologies. Food safety
and transportation are other critical areas requiring focus to overcome the hunger issues which
did not get the attention of researchers as it deserves. Section VI supplies the role of the IoT to
ensure food quality for longer periods and to deliver to remote areas. Section VII identi_es
current and future trends of this technology in the crop industry by highlighting potential
research challenges. Finally, Section VIII concludes this article.

Page | 9
MAJOR APPLICATIONS
By implementing the latest sensing and IoT technologies in agriculture practices, every aspect
of traditional farming methods can be fundamentally changed. Currently, seamless integration
of wireless sensors and the IoT in smart agriculture can raise agriculture to levels which were
previously unimaginable. By following the practices of smart agriculture, IoT can help to
improve the solutions of many traditional farming issues, like drought response, yield
optimization, land suitability, irrigation, and pest control. Figure 3 lists a hierarchy of major
applications, services and wireless sensors being used for smart agriculture applications. While,
major instances in which the advanced technologies are helping at various stages to enhance
overall ef_ciency are discussed below.

A. SOIL SAMPLING AND MAPPING


Soil is the ``stomach'' of plants, and its sampling is the rst step of examination to obtain _eld-
speci_c information, which is then further used to make various critical decisions at different
stages. The main objective of soil analysis is to determine the nutrient status of a _eld so that
measures can be taken accordingly when nutrient de_ciencies are found. Comprehensive soil
tests are recommended on an annual basis, ideally in Spring; however, based on soil conditions

Page | 10
and

Page | 11
FIGURE 3. General hierarchy of possible applications, services and sensors for smart
agriculture. weather consents, it may be done in in Fall or Winter. The factors that are critical
to analyze the soil nutrient levels include soil type, cropping history, fertilizer application,
irrigation level, topography, etc. These factors give insight regarding the chemical, physical,
and biological statuses of a soil to identify the limiting factors such that the crops can be dealt
accordingly. Soil mapping opens the door to sowing different crop varieties in a specific field
to better match soil properties accordingly, like seed suitability, time to sow, and even the
planting depth, as some are deep-rooted and others less. Furthermore, growing multiple crops
together could also lead to smarter use of agriculture, simply making the best use of resources.
Currently, manufacturers are providing a wide range of toolkits and sensors that can assist
farmers to track the soil quality and, based on this data, recommend remedies to avoid its
degradation. These systems allow for the monitoring of soil properties, such as texture, water-
holding capacity, and absorption rate, which ultimately help to minimize erosion, densi_cation,
salinization, acidi_cation, and pollution (by avoiding excessive use of fertilizer). Lab-in-a-Box,
a soil testing tool kit developed by AgroCares, is considered a complete laboratory in itself
based on its offered services. By using this, any farmer, without having any lab experience, can
analyze up to 100 samples per day (overall, more than 22,000 nutrient samples a year) without
visiting any lab. Drought is a major concern which limits the productivity of crop yield. Most
of the regions around the globe face this issue with various intensities. To deal with this issue,
especially in very rural areas, remote sensing is being used to obtain frequent soil moisture data
which helps to analyze the agricultural drought in far regions. For this purpose, the Soil
Moisture and Ocean Salinity (SMOS) satellite was launched in 2009 which provides global
soil moisture maps every, one to two days. Authors in used SMOS L2 to calculate the Soil
Water De_cit Index (SWDI) in Spain in 2014. In this effort, they followed different approaches
to obtain the soil water parameters in order to compare with the SWDI acquired from in situ
data. In [26], authors used the moderate resolution imaging spectroradiometer (MODIS) sensor
to map various soil functional properties to estimate the land degradation risk for sub-Saharan
Africa. The soil maps and _eld survey data, which covered all major climate zones on the
continent, were used to develop the prediction models. Sensors and vision based technologies
are helpful to decide the distance and depth for sowing the seed ef_ciently. Like in, sensor and
vision based autonomous robot called Agribot is developed for sowing seeds. The robot can
perform on any agricultural lands on which the self-awareness of the robot's placement is

Page | 12
ascertained through the global and local maps generated from Global Positioning System
(GPS) while the on-board vision system is paired with a personal computer. Advancing further,
various non-contact sensing methods are proposed to determine the seed _ow rate as in where
the sensors are equipped with LEDs; consist of infrared, visible light and laser-LED as well as
an element as a radiation receiver. The output voltage varies based on the movement of the
seeds through the sensor and band of light rays, and falling of shades on the elements of
receiver. The signal information, linked to the passing seeds, is used to measure the seed _ow
rate. B. IRRIGATION About 97% of Earth's water is salt-water held by oceans and seas, and
only the remaining 3% is fresh water_more than two-third of which is frozen in the forms of
glaciers and polar ice caps. Only 0.5% of the unfrozen fresh water is above the ground or in
the air, as the rest lies underground. In short, humanity relies on this 0.5% to ful_ll all its
requirements and to maintain the ecosystem, as enough fresh water must be kept in rivers,
lakes, and other similar reservoirs to sustain it. It is worth mentioning that solely the agriculture
industry uses approximately 70% of this accessible fresh water. In many countries, situation
rises.

Page | 13
Working Principle

Once the Motor pump has started- following automated condition will work

1. User can switch OFF the motor if he desires by a click on the web page.

2. The motor pump will automatically get switched OFF once the soil moisture sensor has
reached the required threshold value.

3. If weather condition is such that it started raining, then the micro-controller will shut down
the motor pump till raining. And after that it checks whether the soil moisture sensor has
reached the threshold value or not. If it crosses the threshold value then motor pump will
remain shut down otherwise it will start again automatically. This helps in saving water
resource and electricity.

4.Also in case, when power supply gets cut-off and motor gets switched off. It will restart
again automatically when there will be availability power supply, user will have not to worry
about restarting the motor pump manually.

5. Also data of various sensor like- moisture sensor , temperature sensor, humidity sensor will
be displayed on BOLT cloud in graphical form but due to limitation of BOLT i have only
displayed one sensor data(moisture sensor data).

Page | 14
Block Diagram

Page | 15
Circuit Diagram

Page | 16
Components

Moisture Sensor

This Moisture Sensor can be used to detect the moisture of soil or judge if there is water around
the sensor, let the plants in your garden reach out for human help. They can be very to use, just
insert it into the soil and then read it. If you are a gardener, you can use this sensor to know
when your plants need to be watered.

Features
• Easy to Use
• 2.0cmX6.0cm grove module
• Application Ideas
• Botanical gardening
• Water sensor
Page | 17
Arduino Uno:
The Arduino project started at the Interaction Design Institute Ivrea (IDII) in Ivrea, Italy. At that time,
the students used a BASIC Stampmicrocontroller, a considerable expense for many students. In 2003
Hernando Barragán created the development platform Wiring as a Master's thesis project at IDII, under
the supervision of Massimo Banzi and Casey Reas, who are known for work on the Processing language.
The project goal was to create simple, low-cost tools for creating digital projects by non-engineers. The
Wiring platform consisted of a printed circuit board (PCB) with an ATmega168 microcontroller, an IDE
based on Processing and library functions to easily program the microcontroller. In 2003, Massimo
Banzi, with David Mellis, another IDII student, and David Cuartielles, added support for the cheaper
ATmega8 microcontroller to Wiring. But instead of continuing the work on Wiring, they forked the
project and renamed it Arduino. Early arduino boards used the FTDI USB-to-serial driver chip and
an ATmega168. The Uno differed from all

3.1 Arduino Uno:


Page | 18
The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial driver
chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed as a
USB-to-serial converter.
Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to ground, making it
easier to put into DFU mode.
Revision 3 of the board has the following new features:

▪ 1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins
placed near to the RESET pin, the IOREF that allow the shields to adapt to the voltage
provided from the board. In future, shields will be compatible both with the board that use
the AVR, which operate with 5V and with the Arduino Due that operate with 3.3V. The
second one is a not connected pin, that is reserved for future purposes.
▪ Stronger RESET circuit.
▪ Atmega 16U2 replace the 8U2.

"Uno" means one in Italian and is named to mark the upcoming release of Arduino 1.0. The
Uno and version 1.0 will be the reference versions of Arduino, moving forward. The Uno is
the latest in a series of USB Arduino boards, and the reference model for the Arduino platform;
for a comparison with previous versions, see the index of Arduino boards.

Summary

Microcontroller ATmega328

Operating Voltage 5V

Input Voltage (recommended) 7-12V

Input Voltage (limits) 6-20V

Digital I/O Pins 14 (of which 6 provide PWM output)

Page | 19
Analog Input Pins 6

DC Current per I/O Pin 40 mA

DC Current for 3.3V Pin 50 mA

Flash Memory 32 KB (ATmega328) of which 0.5 KB used by bootloader

SRAM 2 KB (ATmega328)

EEPROM 1 KB (ATmega328)

Clock Speed 16 MHz

20x4 Character LCD Display


This is a 20 character x 4 line blue background Super Twisted Nematic (STN) LCD with built-
in HD44780 equivalent controller (also known as alphanumeric displays). Interfacing is
simplified with 4 bit or 8 bit communications and programming code is widely available for
many different controllers and systems.

Features:
Page | 20
• High contrast STN 20x4 character LCD
• White text on blue background
• Single +5.0V supply operation
• LED backlight
• 5x8 dot characters
• HD44780 equivalent controller
• 4 or 8 bit interface

2X16 LCD

Wiring:

SO If you are going to use arduino board then please connect devices as following:

FOR LCD:

* LCD RS pin to digital pin 12

* LCD Enable pin to digital pin 11

* LCD D4 pin to digital pin 5

* LCD D5 pin to digital pin 4

* LCD D6 pin to digital pin 3

* LCD D7 pin to digital pin 2

* LCD R/W pin to ground

* 10Komhs Variable resistor with two ends to +5v and ground and the middle wipper ti LCD pin VO.

If you also have back light in your LCD and want to enable it:

* LCD A to +5v , LCD K to Ground.

Page | 21
And LCD VSS to Ground , LCD VDD to +5v.

FOR HC-SR04:

* VCC to +5v , Gnd to Groung

* “Trig” Pin to Digital pin 7

* “Echo” Pin to Digital pin 8

And if You are not using Arduino Board instead using a Arduino IC after programming it then use the
following schematic:

Page | 22
Arduino Bluetooth Module (HC-05)

This serial Bluetooth module can work as either master or slave. This module also includes the
baseboard, not only the core board, most functions are pre-set, so only the serial port
communication is available but it’s easier to use. It can be used also with Arduino or
Microcontroller.

Product Features:

▪ Compatible with Arduino, Stamp, FPGA and many more!


▪ Plug and Play operation at 9600 baud
▪ Easily integrated into existing (9600 baud) projects without any need to modify code!
▪ Includes: BT2S Slave, Easy-Pin Cable and Pin-out/Instruction Pamphlet
▪ *Requires Bluetooth enabled master device.
▪ Bluetooth module interface including VCC, GND, TXD, RXD, KEY pin
and LED Status pin-out (STATE).
▪ In open space effective distance is 10 meter, more than 10 meter is
also possible by using external antenna.
▪ Backplane set anti-reverse diode with 3.3V LDO input voltage of 3.6 ~~ 6V
unpaired current is about 30mA paired approximately 10mA input voltage
to prohibit more than 7V.

Page | 23
ESP8266 ESP-01 WIFI Wireless Transceiver Send Receive LWIP
AP+STA M70

ESP8266 is a wifi SOC (system on a chip) produced by Espressif Systems. It is an highly


integrated chip designed to provide full internet connectivity in a small package. This is a
module based on ESP8266 chip.

Please see supplied pinout photo and schematics for connectivity details. There is a lot of online
resources available for this module.

DESCRIPTION
ESP8266 is a wifi SOC (system on a chip) produced by Espressif Systems. It is an highly
integrated chip designed to provide full internet connectivity in a small package. This is a
module based on ESP8266 chip.

Please see supplied pinout photo and schematics for connectivity details. There is a lot of
online resources available for this module.

Technical Specs:

▪ 802.11 b / g / n
▪ Wi-Fi Direct (P2P), soft-AP
▪ Built-in TCP / IP protocol stack
▪ Built-in TR switch, balun, LNA, power amplifier and matching network
Page | 24
▪ Built-in PLL, voltage regulator and power management components
▪ 802.11b mode + 19.5dBm output power
▪ Built-in temperature sensor
▪ Support antenna diversity
▪ off leakage current is less than 10uA
▪ Built-in low-power 32-bit CPU: can double as an application processor
▪ SDIO 2.0, SPI, UART
▪ STBC, 1×1 MIMO, 2×1 MIMO
▪ A-MPDU, A-MSDU aggregation and the 0.4 Within wake
▪ 2ms, connect and transfer data packets
▪ standby power consumption of less than 1.0mW (DTIM3)

DHT22 Digital Temperature Humidity Sensor

The DHT22 is a basic, low-cost digital temperature and humidity sensor. It uses a capacitive
humidity sensor and a thermistor to measure the surrounding air, and spits out a digital signal
on the data pin (no analog input pins needed). It's fairly simple to use, but requires careful
timing to grab data. The only real downside of this sensor is you can only get new data from

Page | 25
it once every 2 seconds, so when using our library, sensor readings can be up to 2 seconds
old.

Power supply: 3- 5V.

▪ Current: 2.5mA max use of current during conversion (while requesting data).
▪ Humidity: 0 - 100%, ± 2%.
▪ Temperature: -40°C + 125°C, ± 0.5%.
▪ The sampling rate no more than 0.5 Hz (once every 2 seconds).

Programming ESP8266 NodeMCU for Automatic Irrigation System

For programming the ESP8266 NodeMCU module, only the DHT11 sensor library is used
as external library. The moisture sensor gives analog output which can be read through the
ESP8266 NodeMCU analog pin A0. Since the NodeMCU cannot give output voltage
greater than 3.3V from its GPIO so we are using a relay module to drive the 5V motor
pump. Also the Moisture sensor and DHT11 sensor is powered from external 5V power
supply.

Complete code is given at the end, here we are explaining the program to understand the
working flow of the project.

Page | 26
Code:

#include <DHT.h>

#include <ESP8266WiFi.h>

String apiKey = "X5AQ3EGIKMBYW31H"; // Enter your Write API key here

const char* server = "api.thingspeak.com";

const char *ssid = "CircuitLoop"; // Enter your WiFi Name

const char *pass = "circuitdigest101"; // Enter your WiFi Password

#define DHTPIN D3 // GPIO Pin where the dht11 is connected

DHT dht(DHTPIN, DHT11);

WiFiClient client;

const int moisturePin = A0; // moisteure sensor pin

const int motorPin = D0;

unsigned long interval = 10000;

unsigned long previousMillis = 0;

unsigned long interval1 = 1000;

unsigned long previousMillis1 = 0;

float moisturePercentage; //moisture reading

float h; // humidity reading

float t; //temperature reading

Page | 27
void setup()

Serial.begin(115200);

delay(10);

pinMode(motorPin, OUTPUT);

digitalWrite(motorPin, LOW); // keep motor off initally

dht.begin();

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");

Page | 28
void loop()

unsigned long currentMillis = millis(); // grab current time

h = dht.readHumidity(); // read humiduty

t = dht.readTemperature(); // read temperature

if (isnan(h) || isnan(t))

Serial.println("Failed to read from DHT sensor!");

return;

moisturePercentage = ( 100.00 - ( (analogRead(moisturePin) / 1023.00) * 100.00 ) );

if ((unsigned long)(currentMillis - previousMillis1) >= interval1) {

Serial.print("Soil Moisture is = ");

Serial.print(moisturePercentage);

Serial.println("%");

previousMillis1 = millis();

Page | 29
}

if (moisturePercentage < 50) {

digitalWrite(motorPin, HIGH); // tun on motor

if (moisturePercentage > 50 && moisturePercentage < 55) {

digitalWrite(motorPin, HIGH); //turn on motor pump

if (moisturePercentage > 56) {

digitalWrite(motorPin, LOW); // turn off mottor

if ((unsigned long)(currentMillis - previousMillis) >= interval) {

sendThingspeak(); //send data to thing speak

previousMillis = millis();

client.stop();

Page | 30
void sendThingspeak() {

if (client.connect(server, 80))

String postStr = apiKey; // add api key in the postStr string

postStr += "&field1=";

postStr += String(moisturePercentage); // add mositure readin

postStr += "&field2=";

postStr += String(t); // add tempr readin

postStr += "&field3=";

postStr += String(h); // add humidity readin

postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");

client.print("Host: api.thingspeak.com\n");

client.print("Connection: close\n");

client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");

client.print("Content-Type: application/x-www-form-urlencoded\n");

client.print("Content-Length: ");

client.print(postStr.length()); //send lenght of the string

Page | 31
client.print("\n\n");

client.print(postStr); // send complete string

Serial.print("Moisture Percentage: ");

Serial.print(moisturePercentage);

Serial.print("%. Temperature: ");

Serial.print(t);

Serial.print(" C, Humidity: ");

Serial.print(h);

Serial.println("%. Sent to Thingspeak.");

Page | 32
REFERENCES

[1] Dr. Narayan G. Hegde, “Water Scarcity and Security in India”, BAIF Development
ReseachFoundation, Pune.
[2]Marvin T. Batte, “Changing computer use in agriculture: evidence from Ohio”,
Computers and Electronics in Agriculture, Elsevier science publishers, vol. 47, 1–13,
2005
[3] Csótó, Magyar, “Information flow in agriculture – through new channels for
improved effectiveness”, Journal of Agricultural Informatics 1 (2), 25–34, 2010
[4] Jin Shen, Song Jingling, Han Qiuyan and Yang Yan, “A Remote Measurement and
Control System for Greenhouse Based on GSM-SMS”, Electronic Measurement
andInstruments, 2007. ICEMI '07. 8th International Conference
[5] Indu Gautam and S.R.N Reddy, “Innovative GSM based Remote Controlled
Embedded System for Irrigation”, International Journal of Computer Applications Vol. 47 –
No.13, June 2012
[6] R.Suresh, S.Gopinath, K.Govindaraju, T.Devika, N.SuthanthiraVanitha, “GSM based
Automated IrrigationControl using Raingun Irrigation System”, InternationalJournal of
Advanced Research in Computer and Communication Engineering Vol. 3, Issue 2,
February 2014.
[7] Karan Kansara, Vishal Zaveri, Shreyans Shah, Sandip Delwadkar, and Kaushal Jani
“Sensor based Automated Irrigation System with IOT: A Technical Review”,(IJCSIT)
International Journal of Computer Science and Information Technologies, Vol. 6 (6) , 2015,
5331-5333
[8] Sumeet. S. Bedekar, Monoj. A. Mechkul, and Sonali. R. Deshpande “IoT based
Automated Irrigation System”, IJSRD - International Journal for Scientific Research&
Development| Vol. 3, Issue 04, 2015 | ISSN (online): 2321-0613
[9] K.S.S. Prasad, Nitesh Kumar, Nitish Kumar Sinha and Palash Kumar Saha “Water-
Saving Irrigation System Based on Automatic Control by Using GSM Technology”,
Middle-East Journal of Scientific Research 12 (12): 1824-1827, 2012ISSN 1990-9233 c
IDOSI Publications, 2012DOI: 10.5829/idosi.mejsr.2012.12.12.1258
[10] Remote Sensing and Control of an Irrigation System Using a Distributed Wireless
Sensor Network by Yunseop (James) Kim, Member, IEEE, Robert G. Evans, and William
M. Iversen, IEEE Transaction on Instrumentation and Measurement, VOL.57
[11] Thingspeak : https:// thingspeak.com/
[12] Alexandros Kaloxylos, Robert Eigenmann, Frederick Teye, Zoi Politopoulou, Sjaak
Wolfert, Claudia Shrank, Markus Dillinger, Ioanna Lampropoulou, Eleni Antoniou, Liisa
Pesonen, Huether Nicole, Floerchinger Thomas, Nancy Alonistioti, and George
Kormentzas, “Farm management systems and the Future Internet era”, Elsevier's Computers
and Electronics in Agriculture 89 (2012) 130–144
Page | 33
[13] Pavithra D.S, M.S.Srinath GSM based Automatic Irrigation Control System for
Efficient Use of Resources and Crop Planning by Using an Android Mobile
[14] ZHAI Shun, WANG Wei-hong, ZHANG Kan, LI Peng, IOT SMS alarm system based
on SIM900A, School of Automation Science and Electrical Engineering,Beihang
University,Beijing 100191,China
[15] Pei Suping, Wu Birui, The Soil Moisture Content Monitoring and Irrigation System
Based on IOT, Journal of Agricultural Mechanization Research, 2013-07

Page | 34

You might also like