Вы находитесь на странице: 1из 80

THAI NGUYEN UNIVERSITY OF TECHNOLOGY

Faculty of International Training


-----------------o0o---------------

BACHELOR THESIS

AUTOMATED DRIP
IRRIGATION IN SMART
AGRICULTURE
Author:
Tran Ngo Giang
Student’s ID: K145520207170

Supervisor:
Dr. Nguyen Tuan Minh

1
Thai Nguyen, August 2019

THAINGUYEN UNIVERSITY OF TECHNOLOGY


Faculty of International Training

BACHELOR THESIS

AUTOMATED DRIP
IRRIGATION IN SMART
AGRICULTURE

Author: Supervisor:
Tran Ngo Giang Dr. Nguyen Tuan Minh
Student’s ID: K145520207170

A thesis submitted in fulfillment of the requirements


for the degree of Bachelor of Engineering
in the

Division of English-taught Electrical Engineering


and Computer Science

2
Thai Nguyen August, 2019

This thesis has been approved by the


Supervisor: Dr. Nguyen Tuan Minh

Signed:

Date:

Head of the Division: Dr. Vu Quoc Dong

Signed:

Date:

Faculty Dean: Dr. Nguyen Tien Hung

Signed:

Date:

Composition of the committee (optional):

Dr. Nguyen Tien Hung Thainguyen University of Technology, Chairman


Dr. Nguyen Tuan Minh Thainguyen University of Technology
Dr. Nguyen Minh Y Thainguyen University of Technology
Dr. Myoung Jae Kwon Thainguyen University of Technology
MSc. Tran Que Son Thainguyen University of Technology
MSc. Nguyen Van Lanh Thainguyen University of Technology

Copyright © 2019 by Tran Ngo Giang. All rights reserved.


Published by the Faculty of International Training (FIT). Thai Nguyen University of Technology.
3
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, and scanning without the prior
written permission of the authorization.

Declaration of Authorship

I, Tran Ngo Giang, declare that this thesis titled, “Automated Drip irrigation in Smart
Agriculture” and the work presented in it are my own. I confirm that:

 This work was done wholly or mainly while in candidature for a research
degree at this University.
 Where any part of this thesis has previously been submitted for a degree or any
other qualification at this University or any other institution, this has been
clearly stated.
 Where I have consulted the published work of others, this is always clearly
attributed.
 Where I have quoted from the work of others, the source is always given. With
the exception of such quotations, this thesis is entirely my own work.
 I have acknowledged all main sources of help.
 Where the thesis is based on work done by myself jointly with others, I have
made clear exactly what was done by others and what I have contributed
myself.

Signed:

Date:

4
Acknowledgements

First of all, I would like to express my heartfelt gratitude for my supervisor in this
thesis work, Dr. Nguyen Tuan Minh for giving me the opportunity to explore an
interesting field of Smart Agriculture based Internet of Things. His invaluable
guidance, comments and suggestions helped me in all the time of research and writing
of this thesis. I could not have imagined having a better advisor and mentor for my
project.
I would like to thank my friends for their motivation and encouragement, pieces
of advice, and useful feedback. I would like to thank my groupmate, Mr. Truong
Hoang Linh, Ms. Nguyen Huong Quynh, and Mr. Vuong Ngoc Quang for support and
advice in this thesis. Especially, I would like to say thank to Ms. Nguyen Thi Thanh
Hoa for being good groupmate helping me get through the hardest time when I was a
new member of the group.
Finally, I would like to express my sincere gratitude to my parents for being beside,
emotional support, financial support, and encouragement. I would like to thank my
brother – Mr. Tran Van Truong, my sister-in-law – Mrs. Nguyen Thi Nhung, and my
niece – Tran Thi Hoang Anh – a little angel for their emotional support.
Thank you all very much! Five years may not long but not be considered as a short
time. Thank faculty of international training, active and professional environment for
studying. Thank you!

5
Contents

Acknowledgements........................................................................................................... v

Contents............................................................................................................................ 1

List of figures.................................................................................................................... 4

List of tables...................................................................................................................... 6

List of abbreviations........................................................................................................7

Abstract............................................................................................................................. 8

CHAPTER 1..................................................................................................................... 9

1.1. MOTIVATION................................................................................................9

1.2. RELATED WORK........................................................................................13

1.3. CONTRIBUTION.........................................................................................15

1.4. ORGANIZATION.........................................................................................16

CHAPTER 2................................................................................................................... 17

2.1. INTERNET OF THINGS (IOT)....................................................................17

2.1.1. DEFINITION AND ARCHITECTURE..............................................17

2.1.2. APPLICATION...................................................................................18

2.2. IMPACTS OF NATURAL FACTORS TO THE PLANT GROWTH..........19

2.3. AUTOMATED IRRIGATION UTILIZING WIRELESS


COMMUNICATION TECHNOLOGY..................................................................21

2.3.1. SENSORS IN AUTOMATED IRRIGATION SYSTEMS..................22

2.3.2. COMMUNICATION TECHNOLOGY IN AUTOMATED


IRRIGATION.....................................................................................................24

6
2.4. AUTOMATED DRIP IRRIGATION SYSTEM...........................................26

CHAPTER 3................................................................................................................... 30

3.1. HARDWARE................................................................................................30

3.1.1. NODEMCU ESP8266ESP-12E WIFI DEVELOPMENT BOARD....30

3.1.2. TEMPERATURE AND HUMIDITY SENSOR DHT11.....................33

3.1.3. SOIL MOISTURE SENSOR LM393..................................................37

3.1.4. MODULE 1 RELAY...........................................................................38

3.1.5. SOLENOID VALVE...........................................................................39

3.1.6. LCD16X2............................................................................................40

3.1.7. I2C MODULE.....................................................................................42

3.1.8. POWER SOURCE...............................................................................43

3.2. SOFTWARE..................................................................................................46

3.2.1. ARDUINO IDE...................................................................................46

3.2.2. THINGSPEAK WEBSERVER...........................................................47

3.3. BLOCK DIAGRAM AND FLOWCHART...................................................48

CHAPTER 4................................................................................................................... 53

4.1. REAL MODEL..............................................................................................53

4.1.1. SENSOR UNIT MODEL....................................................................54

4.1.2. BASE STATION UNIT MODEL........................................................55

4.1.3. VALVE UNIT MODEL......................................................................56

4.2. EXPERIMENTAL RESULTS AND DISCUSSION.....................................56

CHAPTER 5................................................................................................................... 60

REFERENCES............................................................................................................... 61

APPENDIX..................................................................................................................... 65

7
List of figures
Figure 1. 1. Population growth graph in the world........................................................9
Figure 1. 2. A system model on IoT based smart agriculture [11]...............................13
Figure 1. 3. A system model of IoT based crop-field monitoring and irrigation
automation [12]...........................................................................................................14
Figure 1. 4. A design for home automation system [13].............................................15
Y
Figure 2. 1. A typical soil moisture sensor..................................................................22
Figure 2. 2. pH sensor.................................................................................................23
Figure 2. 3. Humidity sensor.......................................................................................23
Figure 2. 4. LM35 sensor............................................................................................24
Figure 2. 5. A smart drip irrigation system model.......................................................27
Figure 3. 1. NodeMCU esp8266.................................................................................30
Figure 3. 2. NodeMCU pinout diagram.......................................................................31
Figure 3. 3. Sensor DHT11.........................................................................................33
Figure 3. 4. Connection between DHT11 with MCU..................................................35
Figure 3. 5. DHT11 overall communication process...................................................36
Figure 3. 6. Soil moisture sensor LM393....................................................................37
Figure 3. 7. Working principle of the relay.................................................................38
Figure 3. 8. Module 1 relay.........................................................................................39
Figure 3. 9. Solenoid valve..........................................................................................40
Figure 3. 10. Pin diagram of LCD1602.......................................................................41
Figure 3. 11. Diagram of I2C module.........................................................................43
Figure 3. 12. LM2596 DC/DC step-down voltage converters.....................................44
Figure 3. 13. UnltraFire battery...................................................................................45
Figure 3. 14. Arduino IDE Software...........................................................................47
Figure 3. 15. Thingspeak.............................................................................................47
Figure 3. 16. Diagram of the system...........................................................................49
Figure 3. 17. Flow chart of sensor unit........................................................................50
Figure 3. 18. Flow chart of base station unit...............................................................51
Figure 3. 19. Flowchart of valve unit which controls solenoid valve..........................52

8
Y
Figure 4. 1. The model is running...............................................................................53
Figure 4. 2. Sensor unit...............................................................................................54
Figure 4. 3. Base station unit.......................................................................................55
Figure 4. 4. Valve unit.................................................................................................56
Figure 4. 5. Experimental model.................................................................................57
Figure 4. 6. Temperature is shown on thingspeak.......................................................57
Figure 4. 7. Humidity on thingspeak...........................................................................58
Figure 4. 8. Soil moisture on thingspeak.....................................................................58

9
List of tables
YTable 2. 1. Suitable condition for some types of plants................................................
Table 2. 2. Comparison of communication technologies............................................24

Y
Table 3. 1. DHT11 Overview......................................................................................33
Table 3. 2. DHT11 detailed specifications..................................................................34
Table 3. 3. Technical specification of Soil sensor module..........................................37
Table 3. 4. Pins function of LCD16x2........................................................................41
Table 3. 5. Specification of I2C 16x02 serial LCD module........................................43
Table 3. 6. Technical Specification of The battery Ultrafire.......................................45

10
List of abbreviations
IoT – Internet of Things
RFID – Radio Frequency Identification
SU – Sensor Unit
BSU – Base Station Unit
VU – Valve Unit
LCD - Liquid Crystal Display
I2C – Inter-Integrated Circuit

11
Abstract

