You are on page 1of 58

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING

A PROJECT REPORT

ON

“PYTHON BASED
WATER
MONITORING
SYSTEM USING
RASPBERRY PI”

Submitted in the partial fulfillment of the


requirements in the 8th semester of

BACHELOR OF ENGINEERING

ROHIT KUMAR B YOGNATH G VASU IN SHARATH MOHAN RAHUL C


1NH15IS095 1NH15IS142 1NH15IS153 1NH16IS400
INFORMATION SCIENCE AND ENGINEERING

Under the guidance of By

Dr. S Mohan Kumar


Associate Professor,
Dept. of ISE, NHCE
ABSTRACT

Water pollution is one of the biggest fears for the green globalization. In order
to ensure the safe supply of the drinking water the quality needs to be
monitored in real time.
In this project “Python Based Water Monitoring System” we design and
develop a low cost system for real time monitoring of the water quality using
IOT,(internet of things).The system consist of several sensors used to measuring
physical and chemical parameters of the water. The parameters such as
temperature, PH, turbidity, flow sensor of the water can be measured. The
measured values from the sensors can be processed by the core controller.
The measured values from the sensors can be processed by the core controller.
The Raspberry Pi model can be used as a core controller. Finally, the sensor
data can be viewed on internet using WI-FI system.

Keywords - Temperature Sensors, pH Sensor, Turbidity Sensor, Arduino Uno,


Raspberry Pi

i
TABLE OF CONTENTS

ABSTRAC i
T
ACKNOWLEDGEMENT ii

TABLE OF CONTENTS iii

LIST OF FIGURES iv

LIST OF TABLES v

1 INTRODUCTION 1-2

1.1 Purpose of Project 2

1.2 Problem Definition 3

1.3 Scope of Project 3

1.4 Existing System 4

1.5 Proposed System 4-5

2 LITERATURE SURVEY 6-8

3 SYSTEM REQUIREMENTS AND SPECIFICATION 9

3.1 General Description of the System 9-10

3.2 Technical Requirements of the System 10-12

4 SYSTEM DESIGN AND ANALYSIS 13

4.1 System Architecture 13-19

4.2 Data Flow Diagram 20

4.3 Sequence Diagram 20

4.4 Use Case Diagram 21


4.5 Flow Chart 21

4.6 Data Flow Diagram 22

5 IMPEMENTATION 23

5.1 Flow Chart of the Proposed System 24-27

5.2 Source Code 28-40

6 TESTING 41

6.1 Unit Testing 41

6.2 Integration Testing 41-42

6.3 Validation Testing 42-43

6.4 System Testing 43

6.5 Testing of Initialization and UI Components 44-49

7 SNAPSHOTS 50-54

8 CONCLUSION AND FUTURE ENHANCEMENT 55

8.1 Conclusion 55

8.2 Future Enhancement 55

REFERENCES 56-58

PAPER PUBLISHED

iii
LIST OF FIGURES

Figure Number Figure Name Page Number

2.1 System Architecture 09

2.3 Matplot lib 10

2.4 Data Visualization 11

2.5 Raspbian OS 12

2.6 Raspberry Pi 13

3.2 PH sensor 15

3.2 Flow Sensor 19

4.1 System Design 24

Snapshot-1
Snapshot- 31
2
Snapshot-3 32
6 33
Snapshot-
4

7.2 The Testing Process 34

7.4 Unit Testing 35

7.5 Integration Testing 42

7.5 System approach 43

iv
LIST OF TABLES

Table Number Table Name Page Number

6.1 Test Case for Login 46

6.2 Test Case for Bluetooth Connection 46-47

6.3 Test Case for Emergency Mail 47-48

6.4 Test Case for Voice Output- Obstacle Detection 48-49

6.5 Test Case for Voice Output – Moist/Water 49-50

Detection

v
Water Monitoring System

Chapter 1

Preamble

1. Introduction

In today’s world water is an essential resource without which we cannot live without,

hence it can be said that water is a critical resource in the lives of people who both will

have benefits from its use and who are harmed by its misuse and unpredictability

(flooding, droughts, salinity, acidity, and degraded quality). Water pollution is one of the

biggest fears for the green globalization. In order to ensure the safe supply of the

drinking water the quality needs to be monitored in real time.

2. Relevance of theproject

Theproject is based onsolving the issues related with the pollution levels of water by

identifying the underlying issues present in the quality of water by analyzing the intrinsic

issues which cause the quality of water from a different source to degrade and cause

water-borne diseases. Thisproject ismainlyinspired bythe amount of diseases present

in the water in most Indian localities which cause a lot of harm to the populace mainly

in rural areas and areas where water is not readily available or easy to check.

Thisprojectis highly relevantintoday’s worldwheremoneyistime.So,thesystem allows us

to monitor the quality of water in real time easily.

NewHorizon CollegeofEngineering 2018-2019 1


Water Monitoring System

1.3 Purpose

It has been seen that the quality of the water being distributed to most areas (both rural

and urban) has been deteriorating with time as the water sources from where the water

is being drawn gets polluted, as well as lapses in the part of civic body responsible for the

maintenance of the quality of water. It may also be due to no proper maintenance of the

machines which perform the actions necessary to clean or improve the quality of water

being distributed to homes. Thishasbeen observedtomajorly affect thenumberof water

borne-diseases in the city.

Thisproject works on achieving proper evaluation of the quality of water with respect to

some of the most basic parameters i.e. the temperature will be monitored so that the

climatic changes don’t affect the water. The PH will be monitored so that it remain in the

most optimal range and is fit for human consumption and prevents the growth of disease

causing microbes. The flow of the water is monitored so that there are no disruptions or

leaks and also to maintain a specific flow rate which prevents the growth of fungal and

small plants in the transport network. Finally The turbidity of the water is monitored so

that it gives us a measure of the amount of impurities in the water and if needed it can

