+ All Categories
Home > Technology > Agricultural environment control system using wireless sensor networks

Agricultural environment control system using wireless sensor networks

Date post: 17-Aug-2015
Category:
Upload: ahmed-fawzy
View: 57 times
Download: 1 times
Share this document with a friend
Popular Tags:
94
Agricultural environment Control system using WSNs Mansoura University Faculty of Computers and information Systems Dept. Information Technology Agricultural environment control system using Wireless sensor networks Supervised By Dr. Eman Mohamed Dr. Noha Fayed Dr.Mohammed Azzam Department of Information Technology Faculty of Computers and information systems -Mansoura University 2014-2015
Transcript
Page 1: Agricultural environment control system using wireless sensor networks

Acknowledgement

Agricultural

environment Control

system using WSNs

Mansoura University

Faculty of Computers and information

Systems

Dept. Information Technology

Ag

ricu

ltu

ral

en

vir

on

me

nt

con

tro

l sy

ste

m u

sin

g W

ire

less

se

nso

r n

etw

ork

s

Supervised By

Dr. Eman Mohamed

Dr. Noha Fayed

Dr.Mohammed Azzam

Department of Information Technology

Faculty of Computers and information systems -Mansoura University

2014-2015

Page 2: Agricultural environment control system using wireless sensor networks

1

Mansoura University

Faculty of computers and information

Systems.

Dept. Information Technology

Agricultural

environment Control

system using WSNs

Supervised By

Dr. Eman Mohamed

Dr. Noha Fayed

Dr.Mohammed Azzam

Department of Information Technology

Faculty of Computers and information systems -Mansoura University

2014-2015

Page 3: Agricultural environment control system using wireless sensor networks

2

Team Work

No. Name contact

1 Abdul-aziz mohammed Al-adwi [email protected] 2 Ahmed Fawzy El-Bhay a7hmed31 @gmail.com 3 Mohamed Ragab Shaaban. [email protected] 4 Yomna Alaa Eladl [email protected] 5 Maha Eltantawy Eita [email protected] 6 Radwah Mahmoud omar [email protected]

Page 4: Agricultural environment control system using wireless sensor networks

Acknowledgement

Acknowledgement

We would like to express our gratitude to our advisor and

supervisor Dr. Eman Mohamed for guiding this work with interest.

We would like to also thank Eng. Noha Fayed and Mohammed

Azzam Teaching Assistance for the countless hours they spent with

us. We are grateful to them for setting high standards and giving us

the freedom to explore. We would like to thank our colleagues for

the assistance and constant support provided by them.

Our Team

Page 5: Agricultural environment control system using wireless sensor networks

1

Abstract

The availability of smarter, smaller and inexpensive sensors measuring a

wider range of environmental parameters has enabled continuous timed

monitoring of the environment and real-time applications. This was not

possible earlier when monitoring was based on water sample collection and

laboratory analyses or on automatic sensors wired to field loggers requiring

manual data downloading. During the previous decade, environmental

monitoring has developed from offline sensors to real time, operational sensor

networks and to open Sensor Webs. Sensor networks are used for collecting,

storing and sharing the sensed data. They can also be defined as a system

comprised of a set of sensor nodes and a communication system that allows

automatic data collection and sharing. They allow monitoring remote,

hazardous, dangerous or unwired areas, for example in the monitoring and

warning systems for tsunamis, volcanoes, or seismologic phenomena.

Precision agriculture can be defined as the art and science of using

advanced technology to enhance crop production.

Wireless sensor network is a major technology that drives

the development of precision agriculture. The science and engineering

questions associated with precision agriculture center around increasing the

efficiency to prosper in a sustainable manner. Increases in agricultural

efficiency will stem from networking sensors to elucidate important

spatiotemporal patterns and integrating their data streams so as to not only

display or record information, but to actuate human and autonomous

responses. Remote sensing can direct the farmer’s efforts toward crop zones in need

of water, nutrients or other attention. This information can increase farming

efficiency providing the farmer receives it in a timely manner and has the

capacity to act on it. Development of a wider array of such devices would

greatly benefit the agricultural sector.

Page 6: Agricultural environment control system using wireless sensor networks

2

Contents Chapter-01 Introduction.....................................................................................................4

1.1 Problem Definition…….………....……………………..…..……..….……………………………….5 1.2 Problem Solution …………………………………………………………………………………..………………….5 1.3 Business Model ……………………………………...…………………….……………………...………………… 5 1.4 Block Diagram ………………………………………...………………………..………….….....…………………. 6 1.5 Detailed Technical description …………………………………...………………………..…………………. 7

Chapter-02: Arduino and sensor nodes………………………………………….…….........…..……..……..…………………..6 2.1 | Arduino:-

2.1.1 What's on the board?........................................................................................................ 11 2.2 | Wireless sensor nodes......................................................................................................... 15

2.4.1 ETap liquid level sensor..........................................................................................................15 2.4.2 Moisture Sensor.....................................................................................................................17 2.4.3 DHT11 Humidity & Temperature Sensor................................................................................19 2.4.4 The Grove - Gas Sensor (MQ2)...............................................................................................21

2.3 Solar Panel..............................................................................................................................25

2.4 Battery....................................................................................................................................27 Chapter-03: Wireless transceiver IC....................................................................................................28

3.1 Introduction to NRF24L01.........................................................................................................29 3.2 NRF24L01 features....................................................................................................................29 3.3 connection between NRF24L01 and Arduino ...........................................................................31 3.4 connection to sensors in the same node...................................................................................34 3.5 How many nodes connected among each other.......................................................................27 3.6 Building WSN ........................................................................................................................... 38 3.7 payload details..........................................................................................................................39 3.8 deployment...............................................................................................................................40 3.9 setting the sleep interval ..........................................................................................................41 3.10 protocols and control of NRF24L01 ........................................................................................41 3.11 problems that faces the system .............................................................................................47

Chapter-04: Software and implementation ........................................................................................48 4.1 Software tools ..........................................................................................................................49 4.2 Control system GUI ............................................................................................................49

4.2.1 Configuration subsystem.................................................................................................49 4.2.2 Monitoring subsystem ....................................................................................................50 4.2.3 Alert subsystem...............................................................................................................52 4.2.4 Decision subsystem .........................................................................................................54

Chapter-05: system security ...............................................................................................................56 5.1 Implementation of security.....................................................................................................57 5.2 Log files....................................................................................................................................58

Appendix............................................................................................................................................60

Page 7: Agricultural environment control system using wireless sensor networks

3

List of figures

Figure Title page number

Fig 1.1 ..........................“System architecture”.......................................................................................6

Fig 1.2.......................... “Sequence diagram for collecting and sensing data”..........................................8

Fig 1.3 ..........................“Entire overview of sensor”...............................................................................9

Fig 2.1 ..........................“Arduino board”..............................................................................................12

Fig 2.2.1........................”eTape liquid level sensor”............................................................................15

Fig 2.2.2 ........................“moisture sensor” ........................................................................................18

Fig 2.2.3....................... “DH11 humidity and temperature sensor”.....................................................20

Fig 2.2.4........................“Gas sensor” .................................................................................................21

Fig 2.3 ..........................“Solar panel”.................................................................................................26

Fig 2.4...........................”Battery” ......................................................................................................27

Fig 3.1........................... “Wireless transceiver”..................................................................................31

Fig 3.3 ...........................“connect wireless to Arduino” ......................................................................32

Fig 3.5........................... “Connections between nodes” .....................................................................38

Fig 4.2.1........................ “GUI configuration system”..........................................................................50

Fig 4.2.2.1..................... “Basic monitoring mode”............................................................................51

Fig 4.2.2.2 .....................“Advanced monitoring mode”.......................................................................52

Fig 4.2.2.3 .....................“Alert subsystem”.........................................................................................53

Fig 4.2.2.4 ....................“Decision subsystem”.....................................................................................54

Page 8: Agricultural environment control system using wireless sensor networks

4

Page 9: Agricultural environment control system using wireless sensor networks

5

1.1 | PROBLEM DEFINITION

Agriculture is considered one of the main vital factors to human beings.

We are at the age of Technology. Technology became everything at everything

we can see in our life.

From this point came the challenge about applying technology at Agriculture to control

the agricultural environment system using piece of advanced technology.

Applying these Agricultural technology has more and more benefits for

humans, countries and farmers. It saves effort and time that farmer may need.

It also contribute to increase crop production as you will control the whole

farming system with technology.

1.2 | PROBLEM SOLUTION

Earlier monitoring was based on water sample collection and

laboratory analyses or on automatic sensors wired to field loggers requiring

manual data downloading. During the previous decade, environmental

