0% found this document useful (0 votes)
656 views

Water Quality Monitoring systemFINAL)

This document describes a water quality monitoring system based on Internet of Things technology. The system uses sensors like temperature and turbidity sensors connected to a NodeMCU microcontroller to monitor and measure water quality parameters. If the measured parameters exceed certain thresholds, a servo motor connected to the NodeMCU will close the water pipe. The NodeMCU transmits the sensor data to a Raspberry Pi server. Users can access the stored sensor data through a website to monitor water quality remotely. The system aims to ensure safe drinking water by automatically controlling the water flow based on real-time sensor readings of water parameters.

Uploaded by

Yisäk Desälegn
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
656 views

Water Quality Monitoring systemFINAL)

This document describes a water quality monitoring system based on Internet of Things technology. The system uses sensors like temperature and turbidity sensors connected to a NodeMCU microcontroller to monitor and measure water quality parameters. If the measured parameters exceed certain thresholds, a servo motor connected to the NodeMCU will close the water pipe. The NodeMCU transmits the sensor data to a Raspberry Pi server. Users can access the stored sensor data through a website to monitor water quality remotely. The system aims to ensure safe drinking water by automatically controlling the water flow based on real-time sensor readings of water parameters.

Uploaded by

Yisäk Desälegn
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

WATER QUALITY MONITORING SYSTEM BASED

ON INTERNET OF THING
Documentation submitted in partial fulfillment of the requirements for
the award of the degree of
Bachelor of Science in Computer Engineering
By
NAME OF STUDENTS ID

NIMONA MEGERESA ETS0908/08


HABTAMU AYANA ETS0533/08
HABIB MOHAMMED ETS 0529/08

ADVISOR: - NETSANET GETENET (MSc)

ADDIS ABABA SCIENCE AND TECHNOLOGY UNIVERSITY

JANUARY 2020

i
Examining Committee Approval Sheet

Title of Thesis: Water Quality Monitoring System Based on IoT

Student Names (& ID): Name ID


Nimona megersa ETS0908/08
Habtamu Ayana ETS0533/08

Habib Mohammed ETS0529/08

Approved by the examining committee members:

Name Academic Rank Signature Date


Advisor: ________________ _______________ ___________ ___________
_
Co-Advisor: ________________ _______________ ___________ ___________
_
Examiner: ________________ _______________ ___________ ___________
_
Examiner: ________________ _______________ ___________ ___________
_

Name Signature Date


DC Chairperson: _______________ _______________ _______________
_ _ _

Associate Dean for _______________ _______________ _______________


_ _ _
Under Graduate
Programs:

ii
DECLARATION

We are students of Addis Ababa Science and Technology University (AASTU) College of
Electrical and Mechanical Engineering. The information found in this project is our
original work. And all sources of materials that are used for the project are fully
acknowledged.

Name ID Signature

1. Nimona Megeresa ETS 0908/08 _________________

2. Habtamu Ayana ETS 0531/08 _________________

3. Habib mohammed ETS 0652/08 _________________

Date of submission date: -___________________

This project has been submitted for examination with our approval as a university advisor

Name Signature date

Mr. Netsanet Getnet _____________ ________________

iii
ACKNOWLEDGMENT

First and foremost, we would like to give our heartfelt gratitude to the almighty God that keeps
us to this day with His endless love and guidance in the path of our life. Next, we would like to
thank the Addis Ababa Science and Technology University department of computer engineering
for giving this chance to this thesis project. Especially, we would like to acknowledge our
advisor, Mr.Netsanet Getenet for his valuable and constructive suggestions during the
development of this project work. His willingness to give his time so generously has been very
much appreciated and as well as his dedication towards work and hardworking nature is the
motivation for us. Finally, we also extend our sincere thanks to all of our friends for their
contribution and ideas during the development of this project.

iv
ABSTRACT

Wireless communication developments are creating new sensor capabilities. Sensor networks are
critical for monitoring physical conditions of the environment such as temperature, humidity,
level of pollution, etc. Internet of Things (IoT) emphasis on connections among different devices
with the ability to exchange and gather collected data. In today's times, ensuring a safe/purified
supply of water for drinking is difficult, because it can be polluted by chemical wastes from
industries, animal wastes, and human contributions for different purposes. These results in illness
or death for human beings. Therefore, Accurate, efficient, inexpensive, and multi-parameter
monitoring of water quality parameters is critical for continued water safety from developed
urban regions or villages to resource-limited or sparsely populated areas. In this paper, we
propose a low cost and efficient system for water quality monitoring and controlling using IoT.
This system consists of several sensors such as turbidity and temperature sensor and servo motor.
These sensors are interfaced to nodeMCU and the data recorded to it is sent to the server and if
the quality of water is out of threshold value the servo motor rotates and closes the pipe. In this
project, The Raspberry Pi acts as a server and its stored data can be accessed through a website.

Key Words: - water quality, temperature sensor, turbidity sensor, internet of thing

v
TABLE OF CONTENTS
Approval Sheet ii

Declaration iii

Acknowledgements iv

Abstract v

Table of Contents. vi

List of Figures viii

List of Tables viii

List of Abbreviations ix

CHAPTER 1: INTRODUCTION
1 Introduction 1
1.1 PROBLEM STATEMENT 2
1.2 Objectives of the Project 3
1.2.1 General objective 3
1.2.2 Specific objective 3
1.3 significance of the project 4
1.4 Scope and Limitation 4
CHAPTER 2: LITERATURE REVIEW
2. Literature review 5
CHAPTER 3: METHODOLOGY AND SYSTEM DESIGN
3.1 Proposed System 7
3.2 Block Diagram of the System 9
3.2.1 Raspberry pi B+ 9
3.2.2 NodeMCU ESP8266 11

vi
3.2.3 DS18B20 Temperature sensor 12

3.2.4 Turbidity Sensor 14


3.2.5 Micro ServoMotorSG90 15
3.3 Software Implementation 16
3.4 Hardware Implementation 17
3.4.1 Interface of Temperature Sensor with NodeMCU 17
3.4.2 Turbidity Sensor Interface with NodeMCU 18
3.4.3 Interfacing servo motor with NodeMCU 19
CHAPTER 4: RESULT AND DISCUSSION
4.1The relationship between turbidity TDS and TSS 26 21
4.2 The Effect of Temperature Sensor on other Water Quality parameter 22
4.3 Result 25
CHAPTER 5: CONCLUSION AND SCOPE FOR FUTURE WORK
5.1Conclusion 28
5.2 Future Work 28
REFERENCES 29
APPENDIX A: PROJECT CODE