prompt the required action to change r modify the quality of water if its not in the

permissible range. A major advantage of the system is the real time monitoring of the

quality of the water (i.e:-its immediate quality is monitored) which gives us ability to

immediately determine if the water is really safe for consumption or not. The system

provides us the facility to immediately identify the attributes or parameters of water

and see if there should be any additional measures taken to clean or improve the quality

of the waterCollegeofEngineering
NewHorizon 2018-2019 2
Water Monitoring System

being sent to us.Thishelps us to make clear cut decisions if we need to purchase

additional equipment or not, which in turn helps us to save money and time.

1.4 Scope of theproject

This project is executed by considering all the sensor values from the sensors are appropriately

taken. These values contain the parameters of the water sample being tested such as

temperature, pH , turbidity , flow etc.

In addition to the parameters listed above some additional details can also be gained by the

use of simple scientific knowledge. For example the density of water can be found using the

flow rate of water, which can in turn be used along with the temperature sensor values to

find if the water is contaminated by specific bacteria which can exist in the water sample only

if specific requirements for their survival are met. One such example is E-coli bacteria which

exists in the guts (intestine and stomach mainly) of humans and other animals. It needs a

relatively higher temperature and density to survive (the harmful strain of the bacterium E. coli

O157:H7, can cause severe abdominal cramps, bloody diarrhea and vomiting). Although it can

spread through other sources also one of its main transmission source is through water

sources

, which get contaminated.

Theparameters obtained by the sensors can bethencheckedwithan existing database which

notes down the requirements for different kinds of impurities to provide the necessary

details of the quality of water

NewHorizon CollegeofEngineering 2018-2019 3


Water Monitoring System

This project also requires that the water from a source to be passed with careful

preparations through the equipment to avoid damage of the instruments used to

measure the water parameters.

If the water that passes through the sensors passes the required permissible safety

requirements of the locality then it can be declared as safe for human use.

5. Problem definition

The amount of diseases caused by water borne micro-organisms in todays India is

increasing at an alarming rate and has become a critical issue which hinders the growth

of the populace and its affecting the effective working of thecities as a whole.

Oneofthemajor reasons for this is the pollution of most water bodies and no proper methods

to detect if the water being sent to us is treated properly or not. Noeffective

measureshavebeentakenwith respecttothe quality control of water sources.

6. Problem explanation

The quality of water has deteriorated a lot as can be seen by how most lakes in our cities

are frothing with foam due to the impurities released into the lakes. The water must

definitely be treated to make it fit for consumption and daily use. Moreover, we should

have a means to measure the quality in terms of parameters which we can easily

understand and monitor the quality in real time. Now that there is a large amount of

people fussing about water especially in summer, thegovernmentt has started identifying

few cases where the water is not treated before use and are in need of a solution to

NewHorizon CollegeofEngineering 2018-2019 4


Water Monitoring System

identify the reasons for this growing amount of pollution to the water sourcesin thecity.

Oneof the fewandmostimportantreasonsisthatthereisnorestriction on the groups that

supply water to the neighbourhoods. Since water is supplied by private vendors also in

most areas due to a acute water shortage, the quality of the water is being affected

adversely and in turn leading to a lot of ailments. Although in the early stages its not

visible in everyone and only people with weak immune systems such as elderly people or

new born infants are affected, if its allowed to grow it will definetly lead to an epidemic

of massive proprtions. Hence the need for proper methods to identify the quality of

water.

7. Objective of thestudy

This project focuses on the above mentioned problems by introducing a dynamic IOT Python

based Water monitoring system using Raspberry pi to identify the water Level, amount of

impurities, PH variations & Detect the presence of Bacteria. The Water wastage and Purity of

water can also be found out.

8. Existing system

In the current system, water sample is taken from the source and examined in the

laboratory manually to measure the specifications required (Water Level, impurities,

PH variations &Detection of Bacteria - Water wastage and Purity of water).

1.8.1 Limitations

The system which is implemented and is deployed across the country has certain

NewHorizon CollegeofEngineering 2018-2019 5


Water Monitoring System

limitations such as:

▶ The experts in the lab measure the sample and give a report to the concerned authorities before
the water is sent to the consumers if it passes the QA testing . If the water sample gets
contaminated during the transfer to the customer it cannot be detected.

The consumer is not made aware of the details of the water sample like its components .

They are just told that its safe for use.

1.9 Proposed system

▶ The propose model is a simple water levels / Leaks and Impurities sensing and sending the

data to the WINGZ gateway or directly to server using GSM. The C-mote which measures

the level sends the collected data to the WINGZ through ZigBee/6LoWPAN and UI or a web

application for WINGZ or any platform can be developed to monitor the data obtained from

the sensor in the field.

▶ Data analytics can also be implemented on the gateway side to study the pattern of usage

in storage tanks or water level changes in natural water bodies. There are many types of

level sensor commercially available.

▶ Based on the requirement like measuring range, output (ADC, I2C, UART, Bio etc…) the

sensor has to be selected. Once the sensor is selected and procured, the embedded C

program has to be implemented in C-mote to obtain the water level data from sensor and

communication link between the C-mote and WINGZ using ZigBee/6LoWPAN or GSM has to

be established.

NewHorizon CollegeofEngineering 2018-2019 6


Water Monitoring System

On the WINGZ gateway a simple UI app or middleware using C, C++, python can be developed

to analyse the data or to send the data to the back end server. Water quality sensors like pH,

chlorine, turbidity and flow sensors can also be included with the system to monitor those

parameters.

Advantages

The proposed system tackles the problems mentioned in the existing system such as:

 The system provides real time quality measure of the water sample.

 Accurate and timely available sensor data.

 Easily deployable.

Sophisticated visual representation of the sensor data lets us.

NewHorizon CollegeofEngineering 2018-2019 7