monitoring has developed from offline sensors to real time, operational

sensor networks and to open Sensor Webs. Sensor networks are used for

collecting, storing and sharing the sensed data.

They can also be defined as a system comprised of a set of sensor nodes and a

communication system that allows automatic data collection and sharing.

They allow monitoring remote, hazardous, dangerous or unwired areas, for example in

the monitoring and warning systems for tsunamis, volcanoes, or seismologic

phenomena.

1.3 | BUSINESS MODEL

our customers are farmers who are in dead need for some technology to help

them at the farming system.

Our product would cover some needs of our customers as helping them to control

Page 10: Agricultural environment control system using wireless sensor networks

6

their work in some technological manner. Providing them with some scientific

information to help them take right decisions.

Our system will also provide them with climate conditions such as temperature,

Humidity, Moisture and the level of water at the soil.

To reach our goal we met with different farmers to know exactly what they need and help

us to get a vision for our final product to be familiar with them and

also we were guided technically by our sponsors to find the best way to cover all

these needs.

In our market the available products doesn't cover all needs we just found some

products but they were complex and expensive for traditional farmer.

1.4 | BLOCK DIAGRAMS

This is the physical view for our system.

Our system depends on the client/server system criteria. Client is the user and

direct connected components with him. Server is components that lands in the farm

that will collect information and send it to user at control room.

Fig. (1.1): System Architecture.

Page 11: Agricultural environment control system using wireless sensor networks

7

1.5 | DETAILED TECHNICAL DESCRIPTION.

Our project was built on the simplest available technologies to reach our goal

in the way that comfort the user so we divided our project into 2 parts software and

hardware.

The hardware part consists of two Arduino boards’ acts as one for client part

and the other for the server.

At the Client we can find user control room and wireless transceiver module

combined to the board.

At server side we can find sensors such as temperature sensor that will get

data about climate change, Humidity sensor, moisture sensor, water level sensor,

light sensor and gas sensor.

All of the previous are settled on the board that get its power from a

chargeable battery.

The software part is windows application available to be installed on any pc.

In the hardware part there're 2 parts for it client and server.

At the server, sensors can gather information from the surround environment then

sensors will send data to sensor manager known as the Arduino board that will

analysis them and convert them to data format.

Data will be stored at sensor external memory then the transceiver wireless module

can interact with sensor and asks for data which will be sent by sensor if it is.

Wireless transceiver can send data through the channel built between the other

transceiver at client side.

Data reached to the client can be managed by user connected with the board through

the GUI which is a windows forms application.

Sensor major work depends on the Micro-Controller chip that is a middle

part between its external memory and the transceiver. (See fig 1.2)

Page 12: Agricultural environment control system using wireless sensor networks

8

The controller performs tasks, processes data and controls the functionality of

other components in the sensor node.

Fig. (1.2): Sequence diagram for collecting and sending data

A microcontroller is often used in many embedded systems such as sensor

nodes because of its low cost, flexibility to connect to other devices, ease of

programming, and low power consumption.

Transceiver Sensor nodes often make use of ISM band, which gives free

radio, spectrum allocation and global availability. The possible choices of

wireless transmission media are radio frequency (RF), optical communication

(laser) and infrared. Lasers require less energy.

External memory From an energy perspective, the most relevant kinds of

memory are the on chip memory of a microcontroller and Flash memory—off

chip RAM is rarely, if ever, used. Flash memories are used due to their cost and

storage capacity.

Memory requirements are very much application dependent. Two

categories of memory based on the purpose of storage are: user memory used

Page 13: Agricultural environment control system using wireless sensor networks

9

for storing application related or personal data, and program memory used for

programming the device. Program memory also contains identification data of

the device if present.

A wireless sensor node is a popular solution when it is difficult or

impossible to run a mains supply to the sensor node. However, since the

wireless sensor node is often placed in a hard to reach location, changing the

battery regularly can be costly and inconvenient.

An important aspect in the development of a wireless sensor node is

ensuring that there is always adequate energy available to power the system.

The sensor node consumes power for sensing, communicating and data

processing. More energy is required for data communication than any other

process.

The energy cost of transmitting 1 Kb a distance of 100 meters (330 ft) is

approximately the same as that used for the execution of 3 million instructions

by a 100 million instructions per second/W processor.

Power is stored either in batteries or capacitors. Batteries, both rechargeable and

non-rechargeable, are the main source of power supply for sensor nodes.

Fig. (1.3): Entire overview of sensor

node.

Page 14: Agricultural environment control system using wireless sensor networks

10

Page 15: Agricultural environment control system using wireless sensor networks

11

2.1| Arduino

Arduino is an open-source platform used for building electronics projects.