vii
LIST OF FIGURES

Figure 3.1: System Design of water Quality Management System Using IoT
Figure 3.2: login system for website
Figure 3.3: Block Diagram of the system
Figure 3.4: Raspberry Pi B+
Figure 3.5: NodeMCU ESP8266
Figure 3.6: DS18B20 Temperature sensor
Figure 3.7: Turbidity level of water
Figure 3.8: Turbidity Sensor
Figure 3.9: Micro servo motor 9g SG90
Figure 3.10: Flow chart of the system
Figure 3.11: Color representation of temperature sensor
Figure 3.12: Interfacing Temperature sensor with nodeMCU
Figure 3.13: Parts of the Turbidity sensor
Figure 3.14 Interfacing turbidity with nodeMCU
Figure 3.15:Interfacing Servo Motor with nodeMCU
Figure 4.1:Relationship between turbidity, TSS, and TDS
Figure 4.2:Relationship between Ph sensor and temperature 27
Figure 4.3: The effects of temperature on other water quality parameters
Figure 4.4:values of the sensor from the web browser
Figure 4.5: Testing the turbidity and temperature of the water
Figure4.6: Testing Turbidity of water with high turbidity values

LIST OF TABLES

viii
Table 4.1: Value of water ionization constant and ph with increasing temperature

LIST OF ABBREVIATIONS
IoT Internet of Thing

PH Potential of Hydrogen

TDS Total Dissolved Solids

TSS Total Suspended Solids

LAMP Linux, Apache, MySQL

SQL Structured Query Language

WIFI Wireless Fidelity

ADC Analog to Digital Converter

HDMI High-Definition Multimedia Interface

GPIO General-Purpose input/output

USB Universal Serial Bus

CSI Camera Serial Interface

DSI Display Serial Interface

SD Secure Digital

nodeMCU Node Microcontroller Unit

RISC Reduced-Instruction-set Computing

CPU Central Processing Unit

UARTs Universal Asynchronous Receiver-Transmitter

SPI Serial Peripheral Interface

I2C Inter-Integrated Circuit

ix
SRAM Static Random-Access Memory

TTL Transistor-Transistor logic

PCB Printed Circuit Board

IDE Integrated Development Environment

SPO Standard operating procedure

NTU Nephelometric Turbidity Unit

PWM Pulse width modulation

PHP Hypertext Preprocessor

HTML Hypertext Markup Language

CSS Cascading Style Sheets

VCC Voltage at the Common Collector

GND GROUND

LED Light Emitting Diode

DO Dissolved Oxygen

x
xi
CHAPTER ONE
INTRODUCTION

Water is an essential resource used for various purposes such as drinking, recreation, or food
processes. Humans, Animals, and plants need water for their survival. Plants prepare their food
in photosynthesis that requires water to make a reaction. The human body contains 70% of water
so a human cannot survive without water. Humans must drink at least six glasses of water per
day for a good digestion system and body metabolism. Water must be of good quality so we have
to keep water from any contamination that can be contaminated by animal faces, wastes from
industries, and by human beings. Millions of people are exposed to unsafe concentrations of
chemical contaminants in their drinking water [9]. This contamination may be linked to naturally
occurring inorganic chemicals such as arsenic and fluoride, which cause cancer and tooth and/or
skeletal damage [9].

According to a report by the Central Statistical Agency of Ethiopia based on results from the
2016 Socioeconomic Survey [8], over 66 percent of the Ethiopian population reported usually
using an improved water source during rainy and dry seasons. In rural areas, 59 percent of the
population reported using improved drinking water sources, a quarter of which are piped [8]. The
most common types of improved sources in rural areas are protected springs, tube wells, and dug
wells. The use of improved drinking water sources varies by region: almost all households in
Addis Ababa and 72 percent in Tigray reported currently using improved sources, compared to
the national average of 66 percent [8].

Determining water quality is an essential thing nowadays, but any of the conventional water
quality monitoring technologies that lack integration, are labor-intensive, time-consuming, and
expensive. In Ethiopia, the way to monitor water quality in survey design (sampling and
stratification). Therefore, low-cost, highly sensitive, accurate, reliable, easy-to-use, and
integrated sensing systems are needed for the regular/continuous monitoring of multiple water
quality parameters in multiple locations to ensure continued water safety.

1
Now a day’s Internet of things is a revolutionary technological phenomenon. IoT (Internet of
Things) is made up of devices – from simple sensors to smartphones and wearables – connected. It is
shaping today's world and is used in different fields for collecting, monitoring, and analysis of
data from remote locations. It can be applied to detect forest fires and early earthquakes, reduce
air pollution, monitor snow levels, prevent landslides and avalanches, etc. Moreover, it can be
applied for monitoring water quality.

Our project focuses on monitoring water quality using interdependent physical and chemical
factors, including turbidity sensor, temperature, sensor PH sensor, and servo motor controller.
We mainly focus on temperature and turbidity factors. We use an integrated sensing system,
which could simultaneously measure the temperature and turbidity of water samples. We
integrated these sensors with nodeMCU. It can record measured values of these sensors and pass
these values to the server which is Raspberry-Pi in our project. Consequently, any user can
access it through a web application. This system is an easy and low-cost system.

1.1 Problem statement

Water pollution is the contamination of water that occurs when pollutants are directly or
indirectly discharged into water bodies without adequate treatment to remove the harmful part. It
will give an effect on the ecosystem and human life and become an issue nowadays. One of
mankind’s biggest global challenges is access to potable water supply, its availability, quality,
and governance [17].

In Ethiopia, Due to increasing population and lack of proper water resources management, water
quality is becoming a major problem. Problems like siltation that occurs due to degradation of
watersheds, and also most of the existing industries' and major towns within the upper watershed
have no treatment plants for the discharge of their wastes [7]. Many communities in the country
use unprotected water sources. Rural communities mostly use unprotected springs and hand-dug
wells. Other groundwater sources for some communities include shallow-drilled wells, deep-
drilled wells, ponds, lakes, streams, and rivers [2]. Roof water-harvesting techniques are used to
capture rainwater when there is rain. These sources are exposed to contamination from human
activities and naturally occurring events. The biological contamination usually originates from
human and animal wastes. There is also a potential health risk of re-contamination during

2
collection, transportation, storage, and unsafe drawing cups at the household level. The potential
contamination also includes physical and chemical hazards. The physical impurities affect the
palatability of the drinking water due to the bad smell, odor, and unsightliness of the water [2]