Water Monitoring System

Chapter 2

Literature Survey

2.1 IOT (Internet of things)

 Internet of Things (IOT) is determined as the network of environmental objects which includes
devices, homes, motors which are embedded with sensor, micro-controller, and community
associativity

 It helps combine objects which can then exchange statistics. IOT is a gadget of interrelated
computing gadgets, virtual machines, objects, animals or people with specific identifiers and
ability to transfer statistics over a community with none human-to-human or human-to-pc
interplay.

 IOT includes net-enabled smart devices that use sensors, embedded processor and
hardware to retrieve, ship and get entry to information they gather by from their
environments.

 IOT gadgets share the sensor records they acquire by using connecting to an IOT gateway to
the device where information is both sent to the cloud to be analyzed or analyzed domestically.

 The real-global programs of net of factors, tiers from purchaser IOT and organization IOT to
production and commercial IOT.

 IOT has advanced from the convergence of wi-fi technologies, microelectromechanical


structures, micro services and the internet. IOT encourages agencies to rethink the ways they
technique their corporations, industries and markets and gives them equipment to enhance their
commercial enterprise techniques. because of IOT now more electronic gadgets are connected to
net and communicate to each other without any human interference.

 ATM (Automated Teller Machine) was one of the earliest IOT enabled devices ever to be
introduced. Wearable devices like fitness trackers, smartwatches are connecting extra regular
customers to the IOT. The generation of internet-linked garb is coming. Smart homes are not a
factor for future anymore. Human beings have already commenced adopting smart home, home
equipment and home automation gadgets.

NewHorizon CollegeofEngineering 2018-2019 8


Water Monitoring
System

2. Python
 Python is dynamically typed and garbage-collected.

 It supports various types of programming concepts which includes procedural, object-oriented, and
functional programming and also features a comprehensive library.

 Widely used to create web applications on server and also used widely to develop applications and mobile
games.
 It is high level multi purpose programming language that is widely used in the current industry

2.3 Matplot Lib

It will seem that there are quite some components to consider when you start plotting with this
Python data visualization library.
Sometimes it is even discouraging seeing the amount of code that is necessary for some plots, not
knowing where to start and which components you should use. this Library is very flexible and has a
lot of handy, built-in defaults that will help you out tremendously.
You don’t need much to get started: you need to make the necessary imports, prepare some data,
and you can start plotting with the help of the functions When you’re ready, don’t forget to show
your plot using the functions.
The anatomy of a Matplotlib plot: is it subplot? Or the Axes? What is it exactly?

NewHorizon CollegeofEngineering 2018-2019 9


Water Monitoring System

 Plot creations
 Plotting routines
 Basic Plot Customizations
 Saving Showing Clearing the plots

The main point of Matlib port is to run along with python by showing the above forms of results which is
to be conducted in project.

2.4 Data Visualizations

Data visualization is defined as the process in which the data is represented visually to make the context

more understanding and more clear.

The process of visually representing data in forms of graphs, charts, Flow diagram, pie chart, are called

Data visualization.

Data visualizations is viewed widely by many disciplines because it is a part of modern equivalent for visual

communication.

It ensures the viewers to learn more about the project analyze, study and gasp the detail of it.

This pictorial representation helps in understanding the complex data sets since it is represented
visually.

NewHorizon CollegeofEngineering 2018-2019 10


Water Monitoring
System

2.5 Raspbian OS

Raspbian os is a special type of operating system which helps in functioning the device
operations necessary for customizing the software.

Basically the Raspbian is the Foundations first operating system which is more stable.

Raspbian is a debain-based computer operating system.

There are several version of Raspbian which includes Raspbian stretch and Raspbian Jessie

NewHorizon CollegeofEngineering 2018-2019 11


Water Monitoring
System

2.6 Rasberry pi

Raspberry pi is low cost seized computer which plugs into monitor or Tv which is handy on
keyboard and mouse.
The raspberry pi is device which enables all age people to learn and explore it.

It also gives an additional platform to explore the programming languages like

python and scratch.

The Raspberry pi is one special type of device which enable the user to explore the
software and run the applications based on the customization.

NewHorizon CollegeofEngineering 2018-2019 12


Water Monitoring
System

NewHorizon CollegeofEngineering 2018-2019 13


Water Monitoring System

Chapter 3

System RequirementSpecification

1. General Description of the System

The Python based Water monitoring system using Raspberry pi is developed to serve as a

measure to find all the parameters of water which are needed to find out if the water is

indeed safe for human consumption and general use. The system contains the integration

of several sensors namely PH , temperature ,turbidity, flow sensor to find out their

values and then determine if the water is indeed safe for human consumption . Other

parameters needed can be derived from the known parameters and then we can

determine the quality of the water sample in general.

1. Overview of the functional requirements

The project revolves around the fact that the parameters of water being tested remain

constant during the entire process of testing. All the sensors must first be verified to see

if they are working in their optimal range and if needed, the necessary calibrations are to

be done as required. The data are kept in databases for further analysis using machine

learning algorithm.

NewHorizon CollegeofEngineering 2018-2019 14


Water Monitoring
System

3.1.2 Overview of DataRequirements

The normal range of all the sensors must be taken into account before implementing it.

The sensors range, version info, input voltage and the correct fittings of the connections

must be verified before the system can be used and implemented and the necessary

parameters can be read from the sensor and other operations can be performed.

2. Technical requirements of the system

1. Hardware

requirements PH-

SENSOR

PH, normally used for water measurements, is a measure of acidity and alkalinity, or the caustic and
base present in a given solution.
It is generally expressed with a numeric scale ranging from 0-14. The value 7 represents neutrality.
The numbers on the scale increase with increasing alkalinity, while the numbers on the scale decrease
with increasing acidity.
Each unit of modification represents a multiple modification in acidity or pH.
The pH value is also equal to the negative logarithm of the hydrogen-ion concentration or hydrogen-
ion activity.
The sensor used by us in the implementation of our project is a combination pH sensor as