Popular growth affects to food security, thus agricultural productivity needs to increase
by applying new technology. In addition, demand for fresh water also increases with
popular growth, while irrigation in agriculture consumes huge amount of water. IoT is
applied in many aspects of our life. By using IoT in agriculture, productivity is
improved, and water waste is reduced in irrigation. In this project, a model of
automated drip irrigation is deployed by using data from soil moisture sensor. WiFi
technology is utilized to transmit data between units and send data to web server. The
design of this system includes 3 units: sensor unit (SU), base station unit (BSU), and
valve unit (VU). Soil moisture data is collected by SU and sent to BSU. By
comparison with threshold set by user, BSU sends command to VU to turn ON/OFF
solenoid valve. The sensing data is sent to webserver for user to monitor remotely and
display on LCD instead of personal computer in practical system. This irrigation
system not only provides and efficient use of fresh water resource but also reduce the
need for workmanship for conventional irrigation methods.

12
CHAPTER 1

INTRODUCTION

1.1. Motivation
The global population has grown from 1 billion in 1800 to 7.616 billion in
2018. It is expected to keep growing, and estimates have put the total population at 8.6
billion by mid-2030, 9.8 billion by mid-2050 ad 11.2 billion by 2100 [ CITATION
population \l 1033 ]. The beginning of population growth was from the Western world
in the industrial revolution of the late 18 th century. Population growth causes to social
infrastructures such as medical facilities and services, increasing government debts,
rising inflation, less employment opportunities, more number of illiterates, difficulties
in the implementation of state development programs, increasing instances of crime,
increase in industrial and community waste, air, water and land pollution. Especially
there are two main problems which I would like to discuss in this section: food
security and freshwater.

Figure 1. . Population growth graph in the world

Increased population means more mouths to feed which forces to the available
stock of food. This is the reason of the under-developed countries with rapid growing
population which is generally faced with a problem of food shortage while they always
try to raise agricultural production, and they are not able to feed their growing
13
population. Population growth also leads to increase cases of water pollution. Water is
one of the most integral and important aspects of daily life for every human being, for
example, food, clothing and almost everything else humans interact with involves
water. Therefore, water and water security is going to be a crucial focus for
governments in the next few decades.

Agriculture is the basic source of food supply of all the countries of the world –
whether underdeveloped, developing or even developed. Due to heavy pressure of
population in underdeveloped and developing countries and its rapid increase, the
demand for food is increasing at a fast rate. If agriculture fails to meet the rising
demand of food products, it is found to affect adversely the growth rate of the
economy. Raising supply of food by agriculture sector has, therefore, great importance
for economic growth of a country [ CITATION roleagri \l 1033 ].

With conventional agriculture, farmers often have to visit their agriculture fields
to check soil moisture level and the growth of crops. Based on the requirement of
water and nutrient, water is pumped by motors to irrigate respective fields and
nutrients are supplied for the for the growth. By this method, famers need to wait for
certain time to switch off motors. This irrigation method takes a lot of time and effort
particularly when a farmer needs to irrigate multiple agriculture fields distributed in
different geographical areas. In some rural regions, famers have to carry water by
human power on their shoulders for long distance to irrigate crops.

Conventional agriculture consumes a huge amount of pesticides, and the use of


pesticides for pest mitigation has become a common practice all around the world
[ CITATION Mah16 \l 1033 ]. Continuous use of pesticides has resulted in damage to
the environment, caused human ill-health, negatively impacted on agricultural
production and reduced agricultural sustainability.

The use of fertilizer is a source of contamination of surface and groundwater


[ CITATION fertilizer \l 1033 ]. Degraded soil quality, expressed as poor surface soil
aggregation, high bulk density, low porosity, and slow infiltration, limits agricultural
productivity and increases nonpoint source pollution of surface water via agricultural
runoff. By information about demand of nutrients for each type of crops, famers can

14
supply enough quantity of fertilizer for crops to have the highest productivity while
they still reduce agricultural impacts on water quality [ CITATION Eva08 \l 1033 ].

Due to environmental pollution, water sources are affected, so freshwater is


reduced while we need freshwater not only for agriculture but also for our living when
population keeps increasing. To meet demands for both food and water, engineers and
scientists issued and applied many methods to manage and keep our water resources
better. Agricultural irrigation consumes the largest amount of freshwater – around 70%
of withdrawals for irrigation. In agriculture, irrigation contributes from 30 to 40% of
the world’s food crops on 17% of all arable land [CITATION label3 \l 1033 ]. With
the advance of technology, drip irrigation is applied in agriculture to increase
efficiency of usage of water in comparison with conventional methods. With the
penetration of Internet of things (IoT), drip irrigation is smarter and minimizes the use
of water to provide for the crop [ CITATION label3 \l 1033 ], [ CITATION ref4 \l
1033 ],[ CITATION lab5 \l 1033 ].

Conventional irrigation mainly uses channel systems from rivers and lakes, and
presence of pumps helps farmers irrigate crops in the terrain regions to the crop field
and distribute water for long distance. This method is surface irrigation including two
types: level basin and furrow basin. In level basin, the top end of the field is applied
with water where it will flow over the whole field. After the water reaches the end of
field it starts off to pond. It is a basic type of irrigation system which is used in our
country at large basis. Water wastage is not good for dry area.

Furrow irrigation basin is used in the production of vegetables. It has several


advantages that whole field is not filled with water than water is applied in furrows.
This saves water at the same time and on the other hand the plant is not in direct
contact with water as same plants like production of vegetables are very sensitive to
pounded water. Furrows are sloping channels which are in its root zone and therefore
plant is not in direct contact with water. This method wastes huge amount of water and
need a large number of worker for watering. Efficient and welfare use of fertilizers is
not possible. Net yield or productivity is also not high. Problems related to soil erosion
are major problem Substantial amount of ground water goes waste. Problem of water
logging in fields.
15
Advanced irrigation methods include sprinkler irrigation system and drip
irrigation system. Sprinkler system is more useful, especially in smaller quantity of
water. This method delivers water through a pressurized pipe network to the nozzles of
sprinkler which spray the water into the air. This system is very useful on the sandy
soil, and less number of worker required water waste is less. This system has several
advantages, such as saving water due to possibility of using saline water, efficient and
welfare use of fertilizers, easy to install and flexibility in operation, suits to all types of
land terrain and also suitable to waste lands, enhancing plant growth and yield and
better quality of produce, less weed growth, saving labor works, no soil erosion which
saves land, and minimum diseases and pest control.

Drip irrigation is named as micro irrigation or trickle irrigation. This is an


efficient technique which is primarily used in hot tropical conditions. It conserves
water and fertilizer. It allows water to drip slowly to the root of plants through valves,
pipes, tubing etc. It helps deliver water directly to the base of the plant. It is the best
technology for watering fruit plants, gardens and trees. Water flow through a main
pipe and divided into sub pipes. Special prepared nozzles are attached to these sub
pipes. In this system waste of water is very less and no worker need for irrigating.
When the farmer knows the status of the farm field then start the motor and chose the
direction from nozzles. The automatically watering the plants and after some time the
farmer check the status of the field and while the whole crop are irrigating then OFF
the motor.

With smart irrigation, the total system is controlled by autonomous mean


automatically control the total irrigation system whether the farmer is not present his
farm field and send messages to the farmer about the information of farm and change
in operation of the farm field. Which require no worker for operating, and also less
waste of water with compared to conventional methods. While sprinkler systems are
around 75-85% efficient, drip systems typically are 90% or higher. Smart drip
irrigation is based on IoT. By applying IoT, crops are irrigated automatically.
Automatic drip irrigation systems water plants based on sensing data such as soil
humidity, pH value of soil, nutrient of soil, temperature and light [ CITATION ref4 \l
1033 ], [ CITATION Hus13 \l 1033 ], [ CITATION Abb14 \l 1033 ]. These parameters

16
are required in big agricultural fields where productivity of the crop matters. In small
areas like office premises, buildings, house gardens tec. Where watering plants at
regular interval matters.

1.2. RELATED WORK


Nikesh Gondchawar et.al., [ CITATION Gon16 \l 1033 ] provide a model on
IoT based smart agriculture to make agriculture smart using automation and IoT
technologies. That paper used GPS based remote controlled robot will perform the
operations like weeding, spraying, moisture sensing etc. It monitors temperature
maintenance, humidity maintenance and theft detection in the warehouse management.
All the operations are controlled by smart device and it will be performed by
interfacing sensors, Zigbee modules, camera and actuators with microcontroller and
raspberry pi.

Figure 1. . A system model on IoT based smart agriculture [ CITATION Gon16 \l


1033 ]

Rajalakshmi P.et.al., [ CITATION Raj16 \l 1033 ] proposed a model to monitor


the crop-field using soil moisture sensors, temperature and humidity sensor, light
sensor and automated the irrigation system. The data from sensors are sent to web
server using wireless transmission and JSON format is used for data encoding to
maintain server database. The moisture and temperature of the agriculture field falls
below the brink; irrigation system will be automated. The notifications are sent to
farmers mobile periodically and farmers can be able to monitor the field conditions
from anywhere. The parameters used here are soil moisture sensor, temperature and
humidity sensor DHT11, LDR used as light sensor and web server – NRF24L01 used

17
for transmitter and receiver. This system will be more useful in areas where water is in
scarcity and it is 92% more efficient than the conventional approach.

Figure 1. . A system model of IoT based crop-field monitoring and irrigation


automation [ CITATION Raj16 \l 1033 ]

Nikhil Afrawal.et.al., [ CITATION Agr15 \l 1033 ] proposed a design for home