Recent statistics on water and sanitation do not provide specific evidence about the quality of
water being provided to communities’ households and institutions. The systems applied to
monitoring water quality lack integration, are labor-intensive, time-consuming, and expensive.
One such approach used is survey design (sampling and stratification). Therefore, a simple, more
accurate, more efficient, and cost-effective system to monitor water quality is needed.

1.2 OBJECTIVE

1.2.1 General objectives

The general objective of this project is to design a system that helps to monitor the quality of
water, that is to know the physical, chemical, and biological status of water resources remotely
by using IoT (Internet of Things) which connects devices to the internet and the ability to
transfer data over a network. This system provides a more accurate, efficient, and cost-effective
water monitoring system and helps the controller (The person authorized to monitor the water
quality) to ensure the water is free from pollutants and to take necessary actions otherwise.

1.2.2 Specific objectives

❖ To develop an IoT based water quality monitoring system


❖ To assess (evaluate or estimate) the quality of the existing water
❖ To identify the change in water quality parameters
❖ To access and control water quality information remotely

3
1.3 Significances of the project

A water quality monitoring system helps us to determine whether or not we are making progress
in cleaning up our waterways and keeps us informed about your building’s water quality at all
times. It reveals the health and composition of water that we drink daily. It is also a crucial part
of identifying any existing problems in the quality of water. It is used to notify the current and
ongoing problems to determine compliance with drinking water standards and it prevents any
hazard that occurs in water reservoirs like adding poisonous substances by humans.

1.4 Scope and limitation

This project is about monitoring water quality by using IoT which emphasizes the water we are
using for drinking and cooking. This project can work from a small town to the overall country.
But because of time and final limitations, this project only considers the cities' drink water, and
also only two sensors are used for demo purposes. In this project, only two sensors (Temperature
and Turbidity) which measure the temperature and clarity of water respectively are used even if
there are a lot of parameters to measure water quality because of financial problems since
sensors used for water quality measurement are expensive. But we have tried to make a relation
how these two sensor values affect other water quality measurements like PH, TDS.

4
CHAPTER TWO

LITERATURE REVIEW

Water quality monitoring has gained more interest among researchers nowadays. Globally,
Numerous works are either done or ongoing on this topic focusing on various aspects of it. The
main aim of most projects was to develop an efficient, cost-effective, real-time water quality
monitoring system, which will integrate wireless sensor networks and the internet of things. But
in Ethiopia, there is almost no research found for water quality management using IOT, even
there is not much research found for water quality management.

The Ethiopian Federal Ministry of Health, as a surveillance agency of assuring water quality,
working to address the gaps seen in water quality monitoring and surveillance [2]. Besides the
improvements of safe water coverage in the country, there could be some mechanism to ensure
drinking water quality and safety from source to consumption [2]. As a result, the development
of water quality monitoring was envisioned as an important step as a requirement for subsequent
development of detailed guidelines and implementation manuals to be used at all levels [2].

In [1], N. VijayKumer and R Ramya [2013] developed a system for real-time monitoring of the
water quality parameters. In their system, the measure of water parameters such as turbidity,
conductivity, temperature, pH, dissolved oxygen is connected to the core controller. They use the
raspberry pi as a controller and send the sensor data on cloud platforms. The final result of
selecting water quality parameters that contains information about each parameter is accessed
using a web server.

In [4], Bharati Sengupta et al [2019]. developed a system for water quality monitoring using IoT.
They use several sensors such as PH sensor, Turbidity sensor, and Temperature sensor. They use
ADC for PH and Turbidity sensors to interface with Raspberry Pi because they are analog and
Temperature sensors directly with Raspberry Pi. The data stored in the Raspberry Pi database is
sent to a web server.

5
In [3], Bishwajit paul studied sensor-based water monitoring systems. This research paper used
sensors such as temperature sensors, flow sensors, PH sensors, and water level sensors. A
microcontroller is used as a sensor node, which stores real-time data and sends the data to the
cloud storage via Wi-Fi.

In [6], Yiheng Qin, Arif U. Alam, and others developed a water monitoring system by using PH,
temperature, and chloride sensors.

In [5], A.N. Prasad, and others. This paper presents a smart water quality monitoring system
using IoT and remote sensing technology; this system consists of four water quality parameters
and microcontrollers for processing data, and GSM technology has been successfully
implemented to send an alarm based on reference parameter to the ultimate user for immediate
action to ensure water quality.

6
CHAPTER THREE

METHODOLOGY AND SYSTEM DESIGN

3.1 Proposed System

Parameters of water quality include chemical, physical, and biological properties and can be
tested or monitored based on the water parameters of concern that are desired. The physical
and chemical parameters which are frequently sampled or monitored for water quality include
pH Sensor, turbidity sensor, temperature sensor, TDS Sensor, Fluorine sensor, chlorine sensor,
dissolved oxygen sensor, carbon dioxide sensor, and conductivity sensor.
In this proposed system the NodeMCU (open-source firmware developed for the ESP8266 wifi
chip) is used for collecting data of the water parameters like temperature, Turbidity sensors and
sending it to the server using the Esp8266 WIFI module. And then the user (the authorized
person) can access the data using a web app developed for this purpose and see the parameters of
water by selecting the view he wants to see that is, the viewer can select the table form, graph
form or he can select both to see both on the same screen.
This system also designs to stop the water flow to the public if the water quality is below the
minimum standard set for drink water, and then it shows the warning to the controller (the person
who controls the water quality at the office).

Figure3.1 System Design of water Quality Management System Using IoT

7
In this system, the water storage is equipped with sensors such as pH Sensor, turbidity sensor,
temperature sensor, TDS sensor, Florine sensor, chlorine sensor, dissolved oxygen sensor,
carbon dioxide sensor, conductivity sensor monitors. These sensors capture data and send it to
the nodeMCU development board that has its onboard analog to digital converter that translates
the sensor analog signals into the digital format for further study. And then the sensor data is
processed by the MCU and updated to the internet using the Wi-Fi data communication module
ESP8266 (NodeMCU) to the webserver page which allows us to monitor and control the system
and then to the central database server that helps us to store the structured information. By
entering the IP address the authorized users can access these data through a browser after
authentication using a username and password. For this project, we used Raspberry pi B+ (a
series of low-cost, programmable computers) as a server for both web and database servers by
installing the LAMP MySQL database.

Figure 3.2: - login system for website

In normal conditions after logging in the user is going to choose which reservoir data he wants to
see since there will be more than one reservoir. If the water quality is less than the standard set
by the authorities, the alarm will warn the authorized controller.

8
3.2 Block Diagram of the System

Figure 3.3: - Block Diagram of the system

In this project, we present the theory on real-time monitoring of water quality in the IoT
environment. The elements of the hardware design of the system are explained below.