shown in the given diagram below:-

NewHorizon CollegeofEngineering 2018-2019 15


Water Monitoring System

The most common technique of measurement hydrogen ion concentration is to use associate chemical
science hydrogen ion concentration sensing element.
Combination hydrogen ion concentration sensing elements area unit a sort of chemical science
hydrogen ion concentration sensor that feature each a measurement conductor and a reference
conductor.
The measurement conductor detects changes within the hydrogen ion concentration price whereas the
reference provides a stable signal for comparison.
A high impedance device, known as a pH meter, is used to display the millivolt signal in pH units.
Combination pH sensor technology can be used to build different products, including laboratory pH
sensors and industrial or process pH sensors. The pH sensors have a wide variety of uses.

Most common usage of them are seen in:-


• pH neutralization of effluent in industrial manufacturing environments
• Cooling tower and boiler control
• Environmental monitoring
• Odor scrubbers
• Food and beverage quality control and safety
• Upstream protection of filtration membranes
• Water pre-treatment for manufacturing processes
• Swimming pool control
• Pulp and paper manufacturing
• Pharmaceutical research & development and manufacturing
• Blood-gas analysis in medical devices
• Temperature Sensor

A temperature sensing element plays a vital role in several applications.

Temperature Sensor

More oftentimes, however, temperature detection is part of preventative reliability.


For example, while an appliance might not actually perform any high temperature activities, the
system itself could be at risk to overheating. This risk arises from specific external factors such as a
harsh operating environment or internal factors like self-heating of electronics. By detecting when
overheating occurs, the system can take preventative action. In these cases, the temperature
detection circuit must be reliable over the expected operating temperature range for the
application.

Temperature Sensor Types :-

NewHorizon CollegeofEngineering 2018-2019 16


Water Monitoring System

Temperature detection is that the foundation for all advanced varieties of temperature
management and compensation.
The temperature detection circuit itself monitors ambient temperature. It can then notify the
system either of the actual temperature or, if the detection circuit is more intelligent, when a
temperature control event occurs.

When a particular extreme temperature threshold is exceeded, preventative action can be taken by the
system to lower the temperature.
An example of this is turning on a fan.

Similarly, a temperature detection circuit will function the core of a temperature compensation perform.
Consider a system such as liquid measuring equipment. Temperature, in this case, directly affects the
volume measured. By taking temperature into account, the system can compensate for changing
environment factors, enabling it to operate reliably and consistently.

There are four commonly used temperature sensor types:


1. Negative Temperature Coefficient (NTC) thermistor
A electrical device |semiconductor device |semiconductor unit |semiconductor} may be a thermally
sensitive resistor that exhibits an outsized, predictable, and precise change in resistance correlated to
variations in temperature.

An NTC thermal resistor provides a really high resistance at low temperatures.


As temperature increases, the resistance drops quickly.
Because associate NTC thermal resistor experiences such an outsized modification in resistance per °C,
small changes in temperature are reflected very fast and with high accuracy (0.05 to 1.5 °C).
Because of its exponential nature, the output of an NTC thermistor requires linearization.
The effective operating range is -50 to 250 °C for glass encapsulated thermistors or 150°C for standard.

Resistance Temperature Detector (RTD)


An RTD, conjointly called a thermometer, measures temperature by correlating the resistance of the RTD
element with temperature.
An RTD consists of a movie or, for greater accuracy, a wire wrapped around a ceramic or glass core.
The most correct RTDs area unit created victimisation atomic number 78 however lower-cost RTDs is
made up of nickel or copper.
However, nickel and copper are not as stable or repeatable. Platinum RTDs offer a somewhat linear
output that is highly accurate (0.1 to 1 °C) across the range of -200 to 600 °C.
While providing the best accuracy, RTDs conjointly tend to be the foremost expensive
of temperature sensors

NewHorizon CollegeofEngineering 2018-2019 17


Water Monitoring System

3. Thermocouple

This type of temperature sensors consists mainly of two wires of different metals connected at two
points.
The variable voltage between these 2 points reflects proportional changes in temperature.
Thermocouples are nonlinear, requiring conversion once used for temperature management and
compensation, generally accomplished employing a search table.
Accuracy is low, from 0.5 °C to 5 °C. However, they operate across the widest temperature range, from -
200 °C to 1750 °C.

4. Semiconductor-based sensors

A semiconductor-based temperature sensing element is placed on integrated circuits (ICs).


These sensors ar effectively 2 identical diodes with temperature-sensitive voltage vs current
characteristics that may be wont to monitor changes in temperature.
They offer a linear response but have the lowest accuracy of the basic sensor types at 1 °C to 5 °C. They
also have the slowest responsiveness (5 s - 60 s) across the narrowest temperature range (-70 °C -150
°C).

Turbidity Sensor

Turbidity sensors live the quantity of sunshine that's scattered by the suspended solids in water.
As the quantity of total suspended solids (TSS) in water will increase, the water’s turbidness level (and
cloudiness or haziness) will increase.
Turbidity sensors are put to use in streams and water gauging, waste matters and effluent
measurements, managing instruments for subsiding ponds, sedimentary transportation research, and
lab experiments.

Flow Sensor

Flow sensors are devices used for measure the rate of flow or amount of a moving liquid or gas.
The water flow sensing element consists of a plastic valve body, a water rotor, and a hall-effect
sensor. When water flows through the rotor, rotor rolls. Its speed changes with different rate of flow.
The hall-effect sensor outputs the corresponding pulse signal. The figure given below
shows the cross-section of the sensor we have incorporated into our project.

NewHorizon CollegeofEngineering 2018-2019 18


Water Monitoring
System

3.2.1 Software requirements

Python