automation system using ready-to-use, cost effective and energy efficient devices
including raspberry pi, Arduino microcontrollers, Xbee modules and relay boards. Use
of these components results in overall cost effective, scalable and robust
implementation of system. The commands from the user are processed at raspberry pi
using python programming language. Arduino microcontrollers are used to receive the
on/off commands from the raspberry pi using Zigbee protocol. Star Zigbee topology
serves as backbone for the communication between raspberry pi and end devices.
Raspberry pi acts a central coordinator and end devices act as various routers. Low-
cost and energy efficient drip irrigation system serves as a proof of concept. The
design can be used in big agriculture fields as well as in small gardens via just sending
an email to the system to water plants. The use of ultrasound sensors and solenoid
valves make a smart drip irrigation system.

18
Figure 1. . A design for home automation system [ CITATION Agr15 \l 1033 ]

1.3. CONTRIBUTION
Soil moisture is water that held in the spaces between soil particle. Soil
moisture is an important parameter to determine when to irrigate and right amount of
water to supply. Soil moisture affects to ability of the roots to extract water and
nutrient from the soil. Soil moisture also relates to the growth, productivity, and
quality of the product of the crops.

Drip irrigation allows water to drip slowly to the root zone of the plants, so it
conserves water and fertilizer. Smart drip irrigation is the combination of classic drip
irrigation with IoT and wireless sensor networks by which the plants are irrigated
automatically by the soil moisture collected from sensors. WiFi technology is applied
in many applications. WiFi technology supports for all applications online. Via WiFi,

19
we can send and update sensing data on the webserver [ CITATION Gia19 \l 1033 ].
In some applications, we can control devices via WiFi remotely. For this reason, WiFi
technology is chosen for this project. The proposed system has three main units: base
station unit (BSU), sensor unit (SU), and valve unit (VU) (in fig.). In this system, data
of humidity, temperature, and soil moisture is collected by sensor unit. Base station
works as a server node which receives data from sensor unit and makes decision based
on the threshold. Valve unit received requirement from base station unit to open or
close the valve.

SU is composed from NodeMCU ESP8266 with soil moisture sensor,


temperature and humidity sensor (DHT11). BSU is NodeMCU which works in both
station and access point mode to receive data from the sensor unit and connects to the
WiFi router to send data to webserver (in this system, data is sent to thingspeak cloud
server and displayed on each field on thingspeak). Sensing data received from SU is
displayed on the LCD screen which is connected directly with NodeMCU of BSU
instead of displaying on the computer. VU includes NodeMCU, relay, and solenoid
valve. In VU, relay is controlled directly by microcontroller to turn on or off solenoid
valve based on the requirement from BSU.

1.4. ORGANIZATION
In chapter 2, the overview of IoT is shown with definition, layers and applications in
industry and life. Impacts of natural factor and smart irrigation system are presented in
this chapter. Especially, drip irrigation system is analyzed in this chapter with details.

Chapter 3 analyzes devices in the model with details, block diagram which presents
deployment of the system. Flowcharts of each unit is presented.

Chapter 4 presents real model and results with discussion. Sensing data is sent to
webserver to show change of environmental factors.

The last chapter – chapter 5 is conclusion and future work of the model.

20
CHAPTER 2
AUTOMATED DRIP IRRIGATION BASED IOT

2.1. INTERNET OF THINGS (IOT)


2.1.1. DEFINITION AND ARCHITECTURE
Definition: Internet of things (IoT) is the advance of combination of Radio Frequency
Identification (RFID) and sensor networks. In the network of IoT, individual devices
can communicate and exchange data to other devices while they work and react
autonomously with physical environment with or without human impacts.

Architecture: There are 5 layers in the IoT architecture:

- Object layer: This layer shows physical sensors to collect and process sensing data
[ CITATION AlF15 \l 1033 ]. This layer includes 2-D bar code labels and readers,
RFID tags and reader-writers, camera, GPS, sensors, terminal, and sensor network
[ CITATION WuM10 \l 1033 ]. In this layer, sensors and actuators function as
identifying object and collecting data. Big data is created by IoT at this layer. The
main problem at this layer is recognizing and perceiving things: collecting and
capturing information. Data collected in this layer is digitalized and transferred to
the object abstraction layer through secure channels.
- Object abstraction layer: Data from object layer is transferred in this layer by
various technologies such as RF, WiFi, Bluetooth low energy, ZigBee, RFID, 3G,
infrared. This layer also functions as cloud computing and data management
processes.
- Service management layer: Service Management or middleware pairing layer pairs
a service with its requester based on addresses and names. This layer enables the
IoT application programmers to work with heterogeneous objects without
consideration to a specific hardware platform. This layer processes received data,
makes decision, and delivers the required services over the network wire protocols.
The main functions should be available for each object and allow
management in IoT. There is a basic set of services: object dynamic discovery,
status monitoring, and service configuration. An expanded set of proposal

21
functionalities are related to the QoS management and lock management, as well as
some semantic functions. To satisfy application needs, the remote deployment of
new services should be enable during run-time in this layer.
- Application layer: The application layer provides the services requested by
customers. The application layer covers numerous vertical markets such as smart
home, smart building, transportation, industrial automation and healthcare. The
challenge of this layer is to provide high quality services to the customer’s demand.
- Business layer: Business (management) layer manages the overall IoT system
activities, and services. The responsibilities of this layer are to build a business
model, graphs, flowcharts, etc. based on the received data from the Application
layer. The success of IoT is based on business model.

2.1.2. APPLICATION
- Transportation and logistics: Road and transported goods are deployed with tags
and sensors to collect information for traffic control sites and transportation
vehicles to better rout traffic, manage the depots, provide tourist, and monitor the
status of the transported goods [ CITATION Atz10 \l 1033 ].
- Healthcare: medical sensors send collected data from patients (such as body
temperature, blood pressure, breathing activity) to the remote medical centers.
From collected data, Medical centers quickly response action when needed
[ CITATION Vil09 \l 1033 ].
- Smart environments: environmental monitoring plays a key role of IoT in smart
environment which is applied in a distributed and self-managing fashion, natural
phenomena and processes such as temperature, wind, rainfall, river height
[ CITATION Atz10 \l 1033 ], [ CITATION Min19 \l 1033 ].
- Smart city: applying IoT improves the smartness of cities including many
applications to monitoring of parking spaces availability in the city, monitoring of
vibrations and material conditions in buildings and bridges, sound monitoring in
sensitive areas of cities, monitoring of vehicles and pedestrian levels, intelligent
and weather adaptive lighting in street lights, detection of waste containers levels
and trash collections, smart roads, intelligent highways with warning messages and
diversions according to climate conditions and unexpected events like accidents or
traffic jams. Some of IoT smart cities applications are smart parking, structural
22
health, noise urban maps, traffic congestion, smart lightning, waste management,
intelligent transportation systems and smart building[ CITATION Gea13 \l 1033 ],
[ CITATION Jin14 \l 1033 ].
- Smart metering and monitoring: The IoT design for smart metering and monitoring
will help to get accurate automated meter reading and issuance of invoice to the
customers. The IoT can also be used to design such scheme for wind turbine
maintenance and remote monitoring, gas, water as well as environmental metering
and monitoring [ CITATION Kha12 \l 1033 ].
- Smart agriculture: A network of different sensors can sense data, perform data
processing and inform the farmer through communication infrastructure e.g.,
mobile phone text message about the portion of land that need particular attention.
This may include smart packaging of seeds, fertilizer and pest control mechanisms
that respond to specific local condition and indicate actions. Intelligent farming
system will help agronomists to have efficient farming practices by having the
knowledge of land conditions and climate variability. This will significantly
increase the agricultural productivity by avoiding the inappropriate farming
conditions [ CITATION Kha12 \l 1033 ].

2.2. IMPACTS OF NATURAL FACTORS TO THE PLANT


GROWTH
The main source of nutrients for plant growth is often found in its surroundings.
The development of plant is dependent on the conditions of the environment in which
plants are grown. The environment consists of many factors mainly soil temperature,
soil moisture, humidity, light, ambient temperature and CO2. These climate factors
play an important role in the quality and productivity of plant growth. The various
environment factors are interrelated and cannot be considered singly without regard to
the effect on the others. A good understanding of these factors and their relationships
will help a farmer to be more aware of any potential problems that may affect the
health of the plants and appropriate measures can be taken to prevent these problems
[ CITATION Kas14 \l 1033 ].

Temperature influence most plant development process such as photosynthesis,


transpiration, absorption and flowering. Each species of plant has a different
23
temperature range in which they can grow. Above of this range, enzymes become
inactive and processes essential for life stop. Hence, temperature should be maintained
at optimum level all the time.

Humidity controls the moisture loss from the plants. CO2 enters the plants
through tiny pores of the leaves and water and oxygen leave from them. High humidity
can also affect the development of plants because fungal diseases will spread easily
and air becomes saturated with water vapor which restricts transpiration.

Light is an important source of energy for plants. Human and animals get
energy from food whereas plants get their energy from sun light through
photosynthesis. The plants would not be able to produce the energy without light.
Light also influences the growth of individual organs of a plant. This differences can
be easily demonstrated when a plant is grown in normal light and the other one is
grown in total darkness.

Soil moisture is the key parameter to determine when to irrigate and right
amount of water to supply. Water is taken from root system and lost through
transpiring leaves. The rate of water lost depends on the condition of soil, air flow,
relative humidity in air and the temperature of the environment. The farmers need to
be aware the effects of overly moist soil. The oxygen content of the plant’s root
substrate is reduced if the soil is flooded with water. This will damage the roots and as
result the roots cannot extract water and nutrient from soil. Therefore, enough water
need to be supplied to the plants all the time (also known as “Precision Irrigation”).

Table 2. . Suitable condition for some types of plants

pH Soil moisture Temperature Humidity Ref.