Arduino consists of both a physical programmable circuit board (often referred

to as a microcontroller and a piece of software, or IDE (Integrated

Development Environment) that runs on your computer, used to write and

upload computer code to the physical board.

The Arduino platform has become quite popular with people just starting out

with electronics, and for good reason. Unlike most previous programmable

circuit boards, the Arduino does not need a separate piece of hardware (called

a programmer) in order to load new code onto the board – you can simply use

a USB cable.

Additionally, the Arduino IDE uses a simplified version of C++, making it

easier to learn to program. Finally, Arduino provides a standard form factor

that breaks out the functions of the micro-controller into a more accessible

package.

2.1.1 | What's on the board?

There are many varieties of Arduino boards that can be used for different

purposes. Some boards look a bit different from the one below, but most

Arduinos have the majority of these components in common:

Page 16: Agricultural environment control system using wireless sensor networks

12

1- Power (USB / Barrel Jack) Every Arduino board needs a way to be connected to a power source. The

Arduino UNO can be powered from a USB cable coming from your computer

or a wall power supply that is terminated in a barrel jack. In the picture above

the USB connection is labeled (1) and the barrel jack is labeled (2).

The USB connection is also how you will load code onto your Arduino board.

NOTE: Do NOT use a power supply greater than 20 Volts as you will

overpower (and thereby destroy) Arduino.

The recommended voltage for most Arduino models is between 6 and 12

Volts.

Page 17: Agricultural environment control system using wireless sensor networks

13

2- Pins (5V, 3.3V, GND, Analog, Digital, PWM, AREF)

The pins on your Arduino are the places where you connect wires to construct

a circuit (probably in conjunction with a breadboard and some wire.

They usually have black plastic ‘headers’ that allow you to just plug a wire

right into the board.

The Arduino has several different kinds of pins, each of which is labeled on the

board and used for different functions.

GND (3): Short for ‘Ground’. There are several GND pins on the

Arduino, any of which can be used to ground your circuit.

5V (4) & 3.3V (5): As you might guess, the 5V pin supplies 5 volts of

power, and the 3.3V pin supplies 3.3 volts of power. Most of the simple

components used with the Arduino run happily off of 5 or 3.3 volts.

Analog (6): The area of pins under the ‘Analog In’ label (A0 through A5

on the UNO) are Analog In pins. These pins can read the signal from an

analog sensor (like a temperature sensor) and convert it into a digital

value that we can read.

Digital (7): Across from the analog pins are the digital pins (0 through

13 on the UNO). These pins can be used for both digital input (like

telling if a button is pushed) and digital output (like powering an LED).

PWM (8): You may have noticed the tilde (~) next to some of the digital

pins (3, 5, 6, 9, 10, and 11 on the UNO). These pins act as normal digital

pins, but can also be used for something called Pulse-Width Modulation

(PWM).

Page 18: Agricultural environment control system using wireless sensor networks

14

AREF (9): Stands for Analog Reference. Most of the time you can leave

this pin alone. It is sometimes used to set an external reference voltage

(between 0 and 5 Volts) as the upper limit for the analog input pins.

3- Reset Button

Arduino has a reset button (10). Pushing it will temporarily connect the reset

pin to ground and restart any code that is loaded on the Arduino. This can be

very useful if your code doesn’t repeat, but you want to test it multiple times.

Unlike the original Nintendo however, blowing on the Arduino doesn’t

usually fix any problems.

4- Power LED Indicator

Just beneath and to the right of the word “UNO” on your circuit board, there’s

a tiny LED next to the word ‘ON’ (11). This LED should light up whenever

you plug your Arduino into a power source. If this light doesn’t turn on,

there’s a good chance something is wrong. Time to re-check your circuit!

5- TX RX LEDs

TX is short for transmit, RX is short for receive. These markings appear quite a

bit in electronics to indicate the pins responsible for serial connection. In our

case, there are two places on the Arduino UNO where TX and RX appear –

once by digital pins 0 and 1, and a second time next to the TX and RX

indicator LEDs (12). These LEDs will give us some nice visual indications

whenever our Arduino is receiving or transmitting data (like when we’re

loading a new program onto the board).

Page 19: Agricultural environment control system using wireless sensor networks

15

6- Voltage Regulator

The voltage regulator (14) is not actually something you can (or should) interact

with on the Arduino. But it is potentially useful to know that it is there and what

it’s for. The voltage regulator does exactly what it says – it controls the amount of

voltage that is let into the Arduino board. Think of it as a kind of gatekeeper; it

will turn away an extra voltage that might harm the circuit. Of course, it has its

limits, so don’t hook up your Arduino to anything greater than 20 volts.

2.2| Wireless sensor nodes.

2.2.1 | ETap liquid level sensor Description

The eTape sensor is a solid state, continuous (multi-level) fluid level sensor for

measuring levels in water, non-corrosive water based liquids and dry fluids

(powders). The eTape sensor is manufactured using printed electronic

technologies which employ additive direct printing processes to produce

functional circuits.

Theory of operation

The eTape sensor's envelope is compressed by hydrostatic pressure of the fluid in

which it is immersed resulting in a change in resistance which corresponds to the

Page 20: Agricultural environment control system using wireless sensor networks

16

distance from the top of the sensor to the fluid surface. The eTape sensor provides

a resistive output that is inversely proportional to the level of the liquid: the lower

the liquid level, the higher the output resistance; the higher the liquid level, the

lower the output resistance.

Specifications

Sensor Length: 14.1" (358 mm) resolution: < 0.01“(0.25 mm)

Thickness: 0.015" (0.381mm) actuation depth: Nominal 1” (25.4 mm)

Width: 1.0" (25.4 mm) Reference Resistor (Rref): 2250, ±10%

Active Sensor Length: 12.4" (315 mm) Connector: Crimp flex

Pins

Sensor Output: 2250 empty, 400 full, ±10%

Temperature Range: 15°F - 150°F (-9°C - 65°C)

Resistance Gradient: 150 /inch (59/cm), ±10%

Power Rating: 0.5 Watts (VMax = 10V)

Connection and Installation

Connect to the eTape by attaching a 4 pin connector with pre-soldered wires to

the Crimp flex pins. Do not solder directly to the Crimp flex pins.

The inner two pins (pins 2 and 3) are the sensor output (Rsense).

The outer pins (pins 1 and 4) are the reference resistor (Rref) which can be used

for temperature compensation.

Suspend the eTape sensor in the fluid to be measured. To work properly the

sensor must remain straight and must not be bent vertically or longitudinally.

For best results install the sensor inside a section of 1-inch diameter PVC pipe.

Double sided adhesive tape may be applied to the upper back portion of the

Page 21: Agricultural environment control system using wireless sensor networks

17

sensor to suspend the sensor in the container to be measured. However, the liquid

must be allowed to interact freely with both sides of the sensor.

The vent hole located above the max line allows the eTape to equilibrate with

atmospheric pressure. The vent hole is fitted with a hydrophobic filter membrane

to prevent the eTape from being swamped if inadvertently submerged.

2.2.2 | Moisture Sensor

Description

The moisture sensor can read the amount of moisture present in the soil

surrounding it, it’s a low tech sensor but ideal for monitoring an urban garden or

your pet plant’s water level.

It 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 , the can be very

to use , just insert it into the soil and read it. With help of this sensor, it will be

realizable to make the plant remind you: hey I am thirsty now give me some

water.

Page 22: Agricultural environment control system using wireless sensor networks

18

The moisture sensor uses the two probes to pass the current through the soil and

then it reads that resistant to get the moisture level, more water makes the soil

conduct electricity more easy ( less resistance), while dry soil conduct electricity

poorly (more resistance).

This item has low power consumption and high sensitivity which are the biggest

characteristics of this module.

This item can be compatible with Arduino uno, Arduino mega2560, Arduino

ADK.

Features

Working voltage: 5 volt Working current<20 ma

Interface: analog Depth of detection:

37mm

Page 23: Agricultural environment control system using wireless sensor networks

19

Working temperature: 10C~30C Weight:

3g

Size: 63*20*8 mm Arduino compatible interface

Low power consumption High sensitivity

Pin definition

“S” stands for signal input

“+” stands for power supply

“-” stands for GND (ground)

2.2.3 | DHT11 Humidity & Temperature Sensor

DHT11 Temperature & Humidity Sensor features a temperature & humidity

sensor complex with a calibrated digital signal output. By using the exclusive

digital-signal-acquisition technique and temperature & humidity sensing

technology, it ensures high reliability and excellent long-term stability. This

sensor includes a resistive-type humidity measurement component and an NTC

temperature measurement component, and connects to a high-performance 8-bit

microcontroller, offering excellent quality, fast response, anti-interference ability

and cost-effectiveness.

DHT11’s power supply is 3-5.5V DC. When power is supplied to the sensor, do

not send any instruction to the sensor in within one second in order to pass the

unstable status. One capacitor valued 100nF can be added between VDD and

GND for power filtering.

Page 24: Agricultural environment control system using wireless sensor networks

20

Power and Pin

DHT11’s power supply is 3-5.5V DC. When power is supplied to the sensor, do

not send any instruction to the sensor in within one second in order to pass the

unstable status. One capacitor valued 100nF can be added between VDD and

GND for power filtering.

Communication Process: Serial Interface (Single-Wire Two-Way)

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

40bit, and the sensor sends higher data bit first.

Page 25: Agricultural environment control system using wireless sensor networks

21

Data format: 8-bit integral RH data + 8-bit decimal RH data + 8-bit integral T

data + 8-bit decimal T data + 8-bit check sum.

If the data transmission is right, the check-sum should be the last 8-bit of "8-bit

integral RH data + 8-bit decimal RH data + 8-bit integral T data + 8-bit decimal

T data".

2.2.4 | The Grove - Gas Sensor (MQ2)

The Grove - Gas Sensor(MQ2) module is useful for gas leakage detecting(in home and

industry). It can detect H2, LPG, CH4, CO, Alcohol, Smoke, Propane. Based on its fast

response time. Measurements can be taken as soon as possible. Also the sensitivity can be

adjusted by the potentiometer.

Features

Wide detecting scope

Stable and long life

Fast response and High sensitivity

Page 26: Agricultural environment control system using wireless sensor networks

22

Application Ideas

Gas leakage detecting

Toys

Mechanic Dimensions

Electronic Characteristics

Items Parameter name Min Type Max Unit

System Characteristics

VCC Working Voltage 4.9 5 5.1 V

PH Heating consumption 0.5 - 800 mW

RL Load resistance can adjust

RH Heater resistance - 33 - Ω

Rs Sensing Resistance 3 - 30 kΩ

2.2.4.1 | Hardware Installation

Grove products have an eco system and all have a same connector which can

plug onto the Base Shield. Connect this module to the A0 port of Base Shield,

however, you can also connect Gas sensor to Arduino without Base Shield by

jumper wires.

ARDUINO UNO GAS SENSOR

5V VCC

GND GND

NC NC

Page 27: Agricultural environment control system using wireless sensor networks

23

ANALOG A0 SIG

You can gain the present voltage through the SIG pin of sensor. The higher the

concentration of the gas, the bigger the output voltage of the SIG pin.

Sensitivity can be regulated by rotating the potentiometer. Please note the best

preheat time of the sensor is above 24 hours. For the detailed information

about the MQ-2 sensor please refer to the datasheet.

How to use

There're two steps you need to do before getting the concentration of gas.

First, connect the module with Grove Shield using A0 like the picture above.

And put the sensor in a clear air and use the program below.

void setup() {

Serial.begin(9600);

Page 28: Agricultural environment control system using wireless sensor networks

24

}

void loop() {

float sensor_volt;

float RS_air; // Get the value of RS via in a clear air

float R0; // Get the value of R0 via in H2

float sensorValue;

/*--- Get a average data by testing 100 times ---*/

for(int x = 0 ; x < 100 ; x++)

{

sensorValue = sensorValue + analogRead(A0);

}

sensorValue = sensorValue/100.0;

/*-----------------------------------------------*/

sensor_volt = sensorValue/1024*5.0;

RS_air = (5.0-sensor_volt)/sensor_volt; // omit *RL

R0 = RS_air/10.0; // The ratio of RS/R0 is 10 in a clear air

Serial.print("sensor_volt = ");

Serial.print(sensor_volt);

Serial.println("V");

Serial.print("R0 = ");

Serial.println(R0);

delay(1000);

}

Then, open the monitor of Arduino IDE, you can see some data are printed,

write down the value of R0 and you need to use it in the following program.

During this step, you may pay a while time to test the value of R0.

Second, put the sensor in one gas where the environment you want to test in.

However, don't forget to replace the R0 below with value of R0 tested above

void setup() {

Serial.begin(9600);

}

void loop() {

Page 29: Agricultural environment control system using wireless sensor networks

25

float sensor_volt;

float RS_gas; // Get value of RS in a GAS

float ratio; // Get ratio RS_GAS/RS_air

int sensorValue = analogRead(A0);

sensor_volt=(float)sensorValue/1024*5.0;

RS_gas = (5.0-sensor_volt)/sensor_volt; // omit *RL

/*-Replace the name "R0" with the value of R0 in the demo of

First Test -*/

ratio = RS_gas/R0; // ratio = RS/R0

/*------------------------------------------------------------

-----------*/

Serial.print("sensor_volt = ");

Serial.println(sensor_volt);

Serial.print("RS_ratio = ");

Serial.println(RS_gas);

Serial.print("Rs/R0 = ");

Serial.println(ratio);

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

delay(1000);

}

2.3 | Solar Panel This solar panel is made of single-crystal material that performs high solar

energy transformation efficiency at 17%. It has a fine resin surface and sturdy

back suitable for outdoor environments. A 2mm JST connecter is attached to

the penal, which makes it perfect to team up with most of our can-use-solar-

power-supply boards, like Seeeduino microcontroller series, Lipo Rider

charging boards seriesand XBee carrier WSN products series.

The typical open circuit voltage is around 5V, depending on light intensity. In

those bright summer days with clear sky and big sun, the peak OC voltage can

rush up to 10V. To prevent any damage to boards that accept a narrow range

Page 30: Agricultural environment control system using wireless sensor networks

26

of input voltage, like Lipo Rider, it’s recommended to check whether the OC

voltage is safe before any connection.

Features

Dimensions: 160x116x2.5(±0.2) mm

Typical voltage: 5.5V

Typical current: 450mA

Open-circuit voltage: 8.2 V

Maximum load voltage: 6.4V

Page 31: Agricultural environment control system using wireless sensor networks

27

2.4 | Battery.

We can use a chargeable battery for our project as a power source for

system.

Page 32: Agricultural environment control system using wireless sensor networks

28

Page 33: Agricultural environment control system using wireless sensor networks

29

3.1 | Introduction to nrf24L01:

This module uses the newest 2.4GHz transceiver with an embedded baseband

protocol engine from Nordic Semiconductor, suitable for ultra-low power

wireless application, the nRF24L01+. This transceiver IC operates in the

2.4GHz band and has many new features, version of the IC has improved

range, sensitivity, and data rates. The command set is backward compatible

with the original nRF24L01.

You can operate and configure nRF24L01+ through Serial Peripheral Interface

(SPI) the register map, which is accessible through SPI, contains all

configuration registers in nRF24L01 and is accessible in all operation modes of

the chip.

The embedded baseband protocol engine is based on packet communication

and support various modes from manual operations to advanced autonomous

protocol operation.

Radio front end uses GFSK modulation. It has user configurable parameter

like frequency channel, output power and air data rate.

3.2 | NRF 24L01 Features:

1-Radio:

Worldwide 2.4GHz ISM band operation.

126 RF channel.

Common RX and TX interface.

GFSK modulation.

250kbps, 1 and 2 Mbps air data rate.

1 MHz Non-overlapping channel spacing at 1Mbps.

Page 34: Agricultural environment control system using wireless sensor networks

30

2 MHz Non-overlapping channel spacing at 2 Mbps.

2-Transmitter:

Programmable output power: 0, -6, -12 or -18 dBm.

11.3 mA at 0dBm output power.

3-Reciver:

Fast AGC for improved dynamic range.

Integrated channel filters.

13.5 mA at 2Mbps.

-82dBm sensitivity at 2 Mbps.

-85dBm sensitivity at 1 Mbps.

-94dBm sensitivity at 250 kbps.

4-RF Synthesizer:

Fully integrated synthesizer.

No external loop filter. VCO varactor diode or resonator.

Accept low cost +- 60 ppm 16MHz crystal.

5-Enhanced ShockBrust:

1 to 32 byte dynamic payload length.

Automatic packet handling.

Auto packet transaction handling.

6 data pipe MultiCeiver for 1:6 star networks.

6-Power Management

Integrated voltage regulator.

1.9 to 3.6V supply range.

Idle modes with fast start-up times for advanced power management.

Page 35: Agricultural environment control system using wireless sensor networks

31

3.3 | Connection to Arduino:

Now, when we know nRF24L01 module pin-out we can now connect

nrf24L01 to Arduino or some other board. Just connect pins on the same

name on Arduino board and nRF24L01 wireless module:

Page 36: Agricultural environment control system using wireless sensor networks

32

Page 37: Agricultural environment control system using wireless sensor networks

33

SPI signals are in the ICSP connector. For connecting we suggest using

female/female jumper wires (type FF). The rest of the signals can be connected

using a female/male jumper wires (type FM).

Connect power pins from nRFto Arduino as shown below:

nRF24L01 Arduino Description

GND GND GND

VCC 3.3 V Power

CSN 7 Chip Select Not

CE 8 Control RX/TX

MOSI 11 Master Output

MISO 12 Master Input

SCK 13 Serial Clock

CE and CSN pins can be connected to any digital pins. Then in RF24 library, you

can specify which pins you used.

In our Project we will divided communication into two parts

Communication between sensors and nRF24L01 at the same node.

Communication among nodes.

And so on until data sent completely to Sink.

Page 38: Agricultural environment control system using wireless sensor networks

34

3.4 | Connection to Sensors in the same node:

RF24Network is a network layer for Nordic nRF24L01+ radios running on

Arduino-compatible hardware. It’s goal is to have an alternative to Xbeeradios for

communication between Arduino units, It provides a host address space and

message routing for up to 6,000 nodes. The layer forms the background of a

capable and scalable Wireless Sensor Network system, at the same time, it makes

communication between even two nodes very simple.

Firstly, we need send all data of sensors which we have her to our wireless

modulation.

We have five sensors (Temperature &Humidity, Moisture Soil_PIN4, Water

Level_PIN5, Smoke_PIN2 and Light_PIN3) that give us almost six data read

within an array called (joystick [6]). That readings of our sensors should send to

and stored in modulation to send them in its turn to receiver, to do this we will be

create RF24radio at (CE_PIN, CSN_PIN).

This Rf24 radio will assign to send readings in a module that we will call it (Pipe).

The main goal of our Project here is that we need get reading of data continuously,

so we need a loop on data read of sensors to store like that

joystick[0] = analogRead(2); // smoke

joystick[1] = analogRead(3); // light

joystick[2]=analogRead(4); // moisture

joystick[3]=analogRead(5); // water level

joystick[4]=int(humidity); // humidity

joystick[5]=int(temperature); // temperature

Page 39: Agricultural environment control system using wireless sensor networks

35

Now, we need to check if data that modulation (Transmitter) received is

correct or there is any loss in data sent, So we make a condition that will

have size of array that hold data with symbols for each reading and then

compare it to size of data sent when read it, if size of array is the same and

there is no any loss of reading or any error the modulation start its

communication to other-side part at receiver.

The receiver must know serial port of node that will be receive data from it,

so the sender will send its serial port to receiver to receive data by way and

Protocols we will take about it later in this chapter. Then modulation

(Receiver) will send data by turn to Windows Application for monitoring it

to user.

To make all of this to happen we need first some libraries

/* ---(Import need libraries )---*\

#include <SPI.h>

#include <nRF24L01.h>

#include <RF24.h>

That kinds of libraries we talk about above that used and help to set

channel.

Then we need to Declare Constants and Pin Numbers, then object and

variable after that...

Page 40: Agricultural environment control system using wireless sensor networks

36

/*---(Declare Constant and Pin Numbers)---*\

#define CE_PIN 7 ///7 9

#define CSN_PIN 8 /// 8 10

#define led 6

/*---(Declare Object)---*\

RF24 radio (CE_PIN , CSN_PIN); //Create Radio

/*---(Declare Variable)---*\

Int joystick[6]; // 3 element array holding Joystick readings

Then we need give Serial Number to receiver

Serial.begin(9600);

//Serial.println("nRf24L01 Receiver starting");

radio.begin();

radio.openReadingPipe(1,pipe);

radio.startListening();

pinMode(led,OUTPUT);

digitalWrite(led,HIGH);

delay(1000);

digitalWrite(led,LOW);

delay(1000);

At the end Receiver will check if data receive is true and completely or there

is any error or loss

Page 41: Agricultural environment control system using wireless sensor networks

37

Void loop() /****LOOP:RUNS CONSTANTLY****\

{

If (radio.avalible())

{

digitalWrite(led,HIGH);

//Read data payload until we've received anything

Bool done = true;

If (done == true){

//Fetch data payload

Done = radio.read(joystick , sizeof(joystick));

Serial.print(joystick[0]); }

And so on until receive all data.

Else that the array will contain all data with Zeros that sign to there are an

error must recover.

3.5 | How many Nodes connect among each other:

RF24Network works great with a few nodes, Nodes are automatically

configured in a tree topology, according to their node address. Nodes can

Page 42: Agricultural environment control system using wireless sensor networks

38

only directly communicate with their parent and their children. The

network will automatically send messages to the right place.

There will be a Node that act like a “base”, others nodes directly

communicate with base Node, but not with each other, so for two Nodes to

send a message to each other, it will travel through base Node.

Nodes that connected to one base nearby node consider a children for this

Node.

In practice, we have gotten in the habit of designating a “router “node,

using a high-power antenna, then all the nodes on that floor communicate

with the “Parent”.

Page 43: Agricultural environment control system using wireless sensor networks

39

3.6 | Building a Wireless Sensor Network:

The “sensor-net” is the place to start from when building out a network of

sensors. There we will demonstrates how to send a pair of sensor readings

back to the base from any number of nodes. Every node will send a ping to

the base every 4 seconds, which is a good interval for testing, while in

practice you’ll want a much longer interval. Leaf nodes will sleep in

between transmissions to conserve battery life.

3.7 | Payload Details:

RF24Network sends two pieces of information out on the wire in each

frame, a header and a message. The header is defined by the library, and

used to route frames to the correct place, and provide standard information.

This is defined in RF24Network.

/**

*Header which is sent with each message

*

*The frame put over the air consist of this heard and a message

*/

Struct RF2NetworkHeader

{

Uintl6_t from_node ; /**<Logical address where message was generated */

Uintl6_t to_node; /**<Logical address where message is going*/

Uintl6_t id; /**<Sequential message ID, incremented every message */

Unsigned char type ; /**<Type of the packet, 0-127 are user-defined types, 128-255 are

reserved for system */

Unsigned char reserved ; /**<Reserved from future use */

Page 44: Agricultural environment control system using wireless sensor networks

40

The message is application-defined, and the header keeps track of the TYPE

of message using a single character. So your application can have different

types of messages to transmit different kinds of information. For the sensor-

net, we’ll use only a type ‘S’ message, meaning “Sensor Data”.

This message is defined in the example, in S_message.h:

/**

*Sensor message (type ‘S’)

*/

StructS_message

{

Until6_t temp_reading;

Until6_t humid_reading;

S_message (void): temp_reading (0), humid_reading (0), counter (next_counter++) {}

Char*toString (void)

};

This simply contains a temperature and humidity reading.

3.8 | Deployment:

Put the sketch on every node. Start it first while connected to the serial port,

so you can give it an address:

RF24network/sensor-net/

PLATFORM: Getting Started Board

VERSION: ……

***No valid address found. Send node address via serial of the form

Page 45: Agricultural environment control system using wireless sensor networks

41

Once you get a bunch of them going, you’ll see the whole spew

3.9 | Setting the sleep interval:

Once it’s up and running, you can change the sleep interval to something

more rational. For production networks, I shoot for one reading from each

node every minute, which is probably overkill but it gives me some

flexibility because sometimes nodes have trouble reaching the base for

several minutes at a time. These are the values to adjust

//Sleep constants.

//every 4s, and every single wakeup we power up the radio and send

//a reading. In real use, these numbers which be much higher.

Constintsleep_cycles_per_transmission=1;

3.10 | Protocols & Control of nRF24L01:

1-PA Control:

The PA (Power Amplifier) control is used to set the output power from the

NRF24L01+ power amplifier.

In TX mode PA control has four Programmable steps.

This Table is RF output power setting for the nRF24L01

Page 46: Agricultural environment control system using wireless sensor networks

42

SPI RF_SETUP

(RF_PWR)

RF Output

Power

DC Current

Consumption

11 0 11.3mA

10 -6dBm 9.0mA

01 -12dBm 7.5mA

00 -18dBm 7.0mA

Conditions:

VDD= 3.0V, VSS= 0V, TA = 27ºC, Load impedance = 15Ω+j88Ω

2-RX/TX Control:

The RX/TX control is set by PRIM_RXbit in the CONFIG register and sets

the nRF24L01+ in transmit / receive mode.

Command:

1-SPI Command:

Command name Command word

(binary)

#Data Bytes Operations

R_REGISTER 000A AAAA 1 to 5 LSByte first Read command and

status Register ,

AAAAA=5 bit

register Map address

Page 47: Agricultural environment control system using wireless sensor networks

43

W_REGISTER 001A AAAA 1 to 5 LSByte first Write command and

status registers.

AAAAA = 5

bit Register Map

Address

Executable in power

down or standby

modes only.

R_RX_PAYLOAD 0110 0001 1 to 32 LSByte first Read RX-payload: 1

– 32 bytes.

A read operation

always starts at byte

0.

Payload is deleted

from FIFO after it is

read. Used in RX

mode.

W_TX_PAYLOAD 1010 0000 1 to 32 LSByte first Write TX-payload:

1 – 32 bytes.

A write operation

always starts at byte

0 used in TX

payload.

FLUSH_TX 1110 0001 0 Flush TX FIFO,

used in TX mode

FLUSH_RX 1110 00010 0 Flush RX FIFO,

used in RX mode

Should not be

Page 48: Agricultural environment control system using wireless sensor networks

44

executed during

transmission of

acknowledge, that

is, acknowledge

package will not be

completed.

REUSE_TX_PL 1110 0011 0 Used for a PTX

device

Reuse last

transmitted payload.

TX payload reuse is

active until

W_TX_PAYLOAD

or FLUSH TX is

executed. TX

payload reuse must

not be activated or

deactivated during

package

transmission.

R_RX_PL_ WIDa

0110 0000 1 Read RX payload

width for the top

R_RX_PAYLOAD

in the RX FIFO.

W_ACK_PAYLOADa 1010 1PPP 1 to 32 LSByte first Used in RX mode.

Write Payload to be

transmitted together

Page 49: Agricultural environment control system using wireless sensor networks

45

with

ACK packet on

PIPE PPP. (PPP

valid in the

Range from 000 to

101). Maximum

three ACK

Packet payloads can

be pending.

Payloads with

same PPP are

handled using first

in - first out

principle.

Write payload: 1–

32 bytes.

A write operation

always starts at byte

0.

W_TX_PAYLOAD_NO

ACKa

1011 0000 1 to 32 LSByte first Used in TX mode.

Disables

AUTOACK

on this specific

packet.

NOP 1111 1111 0 No Operation.

Might be used to

read the

STATUS

Page 50: Agricultural environment control system using wireless sensor networks

46

register

The W_REGISTERand R_REGISTER commands operate on single or

multibyteregisters.

When accessing multi-byte registers read or write to the MSBit of LSByte first.

You can terminate the writing before all bytes in a multi-byte register are

written, leaving the unwritten MSByte(s) unchanged. For example, the LSByte

of RX_ADDR_P0can be modified by writing only one byte to the

RX_ADDR_P0 register.

The content of the status register is always read to MISO after a high to low

transition on CSN.

2-Data FIFO:

The data FIFOs store transmitted payloads (TX FIFO) or received payloads

that are ready to be clocked out (RX FIFO).

Page 51: Agricultural environment control system using wireless sensor networks

47

You can write to the TX FIFO using these three commands:

W_TX_PAYLOADand W_TX_PAYLOAD_NO_ACKin PTX mode and

W_ACK_PAYLOADin PRX mode.

3.11 | Problems That Faces the System:

Problems differentiated from system to another here problems may be caused:

I. One of sensor can to be damage.

II. Data that will be sent may be loss or false.

III. Battery life is short.

IV. Natural phenomena could cause damage on board or Radio.

V. Attackers that hack system and make damage.

Page 52: Agricultural environment control system using wireless sensor networks

48

Page 53: Agricultural environment control system using wireless sensor networks

49

4.1 | Software Tools:-

We have used Visual studio IDE for GUI design and programming and SQL

server for database creation and handling

4.2 | Control system GUI.

GUI is considered the dynamic part that user deals with.

We put in our priority to make GUI simple and provide usability for different

users.

System GUI consists of four subsystems that have different functionalities.

These subsystems are mentioned as:

Configuration System.

Monitoring system

Alert System.

Decision system.

4.2.1 | Configuration system:

In this part we seek to configure the best connection between server and user

system.

We can choose the COM port to connect.

We also can provide some error detection techniques that check the

correctness of arrived data from server.

Page 54: Agricultural environment control system using wireless sensor networks

50

4.2.2 | Monitoring subsystem.

The second subsystem we have is the monitoring part which consists of two

states one for normal users and other for future and advanced calculations.

Page 55: Agricultural environment control system using wireless sensor networks

51

Normal Mode.

In this part we can see real-time values that have been collected from different

sensors in the system.

Temperature sensor can show the temperature values and we can manage the

form in which we need to see values such as Celsius, Kelvin and Fahrenheit.

For Humidity sensor we can determine the status if it is dry, humid, and foggy and error.

These different status are determined based on threshold values that are prior defined.

Page 56: Agricultural environment control system using wireless sensor networks

52

In the switch pump part can show the level of water in the soil based on water level

sensor values.

Advanced mode.

We use charts to represent historical values of sensor reads.

4.2.3 | Alert subsystem.

In this part we can use notifications to warn user if there are any unusual sequence of

events.

The system can alert for fire events, irrigation conditions and any hardware problems.

Page 57: Agricultural environment control system using wireless sensor networks

53

Alarms have two states for work.

We can stop them manually but it also can be automatically reopened after 15 minutes.

4.2.4 | Decision subsystem.

In this part we can control threshold values that affect monitoring process.

So that not any one can control and handle these values we assigned authentication

security option to ensure authority of user to do any changes

Page 58: Agricultural environment control system using wireless sensor networks

54

Page 59: Agricultural environment control system using wireless sensor networks

55

Page 60: Agricultural environment control system using wireless sensor networks

56

5.1 | Implementation of system security.

This chapter talk about security handled to make our system more secure and flexible

to user.

Security in our system help a lot to overcome problems caused damage in system,

Such: Save our system against any damage or hint user to any failure happen,

Make system more secure against unauthorized users that can use data badly or

hidden important data, Make administrative or authentication users track events that

happen in system.

In the system node's component as smoke sensor (MQ-2) take readings of gas, water

level or Moisture soil given readings about soil condition, this readings saved in buffer

and send to end user.

At user control system there are a subsystem that we take about it previously in

implementation chapter one of them for alert.

Alert activated by buzz or show notifications of error happen that present in three

categories one of fire notification depend on readings from MQ-2, other one for

irrigation notification and finally if hardware failure security control system to be

secure by alert user against fire to make decision or irrigation to switch pump or if any

failure happen to repair damage.

In the another hand system give user some privileges as administrative allowed it to

user ,by get him decision to identify and allow whose can use system be sign up

accounts and permission for authentication users.

Page 61: Agricultural environment control system using wireless sensor networks

57

At this urgent step system make only users that have permission to control and access

to threshold and changes or set values as wanted.

here, system have appropriate threshold values that define a lot of things as crop that

will be good to plant under environmental conditional or determine water level and

so on.

At Security part of system user will be need to track events that will be happened in

the system to detect any unauthorized logging or to have a feedback about events he

done.

5.2 | Log files.

So we depended here on Log files that contain a three categories of files:

-Event History.

-log history.

-Notification.

-Event history: is an extension of authentication process which trace the user actions

that took place in the system.

It help to detect sessions that activated that help user to know if there are any sessions

Opened from non-permission users.

-Log History: Monitoring the access control that performed by administrators at

specific time.

To get user information needed about how long activated sessions runs.

Page 62: Agricultural environment control system using wireless sensor networks

58

-Notification: display all the historical notification that generated by the system to be

reviewed as needed by administrator or users later.

All of that help to make system more secure and flexibly to use, it also give

advantages to system as minimized cost and safety water in irrigation and crops from

damage.

Page 63: Agricultural environment control system using wireless sensor networks

59

Appendix

Node code

#include <SPI.h>

#include <nRF24L01.h>

#include <RF24.h>

#include <dht11.h>

/*-----( Declare Constants and Pin Numbers )-----*/

#define CE_PIN 7 /// 7 9

#define CSN_PIN 8 /// 8 10

#define DHT11PIN 3

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe

unsigned long t1=0,t2=0;

int joystick[6]; // 6 element array holding Joystick readings

float humidity, temprature ;

int chk =0 ;

/*-----( Declare objects )-----*/

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

/*-----( Declare Variables )-----*/

dht11 DHT11;

Page 64: Agricultural environment control system using wireless sensor networks

60

void setup() /****** SETUP: RUNS ONCE ******/

{

Serial.begin(9600);

radio.begin();

radio.openWritingPipe(pipe);

pinMode(17,INPUT_PULLUP);

pinMode(14 , OUTPUT);

pinMode(15 , OUTPUT);

}//--(end setup )---

void loop() /****** LOOP: RUNS CONSTANTLY ******/

{

t2=millis();

humidity=(float)DHT11.humidity;

temprature=(float)DHT11.temperature;

joystick[0]=analogRead(2); // smoke

joystick[1]=analogRead(3); // light

joystick[2]=analogRead(4); // moisture

joystick[3]=analogRead(5); // water level

joystick[4]=int(humidity); // humdity

joystick[5]=int(temprature); // temperature

Page 65: Agricultural environment control system using wireless sensor networks

61

if(joystick[3]>=660)

{

digitalWrite(14 , HIGH);

digitalWrite(15 , HIGH);

}

else if(joystick[3]<=436)

{

digitalWrite(14 , LOW);

digitalWrite(15 , LOW);

}

if( t2 - t1 > 2000)

{

t1=t2;

DHT();

}

radio.write( joystick, sizeof(joystick) );

}

void DHT()

{

chk= DHT11.read(DHT11PIN);

Page 66: Agricultural environment control system using wireless sensor networks

62

switch (chk)

{

case 0: break; // print Ok if u want

case -1: Serial.println("Checksum error"); break;

case -2: Serial.println("Time out error"); break;

default: Serial.println("Unknown error"); break;

}

humidity=(float)DHT11.humidity;

temprature=(float)DHT11.temperature;

Serial.print( "temp : " );

Serial.println (temprature);

Serial.print( "Humidity : " );

Serial.println (humidity);

Serial.print("Moisture : ");

Serial.println (joystick[2]);

Serial.print("Water Level : ");

Serial.println (joystick[3]);

Serial.print("Smoke : ");

Serial.println (joystick[0]);

Serial.print("Light : ");

Serial.println (joystick[1]);

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

}

Page 67: Agricultural environment control system using wireless sensor networks

63

Server code

#include <SPI.h>

#include <nRF24L01.h>

#include <RF24.h>

/*-----( Declare Constants and Pin Numbers )-----*/

#define CE_PIN 7 //// 7 9

#define CSN_PIN 8 /// 8 10

#define led 6

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe

/*-----( Declare objects )-----*/

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

/*-----( Declare Variables )-----*/

int joystick[6]; // 7 element array holding Joystick readings

void setup() /****** SETUP: RUNS ONCE ******/

{

Serial.begin(9600);

Page 68: Agricultural environment control system using wireless sensor networks

64

// Serial.println("Nrf24L01 Receiver Starting");

radio.begin();

radio.openReadingPipe(1,pipe);

radio.startListening();

pinMode(led,OUTPUT);

digitalWrite(led,HIGH);

delay(1000);

digitalWrite(led,LOW);

delay(1000);

}//--(end setup )---

void loop() /****** LOOP: RUNS CONSTANTLY ******/

{

if ( radio.available() )

{

digitalWrite(led,HIGH);

// Read the data payload until we've received everything

bool done = true;

if(done == true){

// Fetch the data payload

done = radio.read( joystick, sizeof(joystick) );

Page 69: Agricultural environment control system using wireless sensor networks

65

Serial.print( joystick[0] );

Serial.print( "$");

Serial.print( joystick[1] );

Serial.print( "l");

Serial.print( joystick[2] );

Serial.print( "m");

Serial.print( joystick[3] );

Serial.print( "w");

Serial.print( joystick[4] );

Serial.print( "h");

Serial.println( joystick[5] );

Serial.print( "t");

delay(100);

}

else{

Serial.print(0);

Serial.print( "$");

Serial.print(0 );

Serial.print( "l");

Serial.print(0);

Page 70: Agricultural environment control system using wireless sensor networks

66

Serial.print( "m");

Serial.print(0);

Serial.print( "w");

Serial.print(0);

Serial.print( "h");

Serial.println(0);

Serial.print( "t");

}

}

else

{

digitalWrite(led,LOW);

}

}

Page 71: Agricultural environment control system using wireless sensor networks

67

Labeling data for basic use.

#region labeling data

if (temperature >= 3 && temperature <= 15)

{

//lblTemp.Text = "That's Cold";

lblCold.ForeColor = Color.LightGreen;

lblCool.ForeColor = Color.LightGray;

lblHot.ForeColor = Color.LightGray;

lblTemp.ForeColor = Color.LightGray;

}

else if (temperature >= 16 && temperature <= 29)

{

//lblTemp.Text = "That's Moderate";

lblCold.ForeColor = Color.LightGray;

lblCool.ForeColor = Color.LightGreen;

lblHot.ForeColor = Color.LightGray;

lblTemp.ForeColor = Color.LightGray;

}

else if (temperature >= 30 && temperature <= 48)

{

//lblTemp.Text = "That's Hot";

lblCold.ForeColor = Color.LightGray;

lblCool.ForeColor = Color.LightGray;

lblHot.ForeColor = Color.LightGreen;

lblTemp.ForeColor = Color.LightGray;

Page 72: Agricultural environment control system using wireless sensor networks

68

}

else

{

lblTemp.ForeColor = Color.LightGreen;

lblCold.ForeColor = Color.LightGray;

lblCool.ForeColor = Color.LightGray;

lblHot.ForeColor = Color.LightGray;

}

if (humidity >= 25 && humidity <= 45)

{

// lblHumid.Text = "That's dry";

lblDry.ForeColor = Color.LightGreen;

lblHumi.ForeColor = Color.LightGray;

lblFog.ForeColor = Color.LightGray;

lblHumid.ForeColor = Color.LightGray;

}

else if (humidity >= 45 && humidity <= 84)

{

//lblHumid.Text = "That's Humid";

lblDry.ForeColor = Color.LightGray;

lblHumi.ForeColor = Color.LightGreen;

lblFog.ForeColor = Color.LightGray;

lblHumid.ForeColor = Color.LightGray;

}

else if (humidity < 25)

Page 73: Agricultural environment control system using wireless sensor networks

69

{

//lblHumid.Text = "That's very dry";

lblDry.ForeColor = Color.LightGreen;

lblHumi.ForeColor = Color.LightGray;

lblFog.ForeColor = Color.LightGray;

lblHumid.ForeColor = Color.LightGray;

}

else if (humidity > 84 && humidity < 200)

{

//lblHumid.Text = "That's very Humid";

lblDry.ForeColor = Color.LightGray;

lblHumi.ForeColor = Color.LightGray;

lblFog.ForeColor = Color.LightGreen;

lblHumid.ForeColor = Color.LightGray;

}

else

{

lblHumid.ForeColor = Color.LightGreen;

lblDry.ForeColor = Color.LightGray;

lblHumi.ForeColor = Color.LightGray;

lblFog.ForeColor = Color.LightGray;

}

if (waterlevel >= 400 && waterlevel <= 550)

{

//lblWater.Text = "optimal level";

Page 74: Agricultural environment control system using wireless sensor networks

70

lblWl.ForeColor = Color.LightGray;

lblWm.ForeColor = Color.LightGreen;

lblWh.ForeColor = Color.LightGray;

lblWater.ForeColor = Color.LightGray;

}

else if (waterlevel < 400)

{

// lblWater.Text = "High level water";

lblWl.ForeColor = Color.LightGray;

lblWm.ForeColor = Color.LightGray;

lblWh.ForeColor = Color.LightGreen;

lblWater.ForeColor = Color.LightGray;

}

else if (waterlevel > threw && waterlevel < 800)

{

//lblWater.Text = "Low level water";

lblWl.ForeColor = Color.LightGreen;

lblWm.ForeColor = Color.LightGray;

lblWh.ForeColor = Color.LightGray;

lblWater.ForeColor = Color.LightGray;

}

else

{

lblWater.ForeColor = Color.LightGreen;

lblWl.ForeColor = Color.LightGray;

Page 75: Agricultural environment control system using wireless sensor networks

71

lblWm.ForeColor = Color.LightGray;

lblWh.ForeColor = Color.LightGray;

}

if (light > 0 && light < 150)

{

//lblLight.Text = "It's Shining";

lblShine.ForeColor = Color.LightGreen;

lblDark.ForeColor = Color.LightGray;

lblMD.ForeColor = Color.LightGray;

lblLight.ForeColor = Color.LightGray;

}

else if (light >= 150 && light <= 300)

{

// lblLight.Text = "It's tend to darkness";

lblShine.ForeColor = Color.LightGray;

lblDark.ForeColor = Color.LightGray;

lblMD.ForeColor = Color.LightGreen;

lblLight.ForeColor = Color.LightGray;

}

else if (light > 300)

{

// lblLight.Text = "It's dark";

lblShine.ForeColor = Color.LightGray;

lblDark.ForeColor = Color.LightGreen;

lblMD.ForeColor = Color.LightGray;

Page 76: Agricultural environment control system using wireless sensor networks

72

lblLight.ForeColor = Color.LightGray;

}

else

{

lblLight.ForeColor = Color.LightGreen;

lblShine.ForeColor = Color.LightGray;

lblDark.ForeColor = Color.LightGray;

lblMD.ForeColor = Color.LightGray;

}

if (smoke >= 150 && smoke <= 200)

{

//lblSmoke.Text = "It's may be a fire";

lblMM.ForeColor = Color.LightGreen;

lblLL.ForeColor = Color.LightGray;

lblHH.ForeColor = Color.LightGray;

lblSmoke.ForeColor = Color.LightGray;

}

else if (smoke > thres && smoke <= 600)

{

// lblSmoke.Text = " Caution it's a fire ! ";

lblMM.ForeColor = Color.LightGray;

lblLL.ForeColor = Color.LightGray;

lblHH.ForeColor = Color.LightGreen;

lblSmoke.ForeColor = Color.LightGray;

Page 77: Agricultural environment control system using wireless sensor networks

73

}

else if (smoke <= 150)

{

//lblSmoke.Text = "It's Safe";

lblMM.ForeColor = Color.LightGray;

lblLL.ForeColor = Color.LightGreen;

lblHH.ForeColor = Color.LightGray;

lblSmoke.ForeColor = Color.LightGray;

}

else

{

lblSmoke.ForeColor = Color.LightGreen;

lblMM.ForeColor = Color.LightGray;

lblLL.ForeColor = Color.LightGray;

lblHH.ForeColor = Color.LightGray;

}

if (moisture < threm)

{

//lblMoisture.Text = "Very dry";

lblD.ForeColor = Color.LightGreen;

lblM.ForeColor = Color.LightGray;

lblW.ForeColor = Color.LightGray;

lblMoisture.ForeColor = Color.LightGray;

Page 78: Agricultural environment control system using wireless sensor networks

74

}

else if (moisture >= 50 && moisture <= 100)

{

//lblMoisture.Text = "It's wet";

lblD.ForeColor = Color.LightGray;

lblM.ForeColor = Color.LightGreen;

lblW.ForeColor = Color.LightGray;

lblMoisture.ForeColor = Color.LightGray;

}

else if (moisture > 100)

{

//lblMoisture.Text = "very wet";

lblD.ForeColor = Color.LightGray;

lblM.ForeColor = Color.LightGray;

lblW.ForeColor = Color.LightGreen;

lblMoisture.ForeColor = Color.LightGray;

}

#endregion

Page 79: Agricultural environment control system using wireless sensor networks

75

Example Code for charting data in advanced Mode

#region Smoke char

// overiding the duplicated values

chrtSmoke.Series["Smoke"].Points.Clear();

SqlDataAdapter storesmoke = new SqlDataAdapter("SELECT TOP 9 [value],[time] FROM

[Agriculture].[dbo].[smoke] order by id desc ;", connect);

SqlDataReader readsmoke;

try

{

connect.Open();

readsmoke = storesmoke.SelectCommand.ExecuteReader();

while (readsmoke.Read())

{

chrtSmoke.Series["Smoke"].Points.AddXY(readsmoke.GetString(1),

readsmoke.GetDouble(0));

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

finally {

connect.Close(); }

#endregion

Page 80: Agricultural environment control system using wireless sensor networks

76

A piece of code that Store data

#region Smoke char

// overiding the duplicated values

chrtSmoke.Series["Smoke"].Points.Clear();

SqlDataAdapter storesmoke = new SqlDataAdapter("SELECT TOP 9 [value],[time] FROM

[Agriculture].[dbo].[smoke] order by id desc ;", connect);

SqlDataReader readsmoke;

try

{

connect.Open();

readsmoke = storesmoke.SelectCommand.ExecuteReader();

while (readsmoke.Read())

{

chrtSmoke.Series["Smoke"].Points.AddXY(readsmoke.GetString(1),

readsmoke.GetDouble(0));

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

finally

{ connect.Close(); }

#endregion

Page 81: Agricultural environment control system using wireless sensor networks

77

Notification sys ex.Fire sys

#region Alarm Fire

if (snoozef == false)

{

if (smoke > thres && smoke < 600)

{

smokeA[si] = 1;

si++;

if (si == 61)

{

si = 0;

int i = 0;

for (i = 0; i < 61; i++)

{

smokeA[i] = 0;

}

}

}

else

{

smokeA[si] = 0;

si++;

if (si == 61)

Page 82: Agricultural environment control system using wireless sensor networks

78

{

si = 0;

int i = 0;

for (i = 0; i < 61; i++)

{

smokeA[i] = 0;

}

}

}

if (smokeA.Average() >= 0.75 && si == 60)

{

if (DateTime.Now.Hour > 12)

{

treNotify.Nodes[0].Nodes.Add("smoke sensor detect high level gas at " +

DateTime.Now.Day + "/" + DateTime.Now.Month + " " + (DateTime.Now.Hour -

12).ToString() + ":" + DateTime.Now.Minute);

fileN.WriteLine("smoke sensor detect high level gas at " + DateTime.Now.Day + "/" +

DateTime.Now.Month + " " + (DateTime.Now.Hour - 12).ToString() + ":" +

DateTime.Now);

fileN.WriteLine("----------------------------------------------------------------------------");

}

else

{

treNotify.Nodes[0].Nodes.Add("smoke sensor detect high level gas at " +

Page 83: Agricultural environment control system using wireless sensor networks

79

DateTime.Now.Day + "/" + DateTime.Now.Month + " " +

(DateTime.Now.Hour).ToString() + ":" + DateTime.Now.Minute);

fileN.WriteLine("smoke sensor detect high level gas at " + DateTime.Now.Day + "/" +

DateTime.Now.Month + " " + (DateTime.Now.Hour).ToString() + ":" + DateTime.Now);

fileN.WriteLine("----------------------------------------------------------------------------");

}

player.Play();

Alarm.BalloonTipIcon = ToolTipIcon.Info;

Alarm.Icon = SystemIcons.Information;

Alarm.BalloonTipTitle = "New notification";

Alarm.BalloonTipText = "Fire Alert";

Alarm.ShowBalloonTip(5000);

}

}

#endregion

Page 84: Agricultural environment control system using wireless sensor networks

80

Authentication process

#region Login process

SqlDataAdapter selectuser = new SqlDataAdapter("SELECT * FROM

[Agriculture].[dbo].[Reg] where name = '" + txtLogUser.Text + "' and pass = '" +

txtLogPass.Text + "';", connect);

SqlDataReader readuser;

try

{

connect.Open();

readuser = selectuser.SelectCommand.ExecuteReader();

while (readuser.Read())

{

if (readuser.GetString(0) != null && btnLogin.Text == "Log In")

{

// grpModule.Enabled = true;

grpReg.Enabled = true;

grpThre.Enabled = true;

btnLogin.Text = "Log Out";

btnLogin.BackColor = Color.Red;

this.Focus();

fileL.WriteLine(txtLogUser.Text + " Logged in at " + DateTime.Now);

Page 85: Agricultural environment control system using wireless sensor networks

81

txtLogUser.Enabled = false;

txtLogPass.Enabled = false;

}

else if (btnLogin.Text == "Log Out")

{

// grpModule.Enabled = false;

grpReg.Enabled = false;

grpThre.Enabled = false;

btnLogin.Text = "Log In";

btnLogin.BackColor = Color.SeaGreen;

fileL.WriteLine(txtLogUser.Text + " Logged Out at " + DateTime.Now);

fileL.WriteLine("----------------------------------------------------------------------------");

txtLogUser.Enabled = true;

txtLogPass.Enabled = true;

txtLogPass.Clear();

txtLogUser.Clear();

txtLogUser.Focus();

}

}

if (readuser.HasRows == false)

{

MessageBox.Show("User name or password is incorrect");

Page 86: Agricultural environment control system using wireless sensor networks

82

}

}

catch (Exception)

{

return;

}

finally

{

connect.Close();

}

#endregion

Page 87: Agricultural environment control system using wireless sensor networks

83

users registration process

#region Reg

SqlDataAdapter storereg = new SqlDataAdapter("INSERT INTO Reg (name , pass)

VALUES ('" + txtRegUser.Text + "','" + txtRegPass.Text + "') ;", connect);

SqlDataReader readreg;

try

{

connect.Open();

readreg = storereg.SelectCommand.ExecuteReader();

fileE.WriteLine(txtLogUser.Text + " Had signed up for " + " Mr . " + txtRegUser.Text + "

At " + DateTime.Now);

fileE.WriteLine("----------------------------------------------------------------------------");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

finally

{

Page 88: Agricultural environment control system using wireless sensor networks

84

connect.Close();

txtRegPass.Clear();

txtRegUser.Clear();

txtConfirm.Clear();

MessageBox.Show("you are successfuly signed up", "Confirm");

this.Focus();

}

#endregion

Page 89: Agricultural environment control system using wireless sensor networks

85

Receive , handle and monitoring data

if (Arduino.IsOpen)

{

#region reciving data from arduino and split it into 6 readings from sensors

try

{

indata = Arduino.ReadTo("t");

}

catch (Exception)

{

return;

}

string[] words = indata.Split(spliter, 6);

#endregion

#region handlig data recieved

if (words.Length == 6 && indata.Contains('$'))

{

if (words[0] == "0" && words[1] == "0" && words[2] == "0")

{

//don't collect data

Page 90: Agricultural environment control system using wireless sensor networks

86

}

else

{

try

{

#region Monitring variables

txtSmoke.Text = words[0];

smoke = int.Parse(txtSmoke.Text);

txtLight.Text = words[1];

light = int.Parse(txtLight.Text);

txtMoisture.Text = words[2];

moisture = int.Parse(txtMoisture.Text);

txtWater.Text = words[3];

waterlevel = int.Parse(txtWater.Text);

txtHumidity.Text = words[4];

humidity = int.Parse(txtHumidity.Text);

txtTemp.Text = words[5];

temperature = int.Parse(txtTemp.Text);

if (waterlevel > 435 && waterlevel < 660)

{

prgPump.Value = (660 - waterlevel) + 435;

//lblpmp.Text = "% " + (((prgPump.Value - 435) / (660-435)) * 100).ToString();

}

else if (waterlevel >= 660)

{

Page 91: Agricultural environment control system using wireless sensor networks

87

prgPump.Value = 435;

//lblpmp.Text = "% " + (((prgPump.Value-435) / 660) * 100).ToString();

}

else if (waterlevel <= 435)

{

prgPump.Value = 660;

// lblpmp.Text = "% "+ ((660 / 660) * 100).ToString();

// Arduino Write Switch off pump light

}

}

catch (Exception)

{

return;

}

#endregion

Page 92: Agricultural environment control system using wireless sensor networks

88

Starting and Ending connection

#region End Connection

if (btnPortStart.Text == "Disconnect Server" && Arduino.IsOpen)

{

#region Enaple Alarm And Storing data

// enable data storing

if (StoreData.Enabled == true)

{

StoreData.Enabled = false;

}

//enable Alarm

if (timerAlarm.Enabled == true)

{

timerAlarm.Enabled = false;

}

#endregion

Arduino.Close();

connect.Close();

StoreData.Enabled = false;

timerchart.Enabled = false;

Page 93: Agricultural environment control system using wireless sensor networks

89

timerAlarm.Enabled = false;

cmpPort.Enabled = true;

MessageBox.Show("Your connection with arduino disconnected ", "Access

Notification");

btnPortStart.Text = "Connect Server";

btnPortStart.BackColor = Color.Green;

return;

}

#endregion

#region Start Connection

if (Arduino.PortName != "null" && cmpPort.Enabled == true)

{

MessageBox.Show("You are connected with arduino using port " + Arduino.PortName,

"Access Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);

btnPortStart.Text = "Disconnect Server";

btnPortStart.BackColor = Color.Red;

cmpPort.Enabled = false;

//timerdtaRecieved.Enabled = true;

#region Enaple Alarm And Storing data

// enable data storing

if (StoreData.Enabled == false)

{

StoreData.Enabled = true;

Page 94: Agricultural environment control system using wireless sensor networks

90

}

//enable Alarm

if (timerAlarm.Enabled == false)

{

timerAlarm.Enabled = true;

}

#endregion

Arduino.Open();

}

#endregion


Recommended