The language of Python programming is freely available and makes it almost as easy to

solve a computer problem as you write your thoughts on the solution. It is possible to

write the code once and run on almost any computer without changing the program. It is

NewHorizon CollegeofEngineering 2018-2019 19


Water Monitoring System

a language of programming that is multiparadigm, general purpose, interpreted, high-

level. Python allows programmers to create simple or complex programs using different

programming styles, get faster results, and write code almost as if they were speaking in

a human language. Google Search, YouTube, BitTorrent, Google App Engine, Eve Online,

Maya and iRobot machines are some of the popular systems and applications that Python

used during development. Python has been around for over 20 years, so many code

written in Python has built up over the decades and, being an open source programming

language, a lot has been released for use by others. You can install this software to use

your own projects on your system. For example, if you want to use Python to build scripts

with command-line arguments, you would install and import the "click" library into your

scripts.

 Arduino

Arduino is associate ASCII text file physical science platform supported easy-to-use hardware and
software package.
Arduino boards are able to scan inputs - lightweight on a sensing element, a finger on a button,
or a Twitter message - and turn it into an output -
activating a motor, turning on an LED, publishing something online.
You can tell your board what to try to by causation a collection of directions to the
microcontroller on the board.
To do therefore you employ the Arduino programing language (based on Wiring), and the
Arduino Software (IDE), based on Processing.

Over the years Arduino has been the brain of thousands of comes, from everyday objects to
complex scientific instruments.

Arduino was born at the Ivrea Interaction style Institute as a straightforward tool for quick
prototyping, aimed at students without a background in electronics and programming.
As before long because it reached a wider community, the Arduino board started changing
to

NewHorizon CollegeofEngineering 2018-2019 20


Water Monitoring System

adapt to new needs and challenges, differentiating its offer from simple 8-bit boards to products
for IoT applications, wearable, 3D printing, and embedded environments.
All Arduino boards ar fully ASCII text file, empowering users to build them independently and
eventually adapt them to their particular needs.
The software package, too, is ASCII text file, and it's growing through the
contributions of users worldwide

3. Input Requirements

The details of the Arduino- uno are the same as any basic Arduino, hence the drivers required
are simple ones which are available in the website of Arduino. They are free to download
and use . The Arduino takes in 5V power supply in the form of uninterrupted power directly
from the Raspberry pi where its connected and passes the necessary input to the sensors as
and when required by them.

4. Output Requirements

All the sensor output taken or sensed by the Arduino are directly passed to the
Arduino board which is interfaced or connected with the Raspberry pi. The data is
passed to the Pi which can be viewed on the serial Monitor section of the Python
software section.

5. Language specification

 Python

Python was released on July 3rd, 2010 which included different set of updation and
changes than its former version. It has two sting types which are Unicode strings and
non- Unicode strings. The xrange() function is added to be used to create iterable
objects. There are separate int and long types for non-floating-point numbers. It
included the support for Tkninter and a backport of the memory view object. It has

NewHorizon CollegeofEngineering 2018-2019 21


Water Monitoring System

the added feature of dictionary view and new syntax for nested with statements. It
has much longer period time of maintenance when compared to the earlier version
of
2.x which will be supported by the core development team which means that it will
be receiving the security updates and other bug fixes until at least 2020 which almost
10 years from the date of initial release

NewHorizon CollegeofEngineering 2018-2019 22


Water Monitoring System

Chapter 4

System Design and Analysis

4.1 Preliminary Design

The IOT based system to monitor the quality of water using the sensors to determine

the parameters is built and can be used to measure some of the basic parameters.

System Architecture:-

Fig: 4.2 ArchitectureDiagram

NewHorizon CollegeofEngineering 2018-2019 23


Water Monitoring
System

Fig: 4.2 Data Flow Diagram

NewHorizon CollegeofEngineering 2018-2019 24


Water Monitoring System

Chapter 5

Implementation
“Python based Water monitoring system using Raspberry pi” is a system used to measure

the qualitative parameters of an important resource required for the continued

sustenance of human life namely water.

Implementation of the project is done one sensor at a time so that it is easy to get the

readings and no cross-talk or readings from other sources interfere.

1. The Different Modules of the Project


Aproject usually comprisesofmanymodules.Amodule in general is ahigh-levelcomponent

that can function independent of each other. Many such modules are combined/integrated

togetherto performthe tasks rendered by them and give the output required by them

which

can then be seen as individual units or as a whole to form a full-fledged project.

Modules in “Python based Water monitoring system using Raspberry pi” are listed
below:

1. RPH sensor module to determine the ph of the water which we are testing.

2. A Temperature sensor module to determine the temperature.

3. A turbidity sensor to find the amount of colloidal particles suspended in


water(impurities) .

A Flow sensor to determine the flow rate of water.

NewHorizon CollegeofEngineering 2018-2019 25


Water Monitoring
System

5.2. Functional Description of the Modules


Module functionalities and implementation details are included in the following sub-

sections. As a prototype the above modules are implemented in a simpler and cost-

Code snippets:-

Arduino Code for Sensor Calibration:

#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 5

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

float Celcius=0;
float Fahrenheit=0;

float voltage=0;

const int analogInPin = A0;


int sensorValue = 0;
unsigned long int avgValue;
float b;
int buf[10],temp;

void setup(void)

NewHorizon CollegeofEngineering 2018-2019 26


Water Monitoring
System

void setup(void)
{

Serial.begin(9600);
sensors.begin();

int sensorValue = analogRead(A1);


voltage = sensorValue * (5.0 / 1024.0);
}

void loop(void)
{
sensors.requestTemperatures();
Celcius=sensors.getTempCByIndex(0);
Fahrenheit=sensors.toFahrenheit(Celc
ius);

for(int i=0;i<10;i++)
{

buf[i]=analogRead(analogInPin);
delay(10);
}
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(buf[i]>buf[j])
{
temp=buf[i];
buf[i]=buf[j];

buf[j]=temp;
}
NewHorizon CollegeofEngineering 2018-2019 27
Water Monitoring
System

}
}