(%) (oC) (%)
Cabbage 5.6-6.0 75-80 18-20 80-90 [ CITATIO
N htt \l
1033 ]
Lettuce 5.5-6.6 70-80 18-25 80-90 [CITATIO
N htt1 \l
1033 ],
[CITATIO
N htt2 \l
1033 ]

24
Pepper 5-6 70-80 10-35 70-90 [CITATIO
N htt4 \l
1033 ],
[CITATIO
N htt5 \l
1033 ]
Sugarcan 5.5-7.5 65-80 20-30 75-85 [CITATIO
e N htt6 \l
1033 ]

2.3. AUTOMATED IRRIGATION UTILIZING WIRELESS


COMMUNICATION TECHNOLOGY
Irrigation is defined as the artificial application of water in agricultural land and
it is considered as one of the most important constituents of agriculture. Scarcity of
water in several areas instigates the need of proper use of water in several areas
instigates the need of proper use of water that is water should be provided to only
those places where it is needed an in required quantity. Different methods of irrigation
are in use like drip irrigation, sprinkler irrigation etc. to cope up with the water
wastage problem in traditional methods like flood irrigation, furrow irrigation etc.

A smart irrigation system regulates supplied water according to the needs of the
fields and crops. The feedback mechanism of a smart irrigation system is a moisture
sensor [ CITATION roleagri \l 1033 ]. Along with various IoT application areas
agriculture includes cultivation and water management. A wide range of sensors can
be used for agricultural applications, viz. leaf wetness, soil moisture, temperature,
humidity, ultraviolet and solar radiations, wind vanes, pluviometer, etc. IoT comprises
of deployment of sensors at the respective application fields and storage of their data
cloud for processing. The same concept can be used for irrigation system for
monitoring and controlling. There are various communication technologies for IoT.
“Various WSN solutions have been proposed based on IEEE 802.15.4 standards, e.g.
ZigBee, 6LoWPAN, etc. The IoT architecture includes sensors and actuators
connected to IoT gateway via various local wireless network. The other side of the
gateway is connected to IP based wireless actuator network and can be accessed from
Cloud systems. Controller algorithm is required to run on IoT gateway [ CITATION
Sar17 \l 1033 ]. Four factors are popularly being used in smart irrigation system such
25
as, integration of real-time weather forecast data, control of farmer’s system from
anywhere in the world using home, enabling WiFi and Ethernet connection, adding
synchronization with moisture sensors installed in farmer’s yard, and reducing
farmer’s monthly bills while helping to conserve limited water resources. IoT is
constantly getting popularity in irrigation management related systems around the
world.

2.3.1. SENSORS IN AUTOMATED IRRIGATION SYSTEMS


Sensors are hardware devices that produce measurable response to a change in a
physical condition like temperature, pressure and humidity. The output of the sensor is
analog signal. Analog signal is digitalized by an analog to digital converter. After
processing, digital signal is sent to controller for further processing. There are many
types of sensors from which we can select the suitable and appropriate sensor
depending on the application. In this section, I discuss some typical types of sensors in
agriculture such as: moisture sensor, temperature sensor, humidity sensor, pH sensor.

a. Moisture sensor

The Moisture Sensor detects the moisture of the soil around the sensor, which is
ideal for monitoring the plants or the soil moisture. This sensor uses the two probes to
pass current through the soil, and then it reads that resistance to get the moisture level.
Excess water makes the soil conduct electricity better; while dry soil conducts
electricity poor. Fig. 2.1, shows a typical moisture sensor used in the proposed system.

26
Figure 2. . A typical soil moisture sensor

Moisture sensor placement needs to be consider to measure and provide accurate data
for irrigation. For instance, in [ CITATION Sti95 \l 1033 ], author worked with potato
and proposed the ideal sensor location for monitoring soil water status and scheduling
irrigations are offset 0.15m from the center of the hill and 0.1 to 0.2m deep to response
for four hours to wetting. In [ CITATION Dur11 \l 1033 ], the soil moisture sensor is
located 20cm of depth from ground and 50cm far away from the dwarf cherry tree to
show the change of water content.

b. pH sensor

Figure 2. . pH sensor

27
The pH value of soil is an important factor in determining which crops
will grow. Also by monitoring these values carefully, necessary amount of
nutrients can be supplied to the plants to have a healthy growth.

c. Humidity sensor

Humidity is the amount of water vapor present in the air. It indicates the exact
amount of water vapor present in the air. It converts directly relative humidity to
voltage [ CITATION Kri17 \l 1033 ]. Fig.2.3 shows a typical humidity sensor

Figure 2. . Humidity sensor

d. Temperature sensor

Temperature sensor measures temperature in the air which can affect


growth, germination, sprouting, flowering and fruit development.
Temperature sensor – LM35 is a typical sensor in smart agriculture. LM35 is
an integrated circuit sensor that can be used to measure temperature with an
electrical output proportional to the temperature [ CITATION Gon16 \l 1033 ],
[ CITATION Sar17 \l 1033 ].

28
Figure 2. . LM35 sensor

2.3.2. COMMUNICATION TECHNOLOGY IN AUTOMATED IRRIGATION


Wireless communication technologies like ZigBee, Bluetooth and WiFi
are part of several sensor network based research works. These technologies
have different capabilities and properties on which they are complemented. A
brief comparison is given in Table 2.2 [ CITATION Abb \l 1033 ].

Table 2. . Comparison of communication technologies

ZigBee Bluetooth WiFi

Frequency 2.4GHz 2.4GHz 2.4GHz

Range 30m – 1.6km 8-10m 20-100m

Data rate 250 kbps 1 Mbps 11-54 Mbps

Cost Low Low High

Security 128 bit 64 or 128 bit 128 bit

ZigBee: ZigBee technology defines the network and application layer protocols based
on the IEEE 802.15.4 standard (IEEE Standard for Information technology, 2006)
physical and MAC layer definitions required for designing a wireless personal area
network (WPAN) using low power radio-enabled devices. Being energy-efficient, low
cost, and reliable, the ZigBee technology is preferred for WSN-based applications in

29
the agricultural and farming domains. ZigBee also supports short-distance (10–20 m)
data communication over multi-tier, decentralized, ad-hoc and mesh networks. The
ZigBee-enabled devices have a low-duty cycle, and thus, are suitable for agricultural
applications such as irrigation management, pesticide and fertilizer control, water
quality management, where periodic information update is required. However, ZigBee
applications yield low data rates of only 20–40 kbps and 250 kbps at 868/915 MHz
and 2.4 GHz frequencies of ISM band, respectively. Typically, this standard requires
low specification hardware (such as microprocessor with 50–60 kb memory) and
includes security encryption techniques.

WiFi: WiFi is a wireless local area network (WLAN) standard for information
exchange or connecting to the Internet wirelessly based on the IEEE 802.11 standards
family (IEEE 802.11, 802.11a/b/g/n) (IEEE Standard for Information technology,
2005, 2012a). Currently, it is the most widely used wireless technology found in
devices ranging from smart phones and tablets to desktops and laptops. WiFi provides
a decent communication range in the order of 20 m (indoor) to 100 m (outdoor) with
data transmission rate in the order of 2–54 Mbps at 2.4 GHz frequency of ISM band.
In agricultural applications, WiFi broadens the use of heterogeneous architectures
connecting multiple type of devices over an ad-hoc network.

Bluetooth: Bluetooth (IEEE Standard for Information technology, 2012b; Bluetooth


Technology Special Interest Group), which is based on the IEEE 802.15.1 standard, is
a low power, low cost wireless technology used for communication between portable
devices and desktops over a short range (8–10 m). The Bluetooth standard defines a
personal area network (PAN) communication using the 2.4 GHz frequency of the ISM
band. The data rate achieved in various versions of the Bluetooth ranges from 1 to 24
Mbps. The advantages of this technology are its ubiquitous nature, and therefore, it is
suitable for use in multi-tier agricultural applications. The ultralow power, low cost
version of this standard is named as Bluetooth Low Energy (BLE), which was initially
introduced by Nokia in 2006 as Wibree. However, in 2010, BLE was merged with
main Bluetooth standard version 4.0. BLE also uses the 2.4 GHz ISM frequency band
with adaptive frequency hopping to reduce interference. Also, BLE includes 24 bit
CRC and AES 128-bit encryption technique on all packets to guarantee robustness and

30
authentication. BLE topology supports one-to-one as well as one-to-many connections
between devices.

2.4. AUTOMATED DRIP IRRIGATION SYSTEM


Drip irrigation is the most efficient method of irrigating. While sprinkler
systems are around 75-85% efficient, drip irrigation systems typically are 90% or
higher. It is easy to install, easy to design, can reduce disease problems associated with
high levels of moisture on some plants. There already exist automatic drip irrigation
systems which water plants based on soil humidity, pH value of soil, temperature and
light. These parameters are required in big agricultural fields where productivity of the
crop matters.

Figure 2.5 shows a model of smart drip irrigation. Sensor unit senses
environmental parameters and sends to the base station unit. At base station unit, data
is displayed on computer and sent to internet. Users can monitor of the field on
internet or via computer. Irrigation is also controlled automatically by the threshold
which is pre-set at base station. Base station identify position of the valve to turn
ON/OFF. Each solenoid is installed with a wireless module to receive requirement
from base station and control position of the valve.

31
Figure 2. . A smart drip irrigation system model

Backflow preventer: A device that allows water to go through it in one direction, but
prevents it from going backwards in the opposite direction.