3.2.1 Raspberry Pi B+
The Raspberry Pi is a low cost, small size computer that plugs into a computer monitor or TV,
and uses a standard keyboard and mouse. It is a capable little device that enables people of all
ages to explore computing and to learn how to program in languages like Scratch and Python. It's
capable of doing everything you'd expect a desktop computer to do, from browsing the internet
and playing high-definition video, to making spreadsheets, word-processing, and playing games.

Specification:

The Raspberry Pi 3 Model B+ is the final revision in the Raspberry Pi 3 range.

● Broadcom BCM2837B0, Cortex-A53 (ARMv8) 64-bit SoC @ 1.4GHz


● 1GB LPDDR2 SDRAM
● 2.4GHz and 5GHz IEEE 802.11.b/g/n/a wireless LAN, Bluetooth 4.2, BLE

9
● Gigabit Ethernet over USB 2.0 (maximum throughput 300 Mbps)
● Extended 40-pin GPIO header
● Full-size HDMI
● 4 USB 2.0 ports
● CSI camera port for connecting a Raspberry Pi camera
● DSI display port for connecting a Raspberry Pi touchscreen display
● 4-pole stereo output and composite video port
● Micro SD port for loading your operating system and storing data
● 5V/2.5ADC power input
● Power-over-Ethernet (PoE) support (requires separate PoE HAT)

In this project, we use Raspberry Pi as a server that accepts recorded measurement values of
sensors from nodeMCU and it stores them in its database. It provides stored data when it accepts
requests/invocations by clients.

Figure 3.4: - Raspberry Pi B+

3.2.2 NodeMCU ESP8266

10
NodeMCU is a low-cost open-source IoT platform. It initially included firmware (a small piece
of software that makes hardware work) which runs on the ESP8266 Wi-Fi SoC from Expressive
Systems and hardware which was based on the ESP-12 module. Later, support for the ESP32 32-
bit MCU was added.

NodeMCU ESP8266 Specifications & Features:

● Microcontroller: Tensilica 32-bit RISC CPU Xtensa LX106


● Operating Voltage: 3.3V
● Input Voltage: 7-12V
● Digital I/O Pins (DIO): 16
● Analog Input Pins (ADC): 1
● UARTs: 1
● SPIs: 1
● I2Cs: 1
● Flash Memory: 4 MB
● SRAM: 64 KB
● Clock Speed: 80 MHz
● USB-TTL based on CP2102 is included onboard, Enabling Plug n Play
● PCB Antenna
● Small Sized module to fit smartly inside your IoT projects

11
Figure 3.5: NodeMCU ESP8266

Our project is compatible with ESP8266 boards. We program the ESP8266 using Arduino IDE.
We assemble a proper circuit and upload the sketch provided to insert sensor value into our
database within a given time.

3.2.3 DS18B20 Temperature sensor

Increasing the temperature will also increase the vapor pressure of trace volatiles in drinking
water and, therefore, could lead to increased odor [10]. It is also possible that micro fungi can
grow inside the internal plumbing systems of buildings, leading to complaints of musty, earthy,
or moldy tastes and odors if the temperature rises above approximately 16°C. It is advisable to
keep the growth of such organisms to a minimum by using cold water because certain organic
growths have been shown to protect bacteria from the effects of chlorination.

In the Water Quality Guidelines, it states, “the temperature dependence of most chemical
reactions stems from the activation energy associated with them [10]. The relative concentrations
of reactants and products in chemical equilibria can also change with temperature [10]. If you

12
drink chilled water, there is a temperature mismatch that takes a toll on your digestive health.
Your body also finds it difficult to absorb cold water after a workout. Drinking chilled water
right after a workout may lead to chronic stomach pain as extremely cold water shocks your
body. Temperature can, therefore, affect every aspect of the treatment and the delivery of potable
water [11].

Temperature sensors are instruments that measure the degree of hotness and coolness and
convert it into a readable unit (Celsius, Fahrenheit, or Kelvin) through electrical signals.
Measuring the temperature of the water is accomplished through specialized temperature sensors.
In this project, we use a waterproof DS18b20 temperature sensor.

DS18B20 Sensor Specifications

● Programmable Digital Temperature Sensor


● Communicates using the 1-Wire method
● Operating voltage: 3V to 5V
● Temperature Range: -55°C to +125°C
● Accuracy: ±0.5°C
● Output Resolution: 9-bit to 12-bit (programmable)
● Unique 64-bit address enables multiplexing
● Conversion time: 750ms at 12-bit
● Programmable alarm options
● Available as To-92, SOP, and even as a waterproof sensor

13
Figure 3.6: DS18B20 Temperature sensor

3.2.4 Turbidity Sensor

The Turbidity Sensor is an electronic monitoring module specially developed to work with
microcontroller platforms Arduino, Raspberry Pi, PIC, and among others. It can measure and verify the
clarity of the water. The turbidity sensor is analog. Its analog values are sent to NodeMCU which has
ADC (Analog Digital converter), so its values convert to digital values.

Turbidity is the measure of relative clarity of a liquid [18]. It is an optical characteristic of water
and is a measurement of the amount of light that is scattered by material in the water when a
light is shined through the water sample [18]. Turbidity value is measured in terms
of NTU which is called Nephelometric Turbidity Units [12]. The measurement of turbidity is a
key test of water quality. Turbidity is caused by particles suspended or dissolved in water that
scatter light making the water appear cloudy or murky [12]. Particulate matter can include
sediment, especially clay and silt, fine organic and inorganic matter, soluble colored organic
compounds, algae, and other microscopic organisms [12].

14
Figure 3.7: Turbidity level of water

Specification

❖ Operating Voltage:5V DC
❖ Operating current: 40mA (MAX)
❖ Response Time: <500ms
❖ Insulation Resistance: 100M(Min)
❖ Output Method: Analog
❖ Analog output: 0 - 4.5V
❖ Digital output: High/Low-level signal (it can be adjusting the threshold value by
adjusting the potentiometer)

Figure 3.8: - Turbidity Sensor

3.2.5 Micro ServoMotorSG90

15
Micro Servomotor (SG90) is Small size and lightweight. With 3 sets of servo horns and fittings.
Which have High quality and the high-cost performance servo motor with high output power.
The servo can rotate approximately 180 degrees (90 in each direction) and works just like the
standard kinds but smaller.

In this project, the servo motor controls the water According to the value received from the
sensors about water quality and the servo motor will automatically turn on/off the pump the
water from the tank or close it. When the condition of the water quality is below a minimum
quality the servo motor is off and when the condition of water quality is above minimum level
(in a good condition) the servo motor is on.