for(int i=2;i<8;i++)

avgValue+=buf[i]
;
float pHVol=(float)avgValue*5.0/1024/6;
float phValue = -5.70 * pHVol + 21.34;

Serial.println(phValue);
Serial.print("pH");
Serial.print(" C ");
Serial.print(Celcius);

Serial.print(voltage);
Serial.print("V");
delay(10000);
}

Python Code for Serial Data Monitoring:

import serial
import time
import csv
import
numpy as
np
import
matplotlib.p
yplotNewHorizon
as plt CollegeofEngineering 2018-2019 28
Water Monitoring System

ser = serial.Serial('/COM6',9600)
ser_bytes = ser.readline(10)
print (ser_bytes)

ser.flushIn
put()

while True:
try:
ser_byte
s=
ser.rea
dline()
decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
print(decoded_bytes)
temp = float(decoded_bytes(1:3))
turb = float(decoded_bytes(4:6))
pH = float(decoded_bytes(6:8))
with open("test_data.csv","a") as f:
writer = csv.writer(f,delimiter=",")

writer.writerow([time.time(),decoded_bytes])
except:
print("Keyboard Interrupt")

ser.close()
break()

t = np.arange(0.0, 2.0, 0.01)


s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)

plt.xlabel('time (s)')
plt.ylabel('Celsisus (C)')
plt.title('Temperature')
plt.grid(True)
NewHorizon CollegeofEngineering
plt.savefig("Temperature.png") 2018-2019 29

plt.show()
Water Monitoring
System

plt.xlabel('time (s)')
plt.ylabel('Volatge (C)'

plt.title('Turbidity')
plt.grid(True)
plt.savefig("Turbidity.png")
plt.show()

plt.xlabel('time (s)')
plt.ylabel('pH ')
plt.title('pH')
plt.grid(True)
plt.savefig("pH.png")
plt.show()
Serial.begin(9600);
sensors.begin();
int sensorValue = analogRead(A1);
voltage = sensorValue * (5.0 / 1024.0);
}

void loop(void)
{
sensors.requestTemperatures();
Celcius=sensors.getTempCByIndex(0);
Fahrenheit=sensors.toFahrenheit(Celcius);

for(int i=0;i<10;i++)

NewHorizon CollegeofEngineering 2018-2019 30


Water Monitoring System

{
buf[i]=analogRead(analogInPin);
delay(10);
}
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(buf[i]>buf[j])
{
temp=buf[i];

buf[i]=buf[j];

buf[j]=temp;
}

n = 256
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)
plt.plot(X, C)
plt.plot(X,S)

plt.show()

print ("Visualization of real time sensor Data.")


print("/n")

NewHorizon CollegeofEngineering 2018-2019 31


Water Monitoring System

while True:
try:
ser_byte
s=
ser.rea
dline()
decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
print(decoded_bytes)
temp = float(decoded_bytes(1:3))
turb = float(decoded_bytes(4:6))
pH = float(decoded_bytes(6:8))

with open("test_data.csv","a") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow([time.time(),decode
d_bytes])
except:
print("Keyboard Interrupt")
ser.close()
break()

t = np.arange(0.0, 2.0, 0.01)


s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)

NewHorizon CollegeofEngineering 2018-2019 32


Water Monitoring System

Chapter 6

EXPERIMENTAL RESULTS
The snapshots of each module’s outcome are included below.

Turbidity is seen in the unit NTU:-

i) For
Dusty water:-

NewHorizon CollegeofEngineering 2018-2019 33


Water Monitoring
System
ii For Clear Water :-
)

Temperature Sensor:-

i)For slightly heated water

NewHorizon CollegeofEngineering 2018-2019 34


Water Monitoring
System

iii) Chill water:-

Flow Sensor:-

Flow Sensor output is measured in terms of amount of water flowing per unit time.
The unit which is used here is litres/hour.
Since the amount of water which we are using is too little the measurements are in
te range of 0-0.2 l/h.

PH Sensor : -

Ph sensors measure whether the given liquid is acidic or basic in nature.


The range of a few liquids which we tested were as follows:

Tap water – 5.5-7

Soap water:-12.3-14

Lime juice:- 2.5-3.5

NewHorizon CollegeofEngineering 2018-2019 35


Water Monitoring
System

Chapter 7

Testing

7.1 Testing andvalidation

Testing is the most important part of thesoftware development process. Some of

the reasons for its importance are as follows:

 Testing helps find and fix the bugs in the software which prevent the program from performing as
required or as efficiently as needed.
 Bug fixing in the early development stages helps to save a lot of time and effort.

 Testing is very essential tomake sure that the final output product willwork well without any
errors oncedeployed.

 Testing improves the quality of the software.

Validation is the process of ensuring that the software built is in accordance with

the expected business requirements. It assures to satisfy customer needs.

7.2 Testing
Levels

Fig.7.1. Represents different levels of testing during the SDLC

NewHorizon CollegeofEngineering 2018-2019 36


Water Monitoring System

1. Functional testing

This type of testing is done against the functional requirements of the

project.

Types:

 Unit testing: Each unit/module ofthe project is tested one by one to check
for bugs.

If any bugs found during the process by the testing team, it is reported once

found or discovered to the developer for fixing.

 Integration testing: All the units are nowintegrated as one single unitandchecked

for bugs. This also checks if all the modules are working properly with each other.

 System testing: This testing checksfor operating system compatibility. It includes

both functional and non functional requirements.

 Sanity testing: It ensures change in the code doesn’t affect the working of

the project.

 Smoke testing: thistype of testing is aset of