A backflow preventer is like a one-way gate for water. Most backflow preventers are
used to keep unsafe water from reversing flow and entering the clean water supply.
Backflow preventers can be as simple as a single check valve that closes when water
flow reverses. Using a simple check valve as a backflow preventer might be
considered the equivalent of a turnstile at a store entrance.  It is not very reliable, even
a small amount of effort will overcome it.  A more elaborate backflow preventer can
be a complicated device that consists of multiple check valves, water release valves,
air vents, and/or systems to allow it to be tested to assure it is working properly. This
kind of backflow preventer might be the equivalent of an airport exit security
checkpoint with one-way gates and a guard.

32
Pressure regulator: Pressure regulators reduce incoming water pressure to a set
pressure usable by a drip system. A pressure regulator is used when the incoming
pressure is too high for the emitters or fittings. The flow rate of the regulator should be
matched with the system. Pressure regulation does not take effect until minimum
specified flow passes through the regulator.

Pressure gauges: Pressure gauges are essential components in a drip irrigation


system. Providing vital information concerning the irrigation system, they help in the
detection of leaks and clogging and in the management of filters, chemical injectors
and in keeping the system in its operating range. To acquire as accurate as possible
data always use a pressure in the system should be roughly at the midpoint of the
gauge’s scale.

Valves: In an irrigation system, water flow rate and pressure throughout the system
should be precisely controlled to ensure efficient and timely water application;
therefore, proper selection and placement of valves is critical. Valves play key roles in
controlling pressure, flow and distribution under different conditions to optimize
performance, facilitate management, and reduce maintenance requirements.

Mainline: the mainline is the pipe that goes from the water source to the control
valves. The mainline pipe may be made of galvanized steel, copper, SCH 40 PVC,
SCH 80 PVC, Heavy Wall Polyethylene (SDR 7 or SDR 9) or PEX.

Lateral and/or sub-main line: The lateral is the pipe located between a control valve
and the drip tube. Some people use the name “sub-main” for this same pipe. The
lateral pipe may be PVC, PEX, or polyethylene. The lateral is located after
(downstream) of the pressure regulator so it is not necessary to use a pipe with a high
pressure rating. Class 200 PVC or standard “polyethylene irrigation pipe” work good
for laterals. Class 125 PVC may also be used but be careful as it breaks easily. PVC is
damaged by sunlight and should be buried or protected. Apply several heavy coats of
paint or wrapping PVC with aluminum tape if it is above ground. Laterals are at the
heart of a drip irrigation system. In any irrigation system, the design process starts at
the plant and proceeds to lateral design. It is important to know what to take into
consideration during lateral design: lateral selection, wall thickness, dripper flow rate,

33
spacing between drippers, spacing between laterals, and specification of dripper
insertion depth (in SDI).

Drippers/Emitters: drippers incorporated at uniform spacing along the lateral deliver


water and nutrients directly to the plant root zone. A typical drip irrigation system
includes thousands of drippers. Each dripper should be durable, resistant to clogging,
and emit the same amount of water. Wide water passages guarantee long-term trouble-
free performance. The flow rate and spacing of the drippers is important in
determining the wetting pattern and for the prevention of runoff or deep percolation. A
properly operated and maintained drip irrigation system provides water and nutrients to the
crop root zone without runoff or deep percolation.

Pressure in whole irrigation is needed to consider. In this model, pressure loss drops on the
devices such as: valve, backflow preventer, mainlines and lateral, drip tube, and emitter. For
instance, pressure loss is drop on each part below [ CITATION htt7 \l 1033 ]:

+ Valve 0.4 bars

+ Backflow preventer 0.8 bars

+ Pressure regulator 0.0 bars

+ Mainline and lateral 0.4 bars

+ Drip tube 0.2 bars

+ Emitter 1.0 bars

Total pressure 2.8 bars

Based on 0.2 l/s flow for 20mm valve with smaller supply, 0.4 l/s flow for 20mm
valve, and 0.9 l/s for 25 mm valve

34
CHAPTER 3
SYSTEM DESIGN

3.1. HARDWARE
3.1.1. NODEMCU ESP8266ESP-12E WIFI DEVELOPMENT BOARD
NodeMCU is an open source IoT platform. It includes firmware which runs on
the ESP8266 Wi-Fi SoC from Espressif Systems, and hardware which is based on the
ESP-12 module. The term “NodeMCU” by default refers to the firmware rather than
the DevKit. Thee firmware uses the lLua scripting language. It is based on the eLua
project, and built on the Espress Non-OS SDK for ESP8266. It uses many open source
projects, such as lua-cjson, and spiffs.

Figure 3. . NodeMCU esp8266

Features:

Version: DevKit v1.0

Breadboard Friendly

Light Weight and small size

3.3V operated, can be USB powered

Uses wireless protocol 802.11b/g/n

35
Built-in wireless connectivity capabilities

Built-in PCB antenna on the ESP-12E chip

Capable of PWM, I2C, SPI, UART, 1-wire, 1 analog pin

Uses CH340 USB Serial Communication interface module

Arduino IDE compatible (extension board manager required)

Supports Lua (alike node.js) and Arduino C programming language

Package included:

3 x ESP8266 CH340 Development Board

Pinout Diagram

Figure 3. . NodeMCU pinout diagram

Specifications of ESP-12E WiFi Module

Wireless Standard: IEEE 802.11 b/g/n

Frequency Range: 2.412-2.484 GHz

Power Transmission: 802.11b: +16 ± 2dBm (at 11 Mbps)

36
802.11g: +14 ± 2dBm (at 54 Mbps)

802.11n: +13 ± 2dBm (at HT20, MCS7)

Wireless Form: On-board PCB Antenna

IO Capability: UART, I2C, PWM, GPIO, 1 ADC

Electrical Characteristic: 3.3V operated

15 mA output current per GPIO pin

12 – 200 mA working current

Less than 200μA standby current

Operating Temperature: -40 to +125 ⁰C

Serial transmission: 110 – 921600 bps, TCP Client 5

Wireless Network Type: STA / AP / STA + AP

Security Type: WEP / WPA-PSK / WPA2 – PSK

Encryption Type: WEP64 / WEP128 / TKIP / AES

Firmware Upgrade: Local Serial Port, OTA Remote Upgrade

Network Protocol: Ipv4, TCP / UDP / FPT / HTTP

User Configuration: AT + Order Set, Web Android / iOS, Smart Link APP

3.1.2. TEMPERATURE AND HUMIDITY SENSOR DHT11

Figure 3. . Sensor DHT11

37
DHT11 is a temperature and humidity sensor, it was produced with the purpose of
replacing SHT1x brand sensors for applications and projects not require high accuracy
in temperature and humidity. DHT11 is constructed with 3 pins V CC, Output and
Ground and it uses Serial Interface (Single-Wire Two-Way) communication process.

Table 3. . DHT11 Overview

Item Measurement Humidity Temperature Resolution Package


range accuracy accuracy
DHT11 20-90%RH ±5%RH ±2oC 1 4 Pin
0-50oC Single Row

38
Detailed Specifications:

Table 3. . DHT11 detailed specifications

Parameters Conditions Minimum Typical Maximum


Humidity
Resolution 1%RH 1%RH 1%RH
8 Bit
Repeatability ±1%RH
Accuracy 25oC ±4%RH
0-50oC ±5%RH
Interchangeability Fully Interchangeable
Measurement 0oC 30%RH 90%RH
range 25oC 20%RH 90%RH
o
50 C 20%RH 80%RH
o
Response Time 1/e(63%)25 C 6S 10 S 15 S
(Seconds) 1m/s Air
Hysteresis ±1%RH
Long-term Typical ±1%RH/year
stability
Temperature
Resolution 1oC 1oC 1oC
8 bit 8 bit 8 bit
Repeatability ±1oC
Accuracy ±1oC ±2oC
Measurement 0oC 50oC
range
Response Time 1/6e(63%) 6S 30 S
(Seconds)

Working principle:

39
Figure 3. . Connection between DHT11 with MCU

Note: MCU = Micro-computer Unite or single chip Computer

When the connecting cable is shorter than 20 meters, a 5K pull-up resistor is


recommended; when the connecting cable is longer than 20 meters, choose an
appropriate pull-up resistor as needed. DHT11’s power supply is 3-5.5v DC. One
capacitor valued 100nF can be added between Vcc and GND for power filtering.

Single-bus data format is used for communication and synchronization between MCU
and DHT11 sensor. One communication process is about 4ms.

Data consists of decimal and integral parts. A complete data transmission is 40


bit, and the sensor sends higher data bit first. Data format: 8bit integral RH data + 8bit
decimal RH data + 8bit integral T data + 8bit decimal T data + 8bit check sum. If the
data transmission is right, the check-sum should be the last 8bit of “8bit integral RH
data + 8bit decimal RH data + 8bit integral T data + 8bit decimal T data”.

Overall Communication Process:

When MCU sends a start signal, DHT11 changes from the low-power-
consumption mode to the running-mode, waiting for MCU completing the start signal.
Once it is completed, DHT11 sends a response signal of 40bit data include the relative
humidity and temperature information to MCU. Without the start signal from MCU,
DHT11 will not give the response signal to MCU. Once data is collected, DHT11 will

40
change to the low-power-consumption mode until it receives a start signal from MCU
again.

Figure 3. . DHT11 overall communication process

Data Single-bus free status is at high voltage level. When the communication
between MCU and DHT11 begins, the program of MCU will set Data Single-Bus
voltage level from high to low and this process must take at least 18ms to ensure
DHT’s detection of MCU’s signal, then MCU will pull up voltage and wait 20-40us
for DHT’s response. Once DHT detects the start signal, it will send out a low-voltage-
level response signal, which lasts 80us. Then the program of DHT sets Data Single-
bus voltage level from low to high and keeps it for 80us for DHT’s preparation for
sending data. When DATA Single-Bus is at the low voltage level, this means that
DHT is sending the response signal. Once DHT sent out the response signal, it pulls up
voltage and keeps it for 80us and prepares for data transmission.