Figure 3.9: - Micro servo motor 9g SG90

Specification micro servo motor 9g SG90:

● Item Name: SG90 Digital Servo


● Weight: 9g
● Dimension: 23 × 12.2 x 29mm
● Stall torque: 1.8kg/cm
● Gear: Nylon gear set
● Operating Speed: 0.1sec/60degree
● Operating Voltage: 3-6V DC
● Drive Method: PWM
● PWM Range: 500 to 2400 microseconds
● Speed: 60 degrees in 0.12 s
● Torque: 1.2 kg / cm
● Servo Wire Length: 24 cm

16
● Servo Plug: 3-Pin JR (Fits JR and Futaba)
● Connections: Brown: Ground, Red: 5 V, Orange: PWM

3.3 Software Implementation

The proposed system has implemented Raspbian (an operating system for the raspberry pi),
MySQL database to store structured data, PHP to code server-side program, the LAMP server
that allows us to store sensor readings from the ESP8266, Json to show the value of the sensor in
graphical form, Arduino ide to code client-side program on nodeMCU development board and
read the sensor's value and then send the values to the server. We also use HTML and CSS code
to develop web applications for the user interface. Different libraries like One Wire, Dallas
Temperature, ESP8266WiFi, are also used to read temperature and to connect to wifi.

17
Figure 3.10: - Flow chart of the system

3.4 Hardware Implementation

3.4.1 Interface of Temperature Sensor with NodeMCU

The temperature sensor (DSP20B18) integrates with NodeMCU, it measures the temperature of the water
and sends the measured value to NodeMCU. The Temperature sensor uses the one-wire protocol to
transfer all its information. 1-wire interface is a bidirectional, half-duplex slow serial communication
standard [15]. It does not use any clock signal.

The temperature sensor can be powered in two ways. One is parasitic when only two wires need to go to
the chip and external supply when an extra wire carrying the power for the sensor. The two powering
modes are explained as follows [15].

Parasite power mode: When operating in parasite power mode, only two wires are required: one data
wire, and ground [15]. In this mode, the power line must be connected to the ground. At the master, a
4.7k pull-up resistor must be connected to the 1-wire bus.

Normal (external supply) mode: With an external supply, three wires are required: the bus wire, ground,
and power [15]. The 4.7k pull-up resistor is still required on the bus wire.

Figure 3.11: Color representation of temperature sensor

Connection or integration of temperature sensor (DSP20B18) with NodeMCU ESP8266 board is


as follows: as seen in figure …….

● Firstly, set up NodeMCU and the Temperature sensor on the breadboard.

● Vcc pin to 3.3v of NodeMCU or can be connected to external 5v

18
● GND pin to GND of NodeMCU

● Output pin to digital pin of NodeMCU (D2)

● We also add the 4.7k pull-up resistor between the signal and the power pin to keep the
data transfer stable.

Figure 3.12 interfacing temperature sensor with nodemcu

So, whatever the temperature of the surrounding is, (DSP20B18) will read and pass it to
NodeMCU through (D2) pin, further, the board processes that data from (DSP20B18) and send it
to Server (server on Raspberry Pi) so that we can easily access the data from anywhere and will
able to take decision based on the data value.

3.4.2 Turbidity Sensor Interface with NodeMCU

It has two parts, transmitter and receiver, the transmitter consists of a light source typically a led
and a driver circuit [19]. In the receiver end, there is a light detector like a photodiode or an
LDR. We place the solution in between the transmitter and receiver [19].

Transmitter simply transmits the light, that light waves pass through the solution and the receiver
receives the light [19]. The transmitted light is completely received if there is nothing between
them. The amount of light received by the receiver is very low if there is a solution between a
receiver and a transmitter. That is on the receiver side, we get only a low-intensity light and this
intensity is inversely proportional to turbidity. So, we can measure the turbidity by measuring the

19
light intensity if the light intensity is high, the solution is less turbid(clear) and if the light
intensity is very low that means the solution is more turbid.

Figure3.13: -Parts of Turbidity Sensor

Turbidity sensor integrated with NodeMCU as follows.

❖ The module is to be connected to NodeMCU using three pins only: Vcc, GND, and
SIGNAL.
❖ Connect the Vcc of the Turbidity Sensor with NodeMCU Vin, GND to GND & Analog
Output to NodeMCU (A0) pin.

Figure 3.14 interfacing turbidity with nodeMCU

3.4.3 Interfacing servo motor with NodeMCU

Steps to interface Servo Motor with NodeMCU:

20
Connect the Red wire to the 5V on nodeMCU and Black/Brown wire to the ground. Finally,
connect the Orange/Yellow wire to the PWM enabled pin.

1.Connect the red wire to the 3.3V on NodeMCU

2. Connect the Black wire to the ground of nodeMCU

3. Connect Yellow wire to the PWM to enable pin


∙ Figure 3.15: - Interfacing Servo Motor with nodeMCU

∙ CHAPTER FOUR

RESULT AND DISCUSSION

4.1 The relationship between turbidity TDS and TSS

Turbidity is determined by the amount of light scattered off of these particles. While this
measurement can then be used to estimate the total dissolved solids concentration, it will not be
exact. Turbidity does not include any settled solids or bedload (sediment that “rolls” along the
riverbed) [16]. Total suspended solids, on the other hand, are a total quantity measurement of
solid material per volume of water. This means that TSS is a specific measurement of all
suspended solids, organic and inorganic, by mass. TSS includes settleable solids and is the direct
measurement of the total solids present in a water body [16].

21
Figure 4.1: - Relationship between turbidity, TSS, and TDS

The above figure shows While turbidity and total suspended solids often overlap, there are a few
outlying factors that only contribute to one or the other.

Turbidity and TSS are the most visible indicators of water quality. While some streams can have
naturally high levels of suspended solids, clear water is usually considered an indicator of
healthy water. A sudden increase in turbidity in a previously clear body of water is a cause for
concern. Excessive suspended sediment can impair water quality for aquatic and human life,
impede navigation and increase flooding risks [16].

In terms of water quality, high levels of total suspended solids will increase water temperatures
and decrease dissolved oxygen (DO) levels.

1. This is because suspended particles absorb more heat from solar radiation than water
molecules will. This heat is then transferred to the surrounding water by conduction.
Warmer water cannot hold as much dissolved oxygen as colder water, so DO levels will
drop. Besides, the increased surface temperature can cause stratification, or layering, of a
body of water [16].
2. When water stratifies, the upper and lower layers do not mix. As decomposition and
respiration often occur in the lower layers, they can become too hypoxic (low dissolved
oxygen levels) for organisms to survive.