smalltestsdesignedforeachbuild.

 Interface testing: Testing of the interface and its proper functioning.

 Regression testing: Testing the software repetitively when a new requirement

is added, when bug fixed etc.

Beta/Acceptance testing: User level testing to obtain user feedback on the product.

NewHorizon CollegeofEngineering 2018-2019 37


Water Monitoring System

7.2.2 Non-functional testing

Thistypeoftesting ismainly concernedwiththenon-functionalrequirementssuchas

performance of the system under various scenarios.

 Performance testing: Checks for speed, stability and reliability of the software, hardware

or even the network of the system under test.

 Compatibilitytesting: This type of testing checks for compatibility of the system

with different operating systems, different networks etc.

 Localization testing: Thischecksforthelocalizedversion of theproductmainly concerned

with UI.

 Security testing: Checks if thesoftware has vulnerabilities and if any, fix them.

 Reliability testing: Checks for the reliability of the software

 Stresstesting:Thistestingcheckstheperformanceofthesystemwhenitisexposedto

different stresslevels.

 Usabilitytesting: Type of testing checks the easily the software is being used by

the customers.

Compliance testing: Type oftesting todeterminethecompliance ofa system withinternal

or external standards.

7.3 White boxtesting

White box testing is performed by the developer while developing the various modules for the
software. This type requires thorough knowledge about the software i.e. the
internal logic in the program that is used and the structure of the code used in the program.

NewHorizon CollegeofEngineering 2018-2019 38


Water Monitoring System

7.4 Unit testing

Unit Testing is the very first level of testing of thesoftware where theminute testable partsofanewly
finishedsoftwarepartsaretested.Thisisusedtovalidatethateachunit of the software performs as designed.

NewHorizon CollegeofEngineering 2018-2019 39


Water Monitoring
System

Unit-1

Sensor Reading using OpenCV- Decision Table

Conditions Rule1 Rule2 Rule3 Rule4 Rule4

Temperature N Y Y Y Y
Sensor

Caliberation- Y/N

Turbidity N N N Y Y
Sensor

Caliberation– Y/N

pH Sensor Caliberation– N N Y Y N
Y/N
Actions

Model Integration– X TC EC EC TC

TC/EC

Serial Data Monitoring– X F F F T

T/F

Visual Depiction of X F T T F

Serial Data- T/F

NewHorizon CollegeofEngineering 2018-2019 40


Water Monitoring System

Y-

Yes

N-

No

TC-
True
Coun
t

EC- Error Count


T- True
F- False

The testing
method used
for Unit testing
is White Box
testing method
.

OOP concepts
supported by
unit test
framework:

 test
fixture:

Atestfixtureisusedasabaselineforrunningteststoensurethattestsare
conducted in a fixed environment for repeatable results.
Examples :

 Creating temporary databases.


 test runner:
 Starting a serverprocess.
A test runner sets up the execution of tests and also provides the outcome of the function to the
user.test case:

Atestcaseisasetofconditionswhichisusedtodeterminewhetherasystem under
test workscorrectly.
 test suite:
NewHorizon CollegeofEngineering 2018-2019 41
Testsuiteisacollectionoftestcasesthatareusedtotestasoftwareprogramto showthatit hassome
specified set of behaviours byexecuting theaggregated tests together.
Water Monitoring
System

TheUnit testframework of pythoncanbeusedto convertthedecisiontabletest casesthat


weuse,

to carry out testing on the unit by providing input and verifying the output manually into

automated testing.

7.2 Integration testing

INTEGRATIONTESTINGisasoftwaretestlevelthatcombinesandtestsindividual units as a

group. The purpose of this test level is to identify errors in the interaction of integrated

units. In Integration Testing, test drivers and test stubs are usedto assist.

Testing the interfaces between units / modules is the main function or goal of this test.

We normallydoIntegrationtesting after“Unittesting”.Once all the individual units are

created and tested, combining of those “Unit Tested” modules are started and start

doing the integrated testing. The main function or goal of this testing is to check the

functions between the units/modules. The individual modules are first tested in isolation.

Once the modules are unit tested, they are integrated one by one, till all the modules are

integrated, to check the combinational behavior, and validate whether the requirements are

implemented correctly or not.

Here we should understand that integration testing does not take place at the end of the cycle,
butis carriedoutatthesametimeasthedevelopment.Somostofthetime,not all themodules are
available for testing and here'swhatthechallenge is totestsomething

NewHorizon CollegeofEngineering 2018-2019 42


Water Monitoring
System

Fig.7.3. Architecture of a web application taken as example

UI – User Interface module, which is visible to the end user, where all the inputs are given.
BL– Is

the Business Logic module, which has all the all the calculations and business specific

methods.

VAL – Is the Validation module that has all the input correctness validations.

CNT – Is the content module that has all the static content specific to the user's inputs.

The reports display these contents.

EN – Is the Engine module, this module reads all the data that comes from BL, VAL and
CNT

module and extracts the SQL query and triggers it to the database. Scheduler – Is a module

that schedules all reports (monthly, quarterly, semi-annually & annually) based on user

selection

DB – Is the Database.

Now, having seen the architecture of the entire web application, as a single unit,

Integrationtesting,in thiscase,will focus on theflow of databetween


NewHorizon CollegeofEngineering 2018-2019 43
themodules.
Water Monitoring System

The questions here are:

1. Howthe BL, VAL and the CNT module will read andinterpret ate the data entered in

the UImodule?

2. Is BL, VAL and CNT module receiving the correct data from UI?

3. Inwhichformatthedata from BL, VAL and CNT is transferredtothe EQ module?

4. How will the EQ read the data and extract the query?

5. Is the query extracted correctly?

6. Is the Scheduler getting the correct data for reports?

7. Istheresult setreceivedbythe EN, from thedatabaseiscorrect and asexpected?

8. Is EN able tosendtheresponse back tothe BL, VALand CNTmodule?