When DHT is sending data to MCU, every bit of data begins with 50us low-
voltage-level and the length of the following high-voltage-level signal determines
whether data bit is “0” or “1”.

If the response signal from DHT is always at high-voltage-level, it suggests that


DHT is not responding properly and we need to check the connection. When the last
bit data is transmitted, DHT11 pulls down the voltage level and keeps it for 50us. Then
the Single-Bus voltage will be pulled up by the resistor to set it back to the free status.

41
3.1.3. SOIL MOISTURE SENSOR LM393
Soil moisture sensor is a sensor which senses the moisture content of the soil.
The sensor has both the analog and the digital output. The low output state is 0V, and
the high output state is 5V. LM393 comparator is used in the module to compare the
soil moisture level. The comparator module uses IC LM393. The output state of the
soil can be shown by the LED on the module if it is LOW or HIGH.

Figure 3. . Soil moisture sensor LM393

Specification

- Pins: A0, D0, VCC, GND


- Output:
+ A0: analog signal
+ D0: logic 0, 1

Table 3. . Technical specification of Soil sensor module

PCB size 71.65mm x 24.00mm x 1,6mm

Working voltage 3,3 or 5V DC

Operating voltage 3,3 or 5V DC

42
Compatible interfaces 2.54 3-pin interface and 4-pin Grove interface

3.1.4. MODULE 1 RELAY


Relays consist of three pins normally open pin, common pin and coil. When
coil powered on magnetic field is generated the contacts connected to each other.

Figure 3. . Working principle of the relay

Relay is used to change status of the device. Module 1 relay is ON with LOW
level trigger. One end of the load can be connected to the Common pin and the other
end is either connected to NO or NC. If connected to NO the load remains
disconnected before trigger and if connected to NC the load remains connected before
trigger.

This is a module 1 relay LOW level trigger relay and it can be applied to
Arduino and Raspberry Pi. Relays are suitable for driving high power electronic
devices such as lights, electric fans and air condition. A relay can be used to control
high voltages with a low voltage by connecting it to an MCU.

43
Figure 3. . Module 1 relay

Feature:

- Operating voltage: 5V DC
- Relay rated: 220V 10A
- Relay has indication LED
- ON is 0, and OFF is 1

3.1.5. SOLENOID VALVE


A solenoid valve is an electromechanically operated valve. Solenoid valves differ in
the characteristics of the electric current they use, the strength of the magnetic field
they generate., the mechanism they use to regulate the fluid, and the type and
characteristics of fluid they control. The mechanism varies from linear action, plunger-
type actuators to pivoted-armature actuators and rocker actuators. The valve can use a
two-port design to regulate a flow or use a three or more port design to switch flows
between ports. Multiple solenoid valves can be paced together on a manifold.

Solenoid valves are the most frequently used control elements in fluidics. Their tasks
are to shut off, release, dose, distribute or mix fluids. They are found in many
application areas. Solenoids offer fast and safe switching, high reliability, long service

44
life, good medium compatibility of the materials used, low control power and compact
design.

There are two popular types of the solenoid: normally open and normally closed. If the
valve is open when the solenoid is not energized, then the valve is termed normally
open. Similarly, if the valve is closed when the solenoid is not energized, then the
valve is termed normally closed.

In this project, I chose normally closed valve which is shown in the figure 3.9.

Figure 3. . Solenoid valve

Feature:

- Operating voltage: 12V DC


- Radius of the pipe: 12mm

3.1.6. LCD16X2
LCD16x2, or 16x2 character-type liquid crystal display, is a kind of dot matrix
module to show letters, numbers, and characters and so on. It's composed of 5x7 or
5x11 dot matrix positions; each position can display one character. There's a dot pitch
between two characters and a space between lines, thus separating characters and lines.
The model 16x2 means it displays 2 lines of 16 characters.
45
Generally, LCD16x2 has parallel ports, that is, it would control several pins at the
same time. LCD16x2 can be categorized into eight-port and four-port connections. If
the eight-port connection is used, then all the digital ports of the SunFounder Uno
board are almost completely occupied. If you want to connect more sensors, there will
be no ports available. Therefore, the four-port connection is used here for better
application.

Figure 3. . Pin diagram of LCD1602

 Pins Functions

Table 3. . Pins function of LCD16x2

 Pin
 Function  Name
No
1 Ground (0V) Ground
2 Supply voltage; 5V (4.7V – 5.3V)  VCC
3 Contrast adjustment; through a variable resistor  VEE
Selects command register when low; and data Register
4
register when high Select

46
Low to write to the register; High to read from the
5 Read/write
register
Sends data to data pins when a high to low pulse is
6 Enable
given
7 DB0
8 DB1
9 DB2

10 DB3
8-bit data pins
11 DB4

12 DB5

13 DB6
14 DB7
15 Backlight VCC (5V) Led+
16 Backlight Ground (0V) Led-

3.1.7. I2C MODULE

Product features: The I2C 1602 LCD module is a 2 line by 16-character display
interfaced to an I2C daughter board. The I2C interface only requires 2 data
connections, +5 VDC and GND to operate.

Figure 3. . Diagram of I2C module

47
Specifications:

Table 3. . Specification of I2C 16x02 serial LCD module

I2C Address Range 2 lines by 16 character 0x20 to 0x27


(Default=0x27, addressable)

Operating Voltage 5 VDC

Backlight White

Contrast Adjustable by potentiometer on I2C interface

Size 80mm x 36mm x 20 mm

Viewable area 66mm x 16mm

3.1.8. POWER SOURCE


LM2596 DC/DC step-down voltage converter

In this model, sensors, nodeMCU, and relay operate at 5V DC, so I need to use
a step-down converter to convert voltage from 12V DC to 5V DC.

Figure 3. . LM2596 DC/DC step-down voltage converters

48
The LM2596 regulator is monolithic integrated circuit ideally suited for easy and
convenient design of a step-down switching regulator (buck converter). It is capable of
driving a 3.0A load with excellent line and load regulation. This device is available in
adjustable output version and it is internally compensated to minimize the number of
external components to simplify the power supply design.

 Technical specification
- Adjustable output voltage ranges 1.23V – 37V
- Guaranteed 3.0A output load current
- Wide input voltage ranges up to 40V
- 150 kHz Fixed frequency internal oscillator
- TTL shutdown capability
- Low power standby mode, typ 80µA
- Thermal shutdown and current limit protection
- Internal loop compensation
- Moisture sensitivity level (MSL) equals 1

UltraFire battery

UltraFire battery is rechargeable battery. It is suitable for robotic model, sensor node,
and energy storage. In this project, I use ultrafire battery for sensor node, because
sensor nodes are usually deployed far away to the base station and solenoid valve. In
addition, batteries just can supply voltage level at 3.7V, so voltage level is not enough
for all devices in sensor unit. I have to connect batteries in series, and then a LM2596
DC/DC step-down voltage converter is used to reduce voltage to 5V suitable for
nodeMCU and sensors.

49
Figure 3. . UnltraFire battery

Table 3. . Technical Specification of The battery Ultrafire

Name The battery ultrafire


Voltage DC 3.7V( max 4.2V)
Type Nickel-cadmium( rechargeable)
Capacity 1200mAH
Temperature work -20 ℃ ~ 45 ℃

3.2. SOFTWARE
3.2.1. ARDUINO IDE
Arduino is a both an open source software library and an open-source breakout board
for the popular AVR micro-controllers. The Arduino IDE (Integrated Development
Environment) is the program used to write code, and comes in the form of a
downloadable file on the Arduino website. The Arduino board is the physical board
that stores and performs the code uploaded to it. Both the software package and the
board are referred to as "Arduino."

Cross-platform - The Arduino software runs on Windows, Macintosh OSX, and Linux
operating systems. Most microcontroller systems are limited to Windows.
50
Simple, clear programming environment - The Arduino programming environment is
easy-to-use for beginners, yet flexible enough for advanced users to take advantage of
as well. For teachers, it's conveniently based on the Processing programming
environment, so students learning to program in that environment will be familiar with
the look and feel of Arduino.

Open source and extensible software - The Arduino software is published as open
source tools, available for extension by experienced programmers. The language can
be expanded through C++ libraries, and people wanting to understand the technical
details can make the leap from Arduino to the AVR C programming language on
which it's based. Similarly, you can add AVR-C code directly into your Arduino
programs if you want to.

To code for Arduino, we use C language written on Arduino IDE software. Arduino
IDE has a large library that easy to code. Moreover, its theme is easy to see and use.

Figure 3. . Arduino IDE Software

51
3.2.2. THINGSPEAK WEBSERVER

Figure 3. . Thingspeak

“ThingSpeak” is an open source Internet of Things (IoT) application and


API to store and retrieve data from things using the HTTP protocol over the Internet or
via a Local Area Network. ThingSpeak enables the creation of sensor logging
applications, location tracking applications, and a social network of things with status
updates".

ThingSpeak was originally launched by ioBridge in 2010 as a service in support


of IoT applications

ThingSpeak has integrated support from the numerical computing software


MATLAB from MathWorks allowing ThingSpeak users to analyze and visualize
uploaded data using Matlab without requiring the purchase of a Matlab license from
Mathworks.

ThingSpeak has a close relationship with MathWorks, Inc. In fact, all of the


ThingSpeak documentation is incorporated into the Mathworks' Matlab
documentation site and even enabling registered Mathworks user accounts as valid
login credentials on the ThingSpeak website. The terms of service and privacy policy
of ThingSpeak.com are between the agreeing user and Mathworks, Inc.

ThingSpeak has been the subject of articles in specialized “Maker" websites