The water samples with high turbidity levels had lesser amounts of dissolved oxygen, whereas

22
lower turbidity resulted in more dissolved oxygen concentration in the water sample. Turbidity
and dissolved oxygen are inversely related. The more turbidity, the less dissolved oxygen there is
for living organisms to breathe, negatively affecting animal populations. Human impact has
played an extensive role in keeping the turbidity levels high in these water samples [16].

4.2 The effect of temperature sensor on other water quality parameters

Temperature plays a significant role in PH measurements. A PH value without a temperature value is


incoherent. When the temperature rises or falls affects molecular vibrations that increase with temperature
rises and decrease with temperature falls. Therefore, the temperature is directly proportional to molecular
vibrations. Increasing molecular vibration results in the ability of water to ionize and form more hydrogen
ions. As a result, the pH will drop. The PH will rise when there is a decrease in molecular vibration [13].

PH sensor is the sensor used to measure the PH of a liquid or solid substance. PH is described as
the "negative logarithm" of hydrogen ion concentration in water [14].

PH=-log [H+].

The dissociation of water into hydrogen and hydroxide ion can be represented as:

H2O (l) ⇌ H+ (aq) + OH− (aq)

Every solution will change its pH value through temperature changes. A difference in PH measurements
at different temperatures is NOT an error! The new pH level simply tells us about the true PH for that
solution at that specific temperature [13].

The value of Kw (Water ionization constant) and PH with increasing temperature

23
Table 4.1: - Value of water ionization constant and ph with increasing temperature

Typical PH values for solutions at different temperatures. As we can see from the table the PH value of
water decreases with the increase of temperature. To get your best results in pH measurement, always
remember to calibrate and measure at the same temperature.

Figure 4.2: Relationship between PH sensor and temperature

The PH of pure water varies with temperature while remaining perfectly neutral. Pure water only has a
pH of 7.0 at 25 degrees Celsius. However, that does not mean the temperature changes will make a
solution more acidic or basic. Because the ratio of hydrogen and hydroxyl ions remains the same, the
acidity of water does not change with temperature. Instead, the entire PH range shifts, so that neutral
water will have a value other than 7.00. Pure water will remain neutral at 0°C (pH is 7.47), 25°C. (PH is
7.00) or 100°C. (PH is 6.14) [13].

24
Figure4.3: - The effects of temperature on other water quality parameters.

Water temperature affects nearly every other water quality parameter.

Temperature is an important factor to consider when assessing water quality. In addition to its effects,
Temperature influences several other parameters and can alter the physical and chemical properties of
water [14]. In this regard, water temperature should be accounted for when determining:

• Metabolic rates and photosynthesis production

• Compound toxicity

• Dissolved oxygen and other dissolved gas concentration

• Conductivity and salinity

• Oxidation Reduction Potential (ORP)

• PH

• Water Density

4.3 Result

In our project, we have tested different water samples to check their turbidity and temperature
measurement values.

For turbidity measurement, Tests were carried out on different samples that had different
amounts of suspended particles and pure water from bottled water to test the functionality of the
prototype. These samples exhibited the performance of the system under good and bad
conditions of water samples.

25
Figure 4.4: values of the sensor from the web browser

26
Figure 4.5: Testing the turbidity and temperature of the water

Figure 4.6: Testing Turbidity of water with high turbidity values

To measure the turbidity of water which comes from a pipe, a Turbidity Sensor was placed
inside the water as shown in Figure-4.5 and 4.6, and the result is observed on the pc using the
web browser. In our system, the test in Figure- 4.5 is considered safe for drinking. Hence, the
overall status of the water sample is good.

On the other hand, polluted mud water is tested as shown in Figure-4.6 and is considered as not
safe turbidity of drinkable water, then this status of the water sample is bad so that the servo
motor will rotate to show that the water pump is closed.

For temperature measurement, we tested water taken from different environments. Frigid water,
water at room temperature, and hot water. The temperature sensor shows which water is good for
health and which is not.

The temperature sensor measures water temperature placed inside the water tank as shown in
Figure-4.5. Then the result was observed through a web browser. If the temperature of the water

27
is in the range (5-26) is affordable for drinking. If the temperature is out of the acceptable range
then it is not safe, so that the servo motor will rotate to show that the water pump is closed.

CHAPTER FIVE

CONCLUSION AND SCOPE FOR FUTURE WORK

5.1 Conclusion

Generally, the developed system can monitor water quality automatically by sensing the turbidity
and temperature of the water and then sends the value to the server. This system can also stop the
flow of water to the user if the status of water is above the threshold value (the status of the water
is not safe). And then the authorized user can see remotely using any web browser through an IP
address. It is low in cost, efficient and it reduces manpower. This system has good flexibility, it
can be used to monitor other water quality parameters like the PH sensor, TDS sensor, and others
only by adding additional sensors and relevant software programs. This system can also be
expanding to monitor lakes, rivers, and another water source,

28
5.2 Future work

This project can be extended into detecting more water quality monitoring by increasing the
parameter (addition of multiple sensors) for safe and more secure purposes, we can also work on
GSM that is used to warn the authorities remotely even if they are not in the office if the water
quality is below the given standard. And also, machine learning can be used in addition to IoT to
check water quality parameters and predicting when to clean the water.

REFERENCE

[1] N.VijayaKumar, R Ramya, "The Real-Time Monitoring of Water Quality in IoT


Environment",2013.

[2]. FMoH (2011) National Drinking Water Quality Monitoring and Surveillance Strategy Addis
Ababa: Ministry of health.

[3]. Bishwajit Paul, "Sensor-Based Water Quality Monitoring System", BANGLADESH,


August 2018

[4]. Bharati Sengupta et al, "Water Quality Monitoring using IoT", IJIEEE, June 2019
[5]. A.N.Prasad, et al "Smart Water Quality Monitoring System" Laucala, Fiji Islands, December
2015

[6] Yiheng Qin, Arif U, et al, “Integrated Water Quality Monitoring System with PH, free

29
chlorine and temperature sensor”, August 2017

[7]. Minister of Water, Irrigation and Energy, accessed October 2020,


http://mowie.gov.et/information/-/asset_publisher/XHdTAvLmoOIv/content/existing-water-
quality-situation-in-ethiopia?
_101_INSTANCE_XHdTAvLmoOIv_cur=0&_101_INSTANCE_XHdTAvLmoOIv_page=2

[8]. Biratu Yigezu, “Drinking water Quality in Ethiopia”, Central Statistical Agency of Ethiopia,
Addis Ababa, 2017