9. Is UI module able to readthe data and display it appropriately totheinterface?

Big bang integration testing was carried out to test the flow of data and interactions
between the modules in the project.

NewHorizon CollegeofEngineering 2018-2019 44


Water Monitoring System

As theproject was demonstrated as aprototype big bang approach is the onethat was

well- suited to test small systems.

Integration Testing approach:

1. Bottom-up approach

Fig.7.5. Represents bottom-up approach of integration testing

Asthenamesuggests, bottom-uptestingstartsfromtheapplication's lowest or innermost


unit and gradually moves up. Integration testing begins with the lowest module and
progresses graduallytowards the application's upper modules. This integration
continues
untilallmodulesareintegratedandtestedasasingleunitfortheentireapplication.Test
procedure:

1. The output from the LPR system is testedfor accuracy andif it’s in the acceptable string
format.

2. The occupancy count is determined based on the vehicle and count is processed
fortollgeneration.

0-foranyothervehicleotherthancarandtheexactcount>1 for car.


3. Apythonscriptthatacceptstheseinputsprocesses thedynamictoll by
performing

essential queries and displaying the toll.

NewHorizon CollegeofEngineering 2018-2019 45


Water Monitoring
System

4. The dynamic toll along with vehicle details, route chosen and time stamp is updated in a
column-key of the database for further queries.

5. System testing

System Testing is a software test level that tests a complete and integrated software. This test

is intended to evaluate the compliance of the system with the specified requirements. Testing

system requirements: The agenda is to test if the system serves the initial requirements

stated, asin:

 If,avehiclepassesbythetollgate,theimagewiththevehiclenumberplatetobe

captured.

 The capture image to be processed and the number plate to be detected and the

number to be predicted and access the details of the vehicle from the authorized

database.

 If the vehicle is a car, then the occupancy to be processed.

 The route to be input to the module

 Thedynamictoll to be generatedbased on theoccupancyandtheroute chosenif,

car else just consider the route chosen and the type of the vehicle.

 Based on thetimestamp querythedatabasetoknow if itsone-way ortwo-way

trip and determine the toll.

NewHorizon CollegeofEngineering 2018-2019 46


Water Monitoring System

Chapter 8

Conclusion and Future Enhancements

8.1 Conclusion

Monitoring of Turbidity, PH & Temperature of Water makes use of water detection sensors with
unique advantage and existing GSM network. The need to monitor these values of water arises
with the rise in the risk caused due to the current water quality and standards of water available
for drinking, domestic and household purposes. Even if we humans get adapted to the current
standards and quality of water content, there are many other living organisms and plants that
need a good supply of clean to water to survive. The water quality monitoring is performed
automatically by the system and it is low in cost and does not require people on duty. So the
water quality testing is likely to be more economical, convenient and fast. The system has good
flexibility. This system can be used to monitor other water quality parameters only by replacing
the corresponding sensors and changing the relevant software programs. The working is simple,
the system can be put to better and more use to monitor hydrologic, air pollution, industrial and
agricultural production and so on. It has widespread application and an extension value. In this
project, a IOT based bio monitoring system is proposed which uses sensors to get the most
essential values which can be used to obtain other parameters of all the sensors that are being
used in the model. The project serves its purpose well to cater the needs of current and future
generations. The fact that it focuses on the most sensitive and basic need for survival makes it
that valuable and resourceful. The project focuses completely on something that goes
completely unnoticed and ignored, the quality of water being consumed and used for other
needs. If the quality of water of many places were known, people would immediately stop
consuming or avoid using that particular water due to how harmful and dangerous it may turn out
to be for daily usage. People moving into new locations have no idea about the water
quality and standards of that place, and need a source to monitor the same, this project
would definitely prove to be of great use in such circumstances. Also, knowledge of such quality

of water would help make changes and provide better water henceforth, as prevention is always

NewHorizon CollegeofEngineering 2018-2019 47


Water Monitoring
System

better than cure.

8.2 Future enhancements

The data that is collected over time can be sent to a system or program that can be used to
obtain additional parameters such as density, amount of bacteria the viscosity of water etc.
and then these parameters can be analyzed and by the software. This project serves as a great
purpose to current and future generations. Water monitoring in these times of having irregular
and low quality water supply proves to be very essential to household and domestic needs.
The current generation having suffering a lot of water pollution and unsafe water, definitely
need an approach to keep track of the water that they are consuming and using for domestic
needs. The future however, this project can be implemented just the way it is or also with
major and minor changes to suit the needs of the future generations. The fact that there are a
lot of dying water bodies and the need for water arising every day this project would indeed be

of great help to many people.

NewHorizon CollegeofEngineering 2018-2019 48


Water Monitoring
System

REFERENCES:

1. Dr. Mohan Kumar S & Dr. Balakrishnan, Classification Of Breast Mass Classification – CAD System
And Performance Evaluation Using SSNE, IJISET – International Journal of Innovative Science,
Engineering & Technology, Vol. 2, Issue 9, 417-425, ISSN 2348 – 7968

2. Dr. Mohan Kumar S, Dr. Balakrishnan, Classification Of Breast Mass Classification – CAD System
With Performance Evaluation, International Journal of Engineering And Computer
Science, Volume 4, Issue 09, 14187-14193, ISSN 2319-7242, September, 2015

3. Dr. Mohan Kumar S, Dr. Balakrishnan, Classification Of Breast Microcalcification- CAD System
And Performance Evaluation Using SSNE, International Journal of Advanced Research in Computer
Science and Software Engineering, Volume 5 , Issue 9, 824-830, ISSN: 2277 128X, Sep- 2015

Review through Web Reference

www.codenotes.com

www.python.org

www.w3schools.com

NewHorizon CollegeofEngineering 2018-2019 49


Water Monitoring
System

NewHorizon CollegeofEngineering 2018-2019 50

You might also like