like Intrucstables, Codeproject, and Channel 9.
52
3.3. BLOCK DIAGRAM AND FLOWCHART
As the figure below, sensing data is collected by sensor unit, and then data is
sent to base station to display on LCD or PC. Base station and valve unit are connected
with WiFi router together. Sensing data is sent to webserver and displayed on LCD
instead of PC in this model. In case of real model in agriculture, base station make
decision to turn ON/OFF the valve based on sensing data and find the position of the
valve which is need to turn. In this model, a node MCU is used as server and base
station. It works in both station and access point mode. In access point mode, it creates
WiFi for the sensor unit to connect and send data. In station mode, it connects to WiFi
router to send data to webserver and sends decision to valve unit to control the
solenoid valve.

Figure 3. . Diagram of the system

53
Sensor unit detects temperature, humidity, and soil moisture via GIPO pins of
NodeMCU. After processed in microcontroller of NodeMCU – ESP8266EX, collected
data is sent to base station unit. Flowchart of sensor unit is shown below:

Figure 3. . Flow chart of sensor unit

In base station unit, a NodeMCU is used as server to receive data from sensor unit and
send decision to turn ON/OFF the valve in valve unit. The flowchart of base station
unit is shown in the figure 3.18 below:
54
Figure 3. . Flow chart of base station unit

Valve unit just receives decision from base station to change the working position of
the solenoid valve. In this project, the solenoid valve uses voltage at 12V DC so, the
solenoid valve is controlled via a relay which is controlled by nodeMCU though a
GPIO pin. Figure 3.19 is the flowchart of valve unit:

55
Figure 3. . Flowchart of valve unit which controls solenoid valve

56
CHAPTER 4
EXPERIMENTS AND RESULTS

4.1. REAL MODEL

Figure 4. . The model is running

This system uses WiFi technology to communicate each other. Data is sent
wirelessly from SU to BSU and from BSU to VU. Sensing data sent from SU is
displayed in LCD16x2 instead of computer. SU includes soil moisture sensor and
temperature and humidity sensor (DHT11). At BSU, nodeMCU works at access point
and station mode. It can both create WiFi wave for SU and connect to WiFi router to
transmit data to Thingspeak webserver and decision to control solenoid valve based on
comparison moisture value and threshold. At VU, nodeMCU receives data at 0 and 1
to set pin mode to control relay at LOW and HIGH respectively.

57
4.1.1. SENSOR UNIT MODEL

Figure 4. . Sensor unit

Because all devices in SU operate at 5V DC, and batteries are connected in


series, a step-down converter is used to create stable output voltage for this unit. In
addition, sensors consume low power, and communication consumes almost energy. I
use ultrafire batteries for SU.

58
4.1.2. BASE STATION UNIT MODEL

Figure 4. . Base station unit

LCD16x2 is connected directly to nodeMCU to show sensing data. BSU compares


moisture data with the threshold. If moisture is less than threshold, BSU sends number
0 to VU, otherwise number 0 is sent to VU.

59
4.1.3. VALVE UNIT MODEL

Figure 4. . Valve unit

Because operating voltage of nodeMCU is 5V DC while operating voltage of solenoid


valve is 12V, solenoid valve is controlled via a relay. NodeMCU receives data from
BSU, and then it sets logic level of the pin connected to relay at LOW or HIGH
respect to 0 and 1.

4.2. EXPERIMENTAL RESULTS AND DISCUSSION


In these experiments, I set the threshold of soil moisture at 70%. If soil moisture is less
than 70%, BSU sends number 0 to VU, after VU receives number 0, nodeMCU
changes logic level at the port connecting to relay to LOW logic to open solenoid

60
valve. If soil moisture is greater than 70%, BSU sends number 1 to VU, after VU
receives number 1, nodeMCU changes logic level at the port connecting to relay to
HIGH logic to close solenoid valve.

Figure 4. . Experimental model

Experimental results are sent to thingspeak webserver. In these experiments,


sensing data is presented on each field on the web. On the web, we can see the change
of environmental factors during 30 minutes.

61
Figure 4. . Temperature is shown on thingspeak

Change of temperature is presented on web. Depending on the stage of plants, user can
make decision if extraordinary factors take place. In addition, temperature can be used
to control cooling fan in greenhouse.

Figure 4. . Humidity on thingspeak

The change in humidity in the air is shown on thingspeak.

62
Figure 4. . Soil moisture on thingspeak

Water is dripped into the soil. In this experiment, I place soil sensor at 10cm deep and
10cm far from emitter to show the change in moisture. The threshold is set at 70% to
send value 0(ON) to VU. Because of property of the soil, the spread of water in the
soil oscillates sometime around 70% as in the figure 4.7. Soil moisture changes slowly
in time of testing. In drip irrigation, water spreads slowly into the soil, so moisture
changes gradually, but sometime increases over the threshold and decrease
immediately.

63
CHAPTER 5
CONCLUSION AND FUTURE WORK
Conclusion: In this project, IoT is applied in irrigation for agriculture. WiFi
technology is used to transmit data from sensor unit to base station unit and from base
station unit to valve unit to turn ON/OFF solenoid valve. Temperature, humidity, and
soil moisture are detected to send to base station. Collected data is sent to webserver
and displayed on LCD at base station. Users can monitor environment at base station
or via Internet. Soil moisture is used to irrigate for the plant. A model of drip irrigation
is installed and tested. Experimental result shows the change of soil moisture in drip
irrigation.

Future work: Humidity is the most important for the plant, but there are several
factors which impact to the plant growth and productivity. Other factors are nutrient,
light, pH, … In the future, these factors are need to be considered in automated drip
irrigation. Temperature and humidity can be used to control cooling fan in green
house. In addition, IoT can be applied in whole irrigation system to control other
devices in systems such as pressure in the pipes, water level in the tank. Because a
filtering tank is used in drip irrigation systems, water level in the tank is need to be
monitored to turn ON/OFF the pump automatically. Lifetime of network is also an
important problem. Wireless system can use rechargeable batteries with solar cell to
power for not only sensor unit, but also valve unit. Otherwise, other communication
can be applied in this model such as ZigBee, Bluetooth, and the combination between
these communication technologies is need to consider for large field, transmitting data
for long distance and stability of systems.

64
REFERENCES

[1] [Online]. Available: https://en.wikipedia.org/wiki/Population_growth#cite_note-


3.
[2] A. e. a. Kumar, "Smart irrigation using low-cost moisture sensors and XBee-
based communication," in IEEE Global Humanitarian Technology Conference
(GHTC 2014), IEEE, 2014.
[3] I. e. a. Mahmood, "Effects of pesticides on environment," in Plant, soil and
microbes, Cham, Springer, 2016, pp. 253-269.
[4] H.-J. K. A. S. a. J. W. H. Kim, "Soil macronutrient sensing for precision
agriculture," Journal of Environmental Monitoring, vol. 11, no. 10, pp. 1810-
1824, 2009.
[5] G. e. a. Evanylo, "Soil and water environmental effects of fertilizer-, manure-,
and compost-based fertility practices in an organic vegetable cropping system,"
Agriculture, ecosystems & environment, vol. 127, no. 1-2, pp. 50-58, 2008.
[6] W. G. D. J. M. a. I. W. M. Bastiaanssen, "Remote sensing for irrigated
agriculture: examples from research and possible applications," Agricultural
water management , vol. 46, no. 2, pp. 137-155, 2000.
[7] C. K. a. P. B. Sahu, "A low cost smart irrigation control system." , 2015.," in 2nd
International conference on electronics and communication systems (ICECS),
IEEE, 2015 .
[8] G. e. a. Oron, "Wastewater treatment, renovation and reuse for agricultural
irrigation in small communities," Agricultural water management, vol. 38, no. 3,
pp. 223-234, 1999.
[9] R. J. L. S. a. M. R. Hussain, "Control of irrigation automatically by using
wireless sensor network." ().," 2013.
[10] A. Z. N. I. a. Z. A. S. Abbasi, "A review of wireless sensors and networks'
applications in agriculture," Computer Standards & Interfaces, vol. 36, no. 2, pp.

65
263-270, 2014.
[11] N. a. R. S. K. Gondchawar, "IoT based smart agriculture," International Journal
of advanced research in Computer and Communication Engineering, vol. 5, no.
6, pp. 838-842, 2016.
[12] P. a. S. D. M. Rajalakshmi, " IOT based crop-field monitoring and irrigation
automation," in 10th International Conference on Intelligent Systems and
Control (ISCO). IEEE, IEEE, 2016 .
[13] N. a. S. S. Agrawal, "Smart drip irrigation system using raspberry pi and
arduino," in International Conference on Computing, Communication &
Automation, IEEE, 2015.
[14] T. H. L. H. T. M. N. Giang Tran, "A Design of Sensing Data Collection Circuits
for Wireless Sensor Networks Utilizing WiFi Technology," ICSES Transactions
on Computer Hardware and Electrical Engineering (ITCHEE), vol. 5, no. 1, pp.
1-5, Mar.2019.
[15] A. e. a. Al-Fuqaha, "Internet of things: A survey on enabling technologies,
protocols, and applications," IEEE communications surveys & tutorials, vol. 17,
no. 4, pp. 2347-2376, 2015.
[16] M. e. a. Wu, "Research on the architecture of Internet of Things," in 3rd
International Conference on Advanced Computer Theory and Engineering
(ICACTE), IEEE, 2010.
[17] L. A. I. a. G. M. Atzori, "The internet of things: A survey," Computer networks,
vol. 54, no. 15, pp. 2787-2805, 2010.
[18] A. M. e. a. Vilamovska, "Rfid application in healthcare–scoping and identifying
areas for rfid deployment in healthcare delivery," RAND Europe, February
(2009).
[19] H. T. V. G. N. T. K. H. D. Minh Nguyen, "Wireless Communication
Technologies and Applications for Wireless Sensor Networks: A Survey," ICSES
Transactions on Computer Networks and Communications, vol. 5, no. 1, pp. 1-
15, Apr. 2019.
[20] T. e. a. Gea, "Smart cities as an application of internet of things: Experiences and
lessons learnt in barcelona," in 2013 Seventh International Conference on