[9]. Kebede Worku, "National Drinking Water Quality Monitoring and Surveillance Strategy",
FMoH, Addis Ababa,2014

[10]. Safe Drinking Water Foundation. (2018, Nov. 8), water temperature [online]. Available:
https://www.safewater.org/fact-sheets-1/2018/8/15/water-temperature-fact-sheet#:~:text=The
%20intensity%20of%20taste%20is,could%20lead%20to%20increased%20odour

[11]. Kent.(2019,oct.12). Drinking Chilled Water Affects your Body[online]. Available:


https://www.kent.co.in/blog/5-ways-drinking-chilled-water-affects-your-body/#:~:text=If
%20you%20drink%20chilled%20water,cold%20water%20shocks%20your%20body

[12]. Electronics (2020.sept.6). DIY Turbidity Meter using Turbidity Sensor & Arduino[online].
Available: https://how2electronics.com/diy-turbidity-meter-using-turbidity-sensor-arduino/

[13]. West lab, (2017, Nov.17). “How Does Temperature Affect pH?"[online]. Available:
https://www.westlab.com/blog/2017/11/15/how-does-temperature-affect-ph

[14]. Foundries Environmental, Inc. (7 Feb. 2014.) “Water Temperature.” Fundamentals of


Environmental Measurements. Web. Available: https://www.fondriest.com/environmental-
measurements/parameters/water-quality/water-temperature/.

[15]. Arduino.cc, (). “Dallas Semiconductor's 1-Wire Protocol”[online]. Available:


https://playground.arduino.cc/Learning/OneWire/

30
[16]. Foundries Environmental, Inc. (13 Jun. 2014) “Turbidity, Total Suspended Solids, and
Water Clarity." Fundamentals of Environmental Measurements. Web. <
https://www.fondriest.com/environmental-measurements/parameters/water-quality/turbidity-
total-suspended-solids-water-clarity/ >.

[17]. Maxwell Musingafi, et al,” Litmus Test for Integrated Resource Management of Potable
Water in Zimbabwe and south Africa”,2014

[18].USGS science for changing world, “Turbidity and Water”[online],available:


https://www.usgs.gov/special-topic/water-science-school/science/turbidity-and-water?qt-
science_center_objects=0#qt-science_center_objects

[19].Circuit Digest,(2020. oct,5), “Measuring Turbidity of Water to Determine Water Quality


using Arduino and Turbidity Sensor”, [online]
,Avaliable:https://circuitdigest.com/microcontroller projects/measuring-turbidity-of-water-to-
determine-water-quality-using-arduino-turbidity-sensor

APPENDIX

1) The following is Client-Side code used to read the sensor value and send
to the server:

#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Wire.h>
#include <Servo.h>
//////////////////////////////Variable declaration//////////////////////////////////////////////////
const char* ssid = "@pt";
const char* password = "20132021";
const char* serverName = "http://10.2.96.47/water-data.php";
String apiKeyValue = "tPmAT5Ab3j7F9";
String sensor1Name = "Turb";

31
String sensor2Name = "Temp";
String sensorLocation = "Ginchi";
const int oneWireBus = 4;
const int LED = 14;
int sensorPin = A0;
float volt;
float ntu;
//String safety;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
Servo myservo;
// Setup a one-wire instance to communicate with any One Wire devices
One Wire oneWire(oneWireBus);
// Pass our one wire reference to the Dallas Temperature sensor
Dallas Temperature sensors(&oneWire);

///////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(115200);
myservo.attach(2); // attaches the servo on GIO2 to the servo object
sensors.begin();
WiFi.begin(ssid, password); //your wi-fi name and password
Serial.println("Connecting");
//check for successful connection
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////