66
Innovative Mobile and Internet Services in Ubiquitous Computing, IEEE, 2013.
[21] J. e. a. Jin, "An information framework for creating a smart city through internet
of things," IEEE Internet of Things journal, vol. 1, no. 2, pp. 112-121, 2014.
[22] R. e. a. Khan, "Future internet: the internet of things architecture, possible
applications and key challenges," in 2012 10th international conference on
frontiers of information technology, IEEE, 2012.
[23] M. R. M. I. M. a. A. N. H. Kassim, "Wireless Sensor Network in precision
agriculture application," in 2014 International Conference on Computer,
Information and Telecommunication Systems (CITS), IEEE, 2014.
[24] "http://camnangcaytrong.com/ky-thuat-canh-tac-cay-bap-cai-nd366.html,"
[Online].
[25] [Online]. Available: http://www.lamdong.gov.vn/vi-VN/a/donduong/ky-
thuat/Pages/TrongXaLach.aspx.
[26] [Online]. Available: http://camnangcaytrong.com/ky-thuat-trong-va-cham-soc-
cay-xa-lach-nd725.html.
[27] [Online]. Available: http://tiennong.vn/u7/cay-ho-tieu.aspx.
[28] [Online]. Available: http://lamnong.net/mat-do-trong-tieu/.
[29] [Online]. Available: http://camnangcaytrong.com/xac-dinh-mat-do-trong-mia-
nd202.html.
[30] S. B. a. D. H. G. Saraf, " IoT based smart irrigation monitoring and controlling
system," in 2017 2nd IEEE International Conference on Recent Trends in
Electronics, Information & Communication Technology (RTEICT), IEEE, 2017.
[31] T. D. a. C. C. S. Stieber, "Placement of soil moisture sensors in sprinkler irrigated
potatoes," American Potato Journal, vol. 72, no. 9, pp. 533-543, 1995.
[32] M. a. S. O. Dursun, "A wireless application of drip irrigation automation
supported by soil moisture sensors," Scientific Research and Essays, vol. 6, no. 7,
pp. 1573-1582, 2011.
[33] K. L. e. a. Krishna, "Internet of Things application for implementation of smart
agriculture system," in 2017 International Conference on I-SMAC (IoT in Social,
Mobile, Analytics and Cloud)(I-SMAC), IEEE, 2017.

67
[34] A. Z. N. I. a. Z. A. S. Abbasi, "A review of wireless sensors and networks'
applications in agriculture," Computer Standards & Interfaces, vol. 36, no. 2, pp.
263-270, 2014.
[35] [Online]. Available: https://www.irrigationtutorials.com/drip-irrigation-design-
guidelines-basics-of-measurements-parts-and-more/.

68
APPENDIX
Code of SU

#include <DHT.h>

#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>

//#define DHTPIN 2 //D4

int RH;

const int DHTPIN = 2;

const int DHTTYPE = DHT11;

DHT dht(DHTPIN, DHTTYPE);

// AP Wi-Fi credentials

const char* ssid = "server";

const char* password = "123456789";

// Local ESP web-server address

String serverHost = "http://192.168.4.1/feed";

String data;

int sleepInterval = 5;

// DEEP_SLEEP Timeout interval when connecting to AP fails

int failConnectRetryInterval = 2;

int counter = 0;

int h;

int t;

// Static network configuration

69
IPAddress ip(192, 168, 4, 4);

IPAddress gateway(192, 168, 4, 1);

IPAddress subnet(255, 255, 255, 0);

WiFiClient client;

void setup() {

ESP.eraseConfig();

WiFi.persistent(false);

Serial.begin(115200);

dht.begin();

delay(500);

WiFi.mode(WIFI_STA);

WiFi.config(ip, gateway, subnet);

WiFi.begin(ssid, password);

Serial.println("");

while (WiFi.status() != WL_CONNECTED) {

if (counter > 20) {

Serial.println("- can't connect, going to sleep");

hibernate(failConnectRetryInterval);

delay(500);

Serial.print(".");

counter++;

}
70
void sendHttpRequest() {

HTTPClient http;

http.begin(serverHost);

http.addHeader("Content-Type", "application/x-www-form-urlencoded");

http.POST(data);

String payload = http.getString();

Serial.println(payload);

http.end();

void readDHTSensor() {

delay(200);

h = dht.readHumidity();

t = dht.readTemperature();

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

t = 0.00;

h = 0.00;

Serial.println("- temperature read : " + String(t));

Serial.println("- humidity read : " + String(h));

void readRHsensor() {

RH = analogRead(A0);

RH = map(RH,0,1023,0,100);

if (isnan(RH)) {
71
RH = 0.00;

Serial.println("- Humidity value: " + String(RH));

void buildDataStream() {

data = "temp=";

data += String(t);

data += "&hum=";

data += String(h);

data += "&moist=";

data += String(RH);

void hibernate(int pInterval) {

WiFi.disconnect();

ESP.deepSleep(10 * 600000 * pInterval, WAKE_RFCAL);

delay(100);

void loop() {

readDHTSensor();

delay(10);

readRHsensor();

delay(10);

buildDataStream();

delay(500);
72
sendHttpRequest();

delay(5000);

ESP.reset();

Code of BSU

#include <ESP8266WiFi.h>

//#include <WiFiServer.h>

#include <ESP8266WebServer.h>

#include <ServerHIP.h>

#include <LiquidCrystal_I2C.h>

#include <Wire.h>;

LiquidCrystal_I2C lcd(0x27,16,2);

int R;

//const int channelID = 594402;

String writeAPIKey = "LZ8MAP5C43Q3VYBP";

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

const int postingInterval = 5 * 1000;

// Internet router credentials

const char* ssid = "server";

const char* password = "123456789";

#define wfid "GiangTran" // id wifi

#define pass "123456789" // pass wf


73
ESP8266WebServer server(80);

void setup() {

Serial.begin(115200);

WiFi.mode(WIFI_AP_STA);

setupAccessPoint();

WiFi.begin(wfid, pass);

while (WiFi.status() != WL_CONNECTED) {

Serial.print(".");

delay(200);

ConnectSV();

lcd.begin(16,2);

lcd.init();

lcd.backlight();

lcd.setCursor(0, 0);

lcd.print("Starting program");

lcd.setCursor(0,1);

lcd.print("----------");

lcd.clear();

// Handling the / root web page from my server

void handle_index() {

server.send(200, "text/plain", "welcome");

}
74
String t;

String h;

String RH;

// Handling the /feed page from my server

void handle_feed() {

t = server.arg("temp");

h = server.arg("hum");

RH = server.arg("moist");

float s = float(RH.toInt());

server.send(200, "text/plain", String(t) + String(h) + String(s));

Serial.println("Temperature: " + String(t));

Serial.println("Humidity: " + String(h));

Serial.println("Soil moisture: " + String(s));

setupStMode(t, h, RH);

delay(500);

if (s <= 70) {

R = 0;

else {

R = 1;

void send_data() {

SetFloat("/iot/control", R);
75
}

void setupAccessPoint() {

Serial.println("** SETUP ACCESS POINT **");

Serial.println("- disconnect from any other modes");

WiFi.disconnect();

Serial.println("- start ap with SID: " + String(ssid));

WiFi.softAP(ssid, password);

IPAddress myIP = WiFi.softAPIP();

Serial.print("- AP IP address is :");

Serial.print(myIP);

setupServer();

void setupServer() {

Serial.println("** SETUP SERVER **");

Serial.println("- starting server :");

server.on("/", handle_index);

server.on("/feed", handle_feed);

server.on("/getdata", send_data);

server.begin();

};

void setupStMode(String t, String v, String m){

WiFiClient client;

Serial.println("- connecting to Database server: " + String(logServer));

delay(2000);
76
if (client.connect(logServer, 80)) {

Serial.println("- succesfully connected");

String postStr = writeAPIKey;

postStr += "&field1=";

postStr += String(t);

postStr += "&field2=";

postStr += String(v);

postStr += "&field3=";

postStr += String(m);

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

Serial.println("- sending data...");

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

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

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

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

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

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

client.print(postStr.length());

client.print("\n\n");

client.print(postStr);

client.stop();

void loop() {
77
server.handleClient();

send_data();

setupStMode(t, h, RH);

lcd.setCursor(0, 0);

lcd.print("T="); // display temperature

lcd.print(String(t));

lcd.print("oC");

lcd.setCursor(8, 0);

lcd.print("H=");

lcd.print(String(h));

lcd.print("%");

lcd.setCursor(0, 1);

lcd.print("Moist=");

lcd.print(String(RH));

lcd.print("%");

delay(5000);

Code of VU

#include <ESP8266WiFi.h>

#include <ServerHIP.h>

#define WIFI_SSID "GiangTran"

#define WIFI_PASSWORD "123456789"

#define delay_time 5000


78
int Val_PIN = 2; //D4

void setup() {

Serial.begin(9600);

pinMode(Val_PIN, OUTPUT);

// connect to wifi.

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

Serial.print("connecting");

while (WiFi.status() != WL_CONNECTED) {

Serial.print(".");

delay(500);

Serial.println();

Serial.print("connected: ");

Serial.println(WiFi.localIP());

ConnectSV();

void loop() {

if (GetFloat("/iot/control") == 0) {

digitalWrite(Val_PIN, LOW);

} else {

digitalWrite(Val_PIN, HIGH);

delay(delay_time);

}
79
80

Вам также может понравиться