32
//print the IP if connection is successful
////////////////////////////////////////////////////////////////////////////////////////////////////////
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
////////////////////////////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{
if(WiFi.status()== WL_CONNECTED) //Check WiFi connection status
{
HTTPClient http;
http.begin(serverName); // Your Domain name with URL path or IP address //with path
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // Specify content-
type header
float TurbSensorVal = ReadTurbidity(TurbSensorVal);
float TempSensorVal = ReadTemprature(TempSensorVal);
String sensStatus = alert(sensStatus);

//Prepare your HTTP POST request data


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/
String httpRequestData = "api_key=" + apiKeyValue + "&location=" + sensorLocation +
"&sensor1=" + sensor1Name
+ "&value1= " + String(TurbSensorVal) + "&sensor2=" + sensor2Name +
"&value2= " + String(TempSensorVal) + "&sensStatus= " + sensStatus + "";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
Serial.print("httpRequestData: ");
Serial.println(httpRequestData);

33
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int httpResponseCode = http.POST(httpRequestData); // Send HTTP POST request
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Serial.println("//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////");
//show the response if the post is succeessful
if (httpResponseCode>0)
{
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.print("The Status of the water: ");
Serial.println(sensStatus);
}
//show error if the post is not succeessful
else
{
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else
{
Serial.println("WiFi Disconnected");
}
MotorControl();
ledConrol();
Serial.println("//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////");
//Send an HTTP POST request every 12 seconds

34
delay(12000);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Read the temperature sensor value
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float ReadTemprature(float temperatureC )
{
sensors.requestTemperatures();
temperatureC = sensors.getTempCByIndex(0);
return temperatureC;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Read the turbidity sensor value


////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float ReadTurbidity(float ntu)
{
volt = 0;
for(int i=0; i<800; i++)
{
volt += ((float)analogRead(sensorPin)/1023)*5;
}
volt = volt/800;
volt = round_to_dp(volt,2);
if(volt < 2.5){
ntu = 3000;
}

35
else
{
ntu = -1120.4*sq(volt)+5742.3*volt-4353.8;
}

Serial.print("Turbidity Sensor value output in Voltage is: ==> ");


Serial.println(volt);
Serial.print("Turbidity Sensor value in NTU output is: ==> ");
Serial.println(ntu);
return ntu;

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//round the turbidity value to two decimal place


////////////////////////////////////////////////////////////////////////////////////////////////////////////////

float round_to_dp( float in_value, int decimal_place )


{
float multiplier = powf( 10.0f, decimal_place );
in_value = roundf( in_value * multiplier ) / multiplier;
return in_value;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//control the water pump depending on sensors value


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void MotorControl()
{

36
int pos=0;
float Turbidity = ReadTurbidity(Turbidity);
float Temprature = ReadTemprature(Temprature);
if((Turbidity>2940&&Temprature>26)||(Turbidity<=2940&&Temprature>26)||
(Turbidity>2940&&Temprature<=26)||(Turbidity>2940&&Temprature<=5))
{
for (pos = 180; pos >= 0; pos -= 1)
{ // goes from 180 degrees to 0 degrees
myservo.write(pos);
//delay(15);
}
}
else
{
for (pos = 0; pos <= 180; pos += 1)
{ // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos);
//delay(15);
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//to control led using the sensors value
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////
void ledConrol()
{
float Turbidity = ReadTurbidity(Turbidity);

37
float Temprature = ReadTemprature(Temprature);
if((Turbidity>2940&&Temprature>26)||(Turbidity<=2940&&Temprature>26)||
(Turbidity>2940&&Temprature<=26)||(Turbidity>2940&&Temprature<=5))
{
digitalWrite(LED, HIGH);
}
else
{
digitalWrite(LED, LOW);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////
//check sensor status
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
String alert(String sensStatus)
{
float Turbidity = ReadTurbidity(Turbidity);
float Temprature = ReadTemprature(Temprature);
if((Turbidity>2940&&Temprature>26)||(Turbidity<=2940&&Temprature>26)||
(Turbidity>2940&&Temprature<=26)||(Turbidity>2940&&Temprature<=5))
{
sensStatus="!NotSafe";

else
{
sensStatus="Safe";

38
return sensStatus;
}

////////////////////////////////////////////////////////////////////////////////////////////////////

2) The following is the server-side php code written to receive the value
from the client:
<?php
$servername = "localhost";
// Database name
$dbname = "nimona";
// Database user
$username = "admin";
// Database user password
$password = "123";
// Keep this API Key value to be compatible with the ESP32 code provided in the project page.
// If you change this value, the ESP32 sketch needs to match
$api_key_value = "tPmAT5Ab3j7F9";
$api_key = $location = $sensor1 = $value1 = $sensor2 = $value2 = $sensStatus"";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$api_key = test_input($_POST["api_key"]);

39
if($api_key == $api_key_value) {
$location = test_input($_POST["location"]);
$sensor1= test_input($_POST["sensor1"]);
$value1 = test_input($_POST["value1"]);
$sensor2 = test_input($_POST["sensor2"]);
$value2 = test_input($_POST["value2"]);
$sensStatus = test_input($_POST["sensStatus"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

//insert data to the corresponding server column


$sql = "INSERT INTO SensorData (location, sensor1, value1, sensor2, value2, sensStatus)
VALUES ('" . $location . "', '" . $sensor1 . "','" . $value1 . "', '" . $sensor2 . "' ,'" . $value2 .
"', '"$sensStatus"' )";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
}
else {
echo "Wrong API Key provided.";

40
}
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

3) The following is the PHP, and HTML code that is used to visualize the
sensors data from the database on a web browser:
//this HTML code divide the screen into two and shows the values using the table and the
//chart
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<html>
<head>
<meta charset="utf-8">
<title>Data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//to show the sensors value on the left side of the web browser using the table
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

41
<div class="split left">
<div class="centered">
<?php
$servername = "localhost";
// REPLACE with your Database name
$dbname = "nimona";
// REPLACE with Database user
$username = "admin";
// REPLACE with Database user password
$password = "123";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, location, sensor1, value1, sensor2, value2, reading_time, sensStatus
FROM SensorData ORDER BY id DESC limit 10";
echo '<table cellspacing="5" cellpadding="5">
<tr>
<td>ID</td>
<td>Location</td>
<td>Sensor One</td>
<td>Value One</td>
<td>Sensor Two</td>
<td>Value Two</td>
<td>Timestamp</td>
<td> Status </td>
</tr>';
if ($result = $conn->query($sql)) {
while ($row = $result->fetch_assoc()) {

42
$row_id = $row["id"];
$row_location = $row["location"];
$row_sensor1 = $row["sensor1"];
$row_value1 = $row["value1"];
$row_sensor2 = $row["sensor2"];
$row_value2 = $row["value2"];
$row_reading_time = $row["reading_time"];
$row_sensStatus = $row["sensStatus"];
echo '<tr>
<td>' . $row_id . '</td>
<td>' . $row_location . '</td>
<td>' . $row_sensor1 . '</td>
<td>' . $row_value1 . '</td>
<td>' . $row_sensor2 . '</td>
<td>' . $row_value2 . '</td>
<td>' . $row_reading_time . '</td>
<td>' . $row_sensStatus . '</td>
</tr>';
}

$result->free();
}
$conn->close();
?>
</table>
</div>
</div>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//to show the senser value using the chart on the right side
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<div class="split right">

43
<div class="centered">
<?php
$servername = "localhost";
// REPLACE with your Database name
$dbname = "nimona";
// REPLACE with Database user
$username = "admin";
// REPLACE with Database user password
$password = "123";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, location, sensor1, value1, sensor2, value2, reading_time FROM
SensorData ORDER BY id DESC limit 10";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
$readings_time = array_column($sensor_data, 'reading_time');
$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')),
JSON_NUMERIC_CHECK);
$value2 = json_encode(array_reverse(array_column($sensor_data, 'value2')),
JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time),
JSON_NUMERIC_CHECK);
$result->free();
$conn->close();

44
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.highcharts.com/highcharts.js"></script>
<style>
body {
min-width: 310px;
max-width: 1280px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>ESP Reservoir one Station Data</h2>
<div id="chart-Turbidity" class="container"></div>
<div id="chart-Temprature" class="container"></div>
<script>
var value1 = <?php echo $value1; ?>;
var value2 = <?php echo $value2; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartT = new Highcharts.Chart({
chart:{ renderTo : 'chart-Turbidity' },
title: { text: 'Turbidity Sensor' },
series: [{
showInLegend: false,
data: value1
}],

45
plotOptions: {
line: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
xAxis: {
type: 'datetime',
categories: reading_time
},
yAxis: {
title: { text: 'Turbidity (NTU)' }
//title: { text: 'Temperature (Fahrenheit)' }
},
credits: { enabled: false }
});
var chartH = new Highcharts.Chart({
chart:{ renderTo:'chart-Temprature' },
title: { text: 'DS18B20 Temperature' },
series: [{
showInLegend: false,
data: value2
}],
plotOptions: {
line: { animation: false,
dataLabels: { enabled: true }
}
},
xAxis: {
type: 'datetime',
//dateTimeLabelFormats: { second: '%H:%M:%S' },

46
categories: reading_time
},
yAxis: {
title: { text: 'Temperature (Celsius)' }
},
credits: { enabled: false }
});
</script>
</div>
</div>
</body>
</html>

47

You might also like