Uploaded by Saif Uz Zaman


This is to proclaim that this report on the implemented hardware project is self-contained for
the purpose of submission as a part of the Senior Design course (EEE/ETE 499) in Fall 2018 at
North South University and has not been utilized anywhere else for other reasons. All the sources
used for the purpose of the report has been mentioned with references in the bibliography
section. Any similarities, in phrasing and diction, if found to other existing papers, which has not
been cited, is a subject of pure coincidence.
Kazi Rafiu Ibn Matin
ECE Department
North South University, Bangladesh
Tasnuba Afrin Anika
ECE Department
North South University, Bangladesh
Saif Uz Zaman
ECE Department
North South University, Bangladesh
We, Tasnuba Afrin Anika(1321193645), Kazi Rafiu Ibn Matin(1330538043), and Saif Uz
Zaman(1410757642) members of EEE499/ETE499 Senior Design Project from the Electrical and
Computer Engineering department of North South University seek great pleasure to have worked on our
project titled as “Smart Water Monitoring System for Fisheries” under the supervision of Dr.
Mohammed Shazzad Hosain as a compulsory requirement to complete our degree of Bachelors of
Science in Engineering and it turned out to be with satisfactory outcome.
Supervisor’s signature
Md. Shazzad Hosain, PhD
Associate Professor and Chair
Department of Electrical and Computer Engineering
North South University
Firstly, we are grateful to Allah, for the good health and wellbeing that was needed to have completed
our project and paper with such success. We, as a team express our gratitude towards our supervisor,
Dr. M Shazzad Hosain for his tremendous support and guidance throughout the whole term of our
project. We are extremely thankful and indebted to him for sharing his expertise and encouragement
that was extended towards us. We would also like to take this opportunity to thank our university, North
South University and our department, Electrical and Computer Engineering for all the support provided
to us. We consider ourselves blessed and humbled to have worked within this territory.
Lastly, we are also very appreciative to all the other people who somehow helped and contributed in the
completion of this project.
This report represents the novel design of a water condition monitoring device. Such devices can
be used to scan and observe the water qualities for various purposes from fisheries to agriculture
and other various industrial scale applications where monitoring water condition is necessary. A
leading company that manufactures such products is Libelium. The devices produced by
Libelium can be a bit on the expensive side, ranging from $999 to even greater amounts
depending on the kit. The purpose of such water monitoring device can be met at a low cost,
using simple designs and cheaper materials, which was the motivation towards the device that
was built in this project. The device can greatly benefit fishing economy of Bangladesh, since it
has the world’s largest delta and is mostly low marshy lands where many fish farms reside. If the
conditions of the fisheries are monitored by using the device and measures are taken to control
such conditions, it can greatly improve the fish production yield, since most Bangladeshi
fisheries don’t use any devices to monitor the water. Although Bangladesh is one of the largest
freshwater fish exporters in the world, a lot of freshwater fish in farms are known to die out due
to the poor water conditions and quality assurance. The device has a 10V Solarpanel that charges
a rechargeable battery which delivers the required power to the Arduino to function the sensors.
The readings can be received on a handheld device via Bluetooth and also alert the user for
harmful changes in water conditions which will be very convenient for the operators of various
Table of Content:
Name of the topics
Page Numbers
Chapter 1: Introduction
1.1-Project overview
Pg 8
1.2-Background and Motivation
Pg 9
1.3-Difficulties faced during the project Pg 10
1.4- Project Goal
Pg 10-11
Chapter 2: Related works
Pg 11-28
Chapter 3: Ethics, Safety & Standardization
Pg 28-37
Chapter 4: Theory I
4.1- Introduction
Pg 38
4.2-List of Components in the project
Pg 39-46
Chapter 5: Theory II
Pg 48
5.2- Working principle
Pg 48
5.3- General Sensor Module
Pg 49
5.4-Battery and Solar Panel
Pg 49-50
5.5-Analog Dissolved Oxygen Sensor
Pg 51-52
5.6- Analog meter, pH, Salinity meter
Pg 52-54
5.7- Digital temperature sensor and
Pg 55
5.8- LCD display and Bluetooth module
5.9- Android Application
Pg 56
Pg 57
5.10- Finished device and LCD reading
Pg 57 -59
Chapter 6: Results and Observation
6.1- Requirement Analysis
Pg 60-63
6.2- Real life test results
Pg 64
Chapter 7: Future Works
7.1- Introduction
Pg 65
7.2- More Sensors
Pg 65
7.3- Microcontrollers and Ports
Pg 66
7.4-Improved sensors
Pg 66
7.5- Improved batteries & solar panel
Pg 66
7.6- Upgraded Android app
Pg 67
7.7- Actuators
Pg 67
7.8- Waterproof device
Pg 68
7.9- Conclusion
Pg 69
Pg 70-96
Pg 97
Table of Figures
Figure 2.1
Marker shows the latest measurement data
Figure 2.2
Power Source Block Diagram
Figure 2.3
System architecture based on WSN
Figure 2.4
Outline of the scope of work undertaken in
the design of the SmartCoast platform.
(MAC, National Microelectronics
Applications Centre; NCSR, National Centre
for Sensor Research.)
Figure 2.5
Sensor local area network. (DO, dissolved
oxygen; GPRS, general packet radio service;
MAC, National Microelectronics
Applications Centre.)
Figure 4.1,4.2,4.3, 4.4, 4.5, 4.6, 4.7, 4.8,4.9,
Block diagram, Arduino UNO, Solar Panel,
4.10, 4.11,4.12
ORP, DO sensor, Analog Turbidity Sensor,
Analog pH sensor, Analog Electrical
Conductivity Sensor, Temperature Sensor,
Bluetooth Module(HC-05), LCD
screen(20x4), Wooden frame and box, Buzzer
Alarm for arduino
Figure 5.1, 5.2, 5.3, 5.4, 5.5. 5.6, 5.7, 5.8, 5.9,
A general connection of the sensor module to
5.10, 5.11. 5.12
the arduino,The connection of the complete
device, Batteries connection, connection from
batteries,The module for the DO sensor,the
process of adding the solution to the
probe,ORP reducing and oxidizing agent,pH
characteristics,Codes for alarm
condition,Circuit diagram of LCD and BT
Chapter 1: Introduction
1.1- Project Overview:
Bangladesh has one of the largest export business in fisheries. There are different
research institutes, projects and farming guides whose sole purpose it to enlarge the
market more. Our project is about maintaining the water quality so that the growth of
fisheries can increase in Bangladesh and the mortal rate of fisheries decreases. Water
quality is the most important factor affecting fish health and performance in
aquaculture production systems. Good water quality refers to what the fish wants and
not what the farmer thinks the fish wants. This means that farmers must understand the
water quality requirements of the fish under culture very well. Fish lives and they are
entirely dependent on the water they live in, for all their needs.
Different fish species have different and specific range of water quality aspects
(temperature, pH, oxygen concentration, salinity, hardness, etc.) within which they can
survive, grow and reproduce. Each species has its own optimum range and different
build-up so it is necessary to maintain a basic chemical and physical condition of the
water for the fish to live long.
Our project proposes a smart monitoring system for the ponds, lakes etc. to monitor
elements such as temperature, pH level, dissolved oxygen (DO), oxidation-reduction
potential (ORP), conductivity (salinity), turbidity in water. Our solution will comprise of a
hardware attached to each individual water body, and the readings will be constantly
monitored through a software- android app. The data will also be stored as a back-up
and for further use. There will also be an alarm and an LCD display to monitor the result
and alert people working with it.To a great extent water determines the success or failure
of an aquaculture operation. Our device will help identify the problem in right time so
that proper measures can be taken to prevent death of fish in the water.
1.2- Background and Motivation:
To explain the background of our project we have to emphasis on the history of Bangladesh’s
history on agriculture of fisheries. Bangladesh being a first line littoral state of the Indian Ocean
has a very good source of marine resources in the Bay of Bengal. The country has an exclusive
economic zone of 41,000 square miles (110,000 km2), which is 73% of the country's land area.
More than 80 percent of the animal protein in the Bangladeshi diet comes from fish. Fish
accounted for 6 percent of GDP in the fiscal year of 1970, nearly 50 percent more than modern
industrial manufacturing at that time. From the very beginning Bangladesh has always been into
fish farming and aquaculture production.
As of the end of 1987, prevailing methods for culturing shrimp in Bangladesh were still relatively
unsophisticated, and average yields per hectare were low. In the late 1980s, almost all inland
shrimping was done by capture rather than by intensive aquaculture. Farmers relied primarily
on wild post larval and juvenile shrimp as their sources of stock, acquired either by trapping in
ponds during tidal water exchange or by gathering from local estuaries and stocking directly in
the ponds. Despite the seemingly low level of technology applied to shrimp aquaculture, it
became an increasingly important part of the frozen seafood industry in the mid-1980s. The
shrimp farming industry in Bangladesh has been handicapped by low-quality and low prices.
We also explored the current situation of Bangladesh’s market of fisheries. Bangladesh is
considered one of the most suitable regions for fisheries in the world, with the world's largest
flooded wetland and the third largest aquatic biodiversity in Asia after China and India. There
has been tremendous growth on the agriculture of fisheries in Bangladesh. This increase in the
aquaculture production has been made possible with the implementation of scientific and
technological modernization. From 2000 and 2016, aquaculture production increased from
712,640 and 2,060,408 metric tons, a much larger quantity than wild capture production (1.023
million t) in 2016. There has also been a recent increase in the value of fishery exports, with
more than US $34.08 billion in 2010 rising to more than US $46.60 billion in 2015. However,
fisheries production is well below production targets despite the large gains seen in the
aquaculture sector. This is because every year lots of fish dies due to poor water quality and lack
of balanced conditions of water. This was our main motivation to take on this project and work
out something to contribute in this vast arena and try to make a better survival rate for
fisheries. We also explored other similar projects that were done in other countries which also
helped us to work and improvise our project to make it fit for Bangladesh.
1.3- Difficulties faced during the project:
One of the few difficulties that we faced in this project was most of the components were not
available in Bangladesh and so we had to import them from outside the country. This took a lot
of time and also created trouble for us. Another factor which was more like a challenge to us
was to make the device budget friendly so that people in Bangladesh can afford it who are in
need of it. Our device is cost efficient and hence easier for purchase. One of the other problem
that triggered was insufficient amount of NaOH available which is limestone and it was needed
to activate the Dissolved Oxygen component but then we took help from our university labs and
was successful to work with it.
1.4- Project Goal:
The goal of this project was to make a cost-effective device that would help fisheries or pond
owners to monitor the various conditions that affects the life of fish. If people can identify it at
the right time, then they would be able to rectify the conditions that distresses the mortality
rate of fish. The smart monitoring system device helps the operators so that they can take
actions accordingly for proper fish health and eventually increase the production or yield of fish.
This would also be a huge contribution in the betterment of Bangladesh agriculture for fish.
Chapter 2- Related works:
a. Water Quality Monitoring System by Hao Jie Chan
In September 2016, a water treatment plant has to be shut down because polluted water
flowed into the plant. The water supply company was unable to pin point the contamination
source and this caused a serious water service disruption.
My university course requires the students to build a system to solve community problems. An
automated water quality monitoring system would ease the job of finding the pollution source!
4 sensors are interfaced to Arduino Genuino 101. All of them requires some interfacing circuit
because they are current-output sensors. Arduino Genuino 101 collects the measurements data
periodically, gets the GPS coordinates, and uploads the data bundle into a database using GPRS
data link. Users can go to the website to view the result as shown below.
Fig 2.1: Marker shows the latest measurement data
The three current output sensors are from Global Water, provided by the supervising lecturer. I
use temperature, pH and dissolved oxygen level sensors in this project. Unfortunately, the
dissolved oxygen level sensor is faulty.
The other sensor is a turbidity sensor, which output a voltage level proportional to the amount
of suspended solid particles in the water.
A schematic diagram of the Interfacing Sensors and Arduino is given below-
This A7 GPRS and GPS module module was chosen because it was relatively cheaper than
SIM900 variant, and it combined both GPRS and GPS in a single package. However, the cheaper
price did come with a price. First, the GPS antenna that comes with the module is not really a
GPS antenna, you will have to buy one yourself to cover up this flaw. Second, it only supports
115200 bps UART communication by default, and even if you change it using software, it will
return to the default baud rate after a power cycle, and Software Serial at 115200 bps is very
very unreliable. I pulled my hairs for 2 days for this problem. After that a baud was
implemented to rate change function in the Arduino code.
And, since this is a new module, creation of its own library was needed. The source codes
are collected from various places, like SIM900, and Adafruit GPS module.
A circuit has to be designed to switch on the module. It has two pins, RESET pin and PWR_KEY
pin to be controlled. A voltage is applied to the PWR_KEY for at least 2s to boot up the module.
To reset, pull the RESET pin to GND. Otherwise, the RESET pin should be pulled up to 5V. I first
reset the module, and then proceed to power up the module to make sure it starts up okay.
Power source deserves a special mention her because of the current output sensors. They
require a minimum of 10V to operate, higher than the preferred 5V. Since it was necessary to
demonstrate the capability of this system to work remotely, Li-Ion battery was opted here.
Fig2.2: Power Source Block Diagram
2 Li-Ion batteries in series will give 7.4-8.4V, one buck converter to bring it down to the
necessary 5V for Arduino and A7 module, another boost converter to provide a 11V power rail
for those water sensors. With this setup, the system will not run for a long time, but that is not
a main concern for this prototype.
b. MyRiver project by Andrei Florian
A river or lake can be a great source of fun and relaxation. But if the river becomes dirty
and contaminated, all the fun is gone. Many people depend on river water to feed their
livestock and cannot afford to give their animals dirty water.
Imagine living right next to a river (if you are not), you would not want to wake up in the
middle of the night with your house flooded because of the river. Or what if your
neighbour decides to dump some petrol in the river, you would not want your animals
getting sick.
MyRiver solves all of those problems, it can operate in isolated areas thanks to Sigfox so
that everyone has access to the device. The device will read the pH of the water, its
pollution level using an innovative method, and its water level. You will be able to monitor
the river live on your phone or computer anywhere thanks to Wia. This way you can know
if there is a problem with the stream and allows you to act before it is too late. It will notify
you if there is a problem with the river immediately.
The device is based on the Arduino MKR FOX, it is designed for remote use, the user can place
the device in a river or lake and monitor it from anywhere. Thanks to the SAM D's low power
mode, the device can work for an extended period of time on 2AA batteries.
The device takes readings every 30 minutes, going to sleep afterwards, the sleeping period can
be reset, though the minimum sleep time must be 20 minutes.
The MKR FOX reads the pH of the river using a pH sensor, it also gets its water level, using a
water level sensor, and it senses if it is polluted by insoluble substances by shining an LED at a
photoresistor, if the photoresistor reading is low, it means that a solid substance (oil, petrol,
mercury, etc.) is present in the river. The device then sends all the data to Sigfox, where it is
relayed on to Wia, processed and visualised. The user is notified on the state of the river. Below
is an image of the functionality overview.
The buffer will be sent to Sigfox encoded as HEX, Sigfox will relay the data to Wia, the data will
then pass through a flow, the data will be converted back to string and then into the sensor
values. They will then be processed and the user will be notified if the values are out of bounds.
Below is another image illustrating the project's code overview, described below.
Read Sensors will read the pH, water level and photoresistor sensor values and store them in
Format Buffer will merge all the values into a 12 Byte buffer that can be sent to Sigfox. Parse
Data will parse the buffer to Sigfox. The MKR FOX can only send 12 bytes through Sigfox, this
means that all the sensor values have to be merged into the 12 bytes, each sensor's maximum
raw value is 1024 (as they are all analog), so each sensor represents one third of the buffer (4
bytes). The Arduino has to merge the values and add zeros to the start of each value until the
value has 4 bytes. The image below illustrates this process.
The Arduino receives the sensor values as integers, it then converts the integers into strings and
adds zeros to the start of each value until it has 4 bytes, for example, if the photo-resistor value
is 620, one zero will be added, 0620. But if the water level sensor is equal to 24, two zeros are
added, 0024. The device then merges the values together into a 12b.
c. Design and Development of Water Quality Monitoring System based on
Wireless Sensor Network in Aquaculture
System architecture based on WSN is the process to monitor water quality environment
includes data acquisition, data transmission, data preservation and decision-making, which is
involved with software and hardware comprehensive integration, so the excellent architecture
becomes the top priority to the water quality monitoring system as a composite system.
Wireless sensor network (WSN) is composed of data acquisition node, wireless transmission
network and information processing center. Data acquisition nodes integrate sensors, data
processing module and communication module. Through the communication protocol, the
nodes form a distributed network. Then the network transmits the optimization data to
information processing center. The system adopts Zigbee based on IEEE 802.15.4
communication protocol. Zigbee is a wireless intercommunication technique that has low
transmitting rate and low cost advantages. It can be embed in devices, is particularly suitable
for industrial control, aquaculture water quality monitoring, wireless sensor networks and
smart devices such as the widely distributed applications.
Wireless network monitoring system includes the major technologies:
Wireless communication technology—2.4GHz short range communication and GPRS
communication, wireless signals cover 3km range;
Embed control technology—intelligent information acquisition and control;
Wireless network technology—network routing layer, communication caching. Selfdiagnosis and maintenance technology;
Energy manage technology—low power consumption and energy management.
Wireless sensor networks are widely used throughout intelligent transportation,
environmental protection, public safety, peace at home, smart fire alarm, industrial
monitoring, elderly care, personal health, floriculture, food traceability, enemy
detection and intelligence gathering, and other fields
Particularly in the areas of agriculture and rural information, WSN can be more widely
available, such as: precision agriculture-the precise application of sensor technology,
intelligent expert management system, remote monitoring and remote sensing systems,
bioinformatics and diagnostic systems, food safety traceability system.
Water quality monitoring system architecture applied WSN Based on WSN, the water quality
monitoring system uses three-layer structure: data acquisition layer, data transport layer and
application layer to establish its architecture.
The architecture as figure 1 shows:
Fig2.3- System architecture based on WSN
In the data acquisition layer, the water quality monitoring system uses WSN which is formed by
a large number of tiny sensor nodes through wireless self-organizing way. The sensors obtain
data in the network include PH, water level, water temperature, DO (dissolved oxygen) sensor.
WSN integrates sensor, MEMS and wireless communication technologies, can real-time
perception and handle object’s data information in network range, then send to the users. It
has many excellent characters, such as large cover range, remote monitor, high monitoring
precision, quick deployment and low cost. Through using WSN technology, the system can
effectively monitor transport data and ensure the real-time data to be transported to the water
quality monitoring software for analyzing and providing later control decisions. In the data
transport layer, there are two types of transmission methods: long-distance and short-distance
data transmission. The system uses the GPRS to transport long-distance data, and uses the
Zigbee to obtain the sensors’ monitoring data, and then utilizes application software to manage
the data and to make decisions to control devices. The real-time data through the sensors by
Zigbee stored in the database to ensure users can query any time any sensor monitoring data
information to analyze. In the application layer, the water quality monitoring software is the
main part. Through the software, users can monitor the quality of the water all the time from
the real-time data to ensure the water quality of the aquaculture. Water quality monitoring
software utilizes the expert knowledge stored in the data and knowledge database together
with the pretreatment data transported from sensors to make the decisions. Then the system
decides whether to open or close the valve on relation device to increase or decrease the
oxygen, water with the decisions. On-site users can receive early warning information from
smart handheld device and depend on the decisions to operate. In order to facilitate user
management, and data on water quality issues can occur in time to respond, the software also
uses SMS early warning function. Off-site users can receive early warning information from PDA
and other smart phones, and can send commands by SMS to control the valve on device. The
users can not only get the current water quality environmental data, but also analyze the data
in period to get the water environment trends to overall manage water quality. The system
collects temperature, PH, dissolved oxygen sensor signals by sensor module, via wireless
transport module transmit data, and combines with system software to achieve real-time
monitoring and control. The system based on users demand, can monitor the water quality
data at any time. It provides scientific evidences to automatic monitoring of water quality
information, automatic control and intelligent management.
d. SmartCoast Smart Water Quality Monitoring System
SmartCoast was a 3-year applied R&D Project, cofounded by the Marine Institute and the
Environmental Protection Agency (EPA) (Grant Aid Agreement No. AT-04-01-06), which was
aimed at developing novel sensing technologies that can continuously collect data on water
quality in lakes, rivers and estuaries and transmit this information via wireless links directly to a
computer, delivering detailed data at levels that would otherwise be difficult, if not impossible,
to achieve. In 2003, the Marine Institute commissioned a review of and feasibility study on
requirements, current developments and potential innovations in respect of sensor systems to
support the implementation of the WFD in freshwater catchments. This was carried out by TNI
and its findings included the following. Real-time sensing of water has a number of common
limitations which are distinctive of the technology. Sensor drift is one of the most serious
impairments of chemical and biochemical sensors. Despite efforts to improve long-term
stability, manufacturers have yet to release sensors that are not affected by some degree of
drift. One of the major challenges is to be able to systematically reduce the dimensionality of
the incoming data, while preserving all relevant information. So far there has been no
systematic approach to the problem of data reprocessing and analysis. It seems that the choice
of suitable output (desorption signal, baseline, transient/maximum response, etc. and analytical
protocol is often the result of trial and error, largely based on personal intuition or experience.
Unfortunately this is a time-consuming process, which requires highly skilled personnel. The
adequate validation of environmental sensing systems is rarely carried out and therefore
results are not always meaningful. The main reason for this is that validation takes too much
time and money for a single developer to bear full responsibility for the task. In practice, lack of
validation significantly hampers implementation. SmartCoast aimed to deploy its sensor
network to demonstrate to interested parties the benefits associated with continuous in-situ
In order to design a monitoring system of value, the SmartCoast Project established a user
group as part of its information gathering process. Initially, the project identified all relevant
public sector organisations and invited them to attend a project briefing meeting to create a
relationship between the user group and the project. The SmartCoast Project team engaged in
a series of meetings with the River Basin Districts (RBDs) in 2006 and 2007, which took the form
of briefings and discussions that allowed a two-way flow of information.
User Group Needs the following is a list of needs that were identified by users of water
monitoring systems in relation to developing an ideal monitoring system:
Variable monitoring frequencies
A multi-sensor solution
Data integrity and presentation
Real-time data collection/alarms
Scalable on demand
Owing to SmartCoast and other related investments in environmental sensing R&D, Ireland is
well positioned relative to other countries, even the US, in terms of expertise. Therefore, there
is a real opportunity for Ireland to make critical contributions in this area. A number of
recommendations arose from discussions that took place during a SmartCoast workshop, and it
is important that these are given due consideration for future approaches to effective water
monitoring technologies, systems and programs. Those recommendations are stated below
It was recommended that partnerships should be built between academia,
agencies and end-users that will lead to long-term capability and trust in the
technology. Similarly, agencies must have a stake in the technology development
process and thus in the quality of the data.
Demonstrations Valuable reference data for research prototypes can be
obtained by using off-the-shelf commercial systems at certain test deployment
sites. The latter will also provide data for environmental systems research. It was
recommended that demonstrations must be led by the end-user.
Fundamental research needs to be continued in areas such as biological
contaminants and nutrient species.
Sustainability It is recommended that long-term funding is given to enable
further research into new technologies and effective technology transfer to small
and medium sized enterprises (SMEs). There is a need for the establishment of a
small number of reference/test sites at which there is an infrastructure to plug
devices into to enable continual development and testing of new
The SmartCoast platform covers all aspects of user requirements for the viewing of sensor data
by endusers using a standard web browser as shown in Fig. 4.1.
A number of important decisions were taken early in the project that influenced the overall
system design approach taken to design the SmartCoast platform. These included:
• All communications with the sensors to be wireless (as opposed to wired or
manual display/keypad interface).
• A variety of sensors would be deployed at a monitoring site and sensors could
easily be added and removed when required, i.e. for seasonal monitoring purposes.
• The sensor nodes would be designed for ease of maintenance and deployment.
• While ‘real-time’ monitoring is not a strong requirement of the WFD, it was
agreed that alarm alerts on measurement thresholds, such as pollution alerts, would be
a critical component of the system and would add to the success of the project.
• Where possible, the design adheres to industry standards to ensure futureproof design and compatibility of the system with other possible available solutions.
An important aspect of the overall solution was the decision that each individual sensor would
have its own low-power radio capable of communicating from 75 to 100 m as an unobstructed
space using the IEEE
Fig 2.4. Outline of the scope of work undertaken in the design of the SmartCoast platform.
(MAC, National Microelectronics Applications Centre; NCSR, National Centre for Sensor
Based on the user requirements and the choice of a wireless sensor interface, the following two
system architecture options were designed:
Local area network (‘drive-by’) for local monitoring of sensors A low-cost, lowpower sensor support network that requires manual extraction of the data from
the sensors by a handheld wireless device.
Wide area network for ‘real-time’ monitoring and control of sensors A low-cost,
low-power sensor support network that facilitates real-time monitoring of
sensors for sensor measurement, alarm alerts and fast data reporting.
Local area network (‘drive-by’) for sensor monitoring The main features of the local area
network, shown in Fig. 4.2, include
Each sensor unit shuts off ZigBee® communications to conserve power and only
wakes up periodically to check if a ‘parent’ hand-held device is present. This
period of sleep/wake-up is programmable from ‘always-on’ to once every few
minutes. The recommended period is every 60 s.
A standard off-the-shelf personal digital assistant (PDA) (such as a DELL Axim
X51) is used as the hand-held device and will have a ZigBee® radio unit
connected. It will include a standard Windows operating system with full
processing and display facilities.
A router node is used to extend the operating range of a network and also to
enable a mesh network to be formed.
Fig2.5: Sensor local area network. (DO, dissolved oxygen; GPRS, general packet radio service;
MAC, National Microelectronics Applications Centre.)
Each installation (site) network configuration is pre-programmed into the handheld device to enable ease of identification of the sensor network at this site and
ensure that all sensors located on the site are accounted for when read by the
handheld PDA.
Sensor monitoring data, alarm data and unit status are uploaded to the handheld device. It will also be possible to download new monitoring conditions to
the sensor, such as frequency of sensor monitoring, as well as real-time clock
synchronisation and wake-up frequency.
The hand-held device is capable of displaying individual sensor monitoring data
and any alarm data generated.
It is possible to download new updated software release versions to each sensor
unit from the hand-held device. This feature however will not be part of this
Uploaded data files stored on the unit will have a date/time stamp of upload.
It is possible to upload the data to a remote office personal computer or server
via an optional general packet radio service (GPRS) connection to the hand-held
device or manually by simply plugging the PDA into its cradle when back in the
office and selecting the upload button.
The wide area network will provide a real-time monitoring and control facility for each sensor
network or site. To enable this to happen, a programmable access controller – gateway (PAC-G)
is used as a gateway for the sensor network to a remote (or local on-site) server. Initially, this is
a GPRS connection but other wireless options would also be possible, such as WiMax and
satellite. This network configuration is shown in Fig. 4.3.
The main features of the wide area network, shown in Fig. 4.3 include:
The PAC-G will continuously monitor the ZigBee® sensor network to ensure all
devices are operational and will log any unit not communicating.
Sensors will only communicate with the PAC-G when it has data to send or at a
pre-programmed interval, such as daily, to check if there are any parameter
monitoring changes requested, such as increased frequency of sampling. This
extended sleep time (not having to wake-up every 60 s to see if a ‘parent’ device
is there) of the sensors will assist in minimising power used on sensor units.
The network range can be expanded using a router node that will also enable
mesh networking.
The frequency at which sensors take sensor readings is remotely programmable
and will range from minutes to hours.
Sensors will immediately upload any monitoring data and the unit status to the
The PAC-G first stores the data and then forwards them to a remote server via
the GPRS connection at pre-programmed intervals, e.g. once every 24 h.
Any sensor alarm data are transmitted immediately by the PAC-G to the remote
server, i.e. when a sensor measurement threshold is breached, such as a
pollution level.
All data are retained by the PAC-G until passed on to the server, so in the event
of a server failure no data are lost.
All sensor monitoring requirements and alarm thresholds can be changed
New release versions of the application for sensor monitoring can be
downloaded remotely from a central server via the PAC-G; no data analysis is
performed by the PAC-G.
A multi-sensor water quality monitoring platform has been developed in the project. This
incorporates novel sensor interface technologies that can be reconfigured to meet the
monitoring requirements of a given scenario using a wide variety of sensor input types. The
sensor interface capabilities enabled by the developed wireless sensor network platform allow
for integration of a wide variety of commercially available sensors.
Two sensors capable of measuring phosphate and dissolved oxygen were developed by the
consortium during the project. The phosphate sensor is suitable for long-term monitoring of
phosphate levels in natural waters. The system incorporates sampling, pumping, reagent and
waste storage, colorimetric detection and wireless communication into a compact and portable
device. Currently, the system has a linear dynamic range between 0 and 20 mg/l and a limit of
detection of 0.3 mg/l. Dissolved oxygen sensor technology was developed, providing a sensor
probe that is fully waterproofed and ruggedized, incorporating a novel optical configuration,
and is capable of intermittent operation, facilitating its use in battery-powered systems. The
sensor is fully temperature compensated and utilizes three dimensional calibration equations,
which maximise accuracy. These two novel devices were tested in the demonstration phase and
while the phosphate system performed well, DO system is in need of further work to enable
long-term deployment in the aquatic environment.
Chapter 3-Ethics, safety and standardization:
Ensuring the safety of water is a challenge due the excessive sources of pollutants, most of
which are man-made. The main causes for water quality problems are over-exploitation of
natural resources. The rapid pace of industrialization and greater emphasis on agricultural
growth combined with latest advancements, agricultural fertilizers and non-enforcement of
laws have led to water pollution to a large extent. The problem is sometimes aggravated due to
the non-uniform distribution of rainfall. Individual practices also play an important role in
determining the quality of water.
Water quality is affected by both point and non-point sources of pollution, which include
sewage discharge, discharge from industries, run-off from agricultural fields and urban run-off.
Other sources of water contamination include floods and droughts and due to lack of
awareness and education among users. The need for user involvement in maintaining water
quality and looking at other aspects like hygiene, environment sanitation, storage and disposal
are critical elements to maintain the quality of water resources.
Poor water quality spreads disease, causes death and hampers socio-economic progress.
Around 5 million people die due to waterborne diseases around the world. Fertilizers and
pesticides used by farmers can be washed through the soil by rain, to end up in rivers. Industrial
waste products are also washed into rivers and lakes. Such contaminations enter the food chain
and accumulate until they reach toxic levels, eventually killing birds, fish and mammals.
Chemical factories also dispose wastes in the water. Factories use water from rivers to power
machinery or to cool down machinery. Raising the temperature of the water lowers the level of
dissolved oxygen and upsets the balance of life in the water. All the above factors make water
quality monitoring essential.
Water quality monitoring is defined as the collection of information at set locations and at
regular intervals in order to provide data which may be used to define current conditions,
establish trends, etc. Main objectives of online water quality monitoring include measurement
of critical water quality parameters such as microbial, physical and chemical properties, to
identify deviations in parameters and provide early warning identification of hazards. Also, the
monitoring system provides real time analysis of data collected and suggest suitable remedial
The aim of this paper is twofold. One is to provide a detailed survey of recent work carried out
in the area of smart water quality monitoring in terms of application, communication
technology used, types of sensors employed etc. Second, is to present a low cost, less complex
smart water quality monitoring system using a controller with inbuilt Wi-Fi module to monitor
parameters such as pH, turbidity and conductivity. The system also includes an alert facility, to
inform the user on deviation of water quality parameters.
The selection of a water-quality monitor involves four major interrelated elements—
The purpose of the data collection.
The type of installation.
The type of sensor deployed at the installation.
The specific sensors needed to satisfy the accuracy and precision requirements
of the data-quality objectives.
The most widely used water-quality sensors in monitoring installations are temperature,
specific conductance, dissolved oxygen (DO), pH, and turbidity. Sensors also are available to
measure oxidation-reduction potential, water level, depth, salinity, ammonia, nitrate, chloride,
and chlorophyll; but the focus of this report is on temperature, specific conductance, DO, pH,
and turbidity. The sensors needed to measure these properties are available as single
instruments or in various combinations. For clarity in this report, a sensor is referred to as a
particular lone sensor or a sensor that is detachable from a combination. A group of sensors
configured together commonly is referred to as a sonde, which typically has a single recording
unit or electronic data logger to record the output from the multiple sensors. Types of Monitor
Configuration In general, three types of configurations are used for water-quality monitors. The
flow-through monitoring system generally has a pump that delivers water to the sensor(s)
mounted in a shelter; the second configuration is one in which the sensors are placed in situ
(immersing a field measurement sensor directly into the water); and the third configuration is a
selfcontained sensor and recording system that requires no external power and is placed in situ.
Each configuration has advantages and disadvantages in relation to site location and dataquality objectives. The flow-through monitoring system has a pump to convey water from the
stream to a tank inside a shelter that contains the monitoring sensor or sonde (fig. 1). Typical
pumps require 120-volt alternating current (AC) and deliver about 10 gallons of water per
minute. If access to power is not a problem, then other site considerations become important;
the advantages and disadvantages of the flow-through monitoring system must be compared to
the data objectives.
The purposes of the sensor inspection are to provide an ending point for the interval of water
quality record since the last service visit, a beginning point for the next interval of water-quality
record, and verification that the sensor is working properly. This is accomplished by recording
the initial sensor readings, servicing the sensors, recording the cleaned sensor readings,
performing a calibration check of sensors by using appropriate standards, and if the readings of
the monitoring sensor are outside the range of acceptable differences (see next section,
Monitor Calibration Criteria), recalibrating the sensor. A final environmental sensor reading is
required after the calibration check or after recalibration. The difference between the initial
sensor reading and the cleaned sensor reading is the sensor error as a result of fouling; the
difference between the calibration-check reading and calibrated-sensor reading, if necessary, is
a result of drift. All information related to the sensor inspection must be recorded on a field
form or in a field notebook. The sensor readings in the field notes become the basis for
corrections (shifts) during the record-processing stage; thus, a complete and thorough
documentation of the sensor inspection is important. The initial sensor readings (before
cleaning) of the monitoring equipment are compared to a calibrated field meter before
removing the monitor sonde for servicing. The comparison ideally is made at the measuring
point in the stream. This initial sensor reading becomes the ending point of the data record
since the last servicing, and the field meter reading provides a sense of the reasonableness of
the monitor readings and an indication of potential drift and fouling. However, except for
temperature sensors, the field meter readings are not used directly in record computation. The
field meter is used as a tool to assess cross-sectional variability and environmental changes that
may occur while the monitor is being serviced. Upon removal from the water, the monitoring
sensors are inspected for signs of chemical precipitates, stains, siltation, or aquatic growth.
These observations are recorded in the field notes before cleaning, and the Monitor Operation
13 individual sensors must be cleaned according to the manufacturer’s specifications. The
cleaned sonde or sensor is then returned to the stream and checked against the field meter.
Both instrument readings are recorded in the field notes. The observed difference between the
initial sensor reading and the cleaned sensor reading is a result of fouling chemical precipitates,
stains, siltation, or aquatic growth.
The significance of water for bio-culture and aquaculture can scarcely be overstated, and hence
the pertinence of ethics to water utilization and management is clear in a general sense. It is
important for everyone involved in water resource management and in public health to have a
well-reasoned understanding of the moral values and obligations that correspond to that
significance. In the domain of ethics, questions of scientific knowledge come together with
aspects of cultural meaning and perception; questions of conservation, sanitation, and health
promotion come together with questions of justice, equity, and human rights; questions of
sustainability and biodiversity come together with questions of democratic governance, law,
and policy.
Access to clean water and adequate sanitation is a growing problem for many parts of the
world. More than one billion people are in need of clean water, and 2.6 billion lack access to
basic sanitation. Water intensive agricultural, manufacturing, and land use practices throughout
much of the world are drawing down or contaminating groundwater at an alarming rate.
Many questions confront the world today. How can we ensure that an adequate supply of clean
water is available, both for today and for coming generations? How equitable will access to it
be? How should it be managed, and by whom? What will the implications of climate change be
on the quality and quantity of fresh water? Is clean water destined to become for the twentyfirst century what petroleum was for the twentieth, a source of geopolitical power and conflict?
Will social change concerning water use come through technological innovation or through
cultural and value change, or some combination of both?
Concurrent with the ecological dimensions of the water crisis are public health dimensions,
including, but not limited to, the spread of water-borne diseases, particularly in the developing
world. Existing systems need to be modified, or new systems need to be created, so as to
achieve more just access to clean drinking water, as well as to provide for effective societal
responses to public health concerns. From a systems perspective, water is more than simply a
medium for vectors of infectious disease; it is a foundation for maintaining the social
determinants and human capacities that sustain and promote health and well-being. Water is
not so much a “resource” as it is a lynchpin in the entire web of planetary life. The focus of
ethics is therefore not on water in isolation, but on the water cycle and how the cycle connects
the land and the atmosphere. The notion of a “watershed” has this connotation, connecting
water, the soil, and the biotic community.
Water is dynamic, elusive, determined, and a fecund source for the human moral and spiritual
imagination. We talk about water as a medium of disease transmission, as a fluid essential for
biological functioning, and as a thing to be manipulated with wells, pumps, sluice gates, dams,
and dikes. When we talk about the scientific and engineering aspects of water, we should not
lose sight of the fact that water is also a vital source of cultural meaning, which not only
sustains our biological life but also our imagination and spirit. No culture or tradition known to
us is indifferent to it. It is a symbol of purification, rebirth, and reconciliation, even as it is also a
source of animosity and conflict. Water, with its close connection with fertility and life, figures
deeply in religious and metaphysical worldviews of virtually all peoples. There is a prototypically
two sided aspect to the way water is represented and imagined in most traditions.
Water is the place from which order comes, but it is itself without form. It is life nurturing and
yet unshapeable, uncontrollable at the same time. If the creator could manage it, human beings
cannot. It is protean and relentless. It floods and recedes, indifferent to human constructions
on a floodplain. It finds tiny fissures and eventually splits the hardest rock and enters the best
sealed dwellings. Its changing physical state slowly reshapes the geology of the planet as ice
sheets progress and recede, as sea levels rise, as rain falls, and as rivers find new channels.
Human things are small by comparison. We move and channel water, to be sure, and we must
use it (carefully), but effective, sustainable utilization of water is really more a form of
accommodation than a form of control. We are not always honest with ourselves about our
dependency on water, and our sheer frailty in the face of it.
Different ways of conceptualizing what water is and how human beings should use it have
different ethical implications. Understanding water supplies as commodities to be bought and
sold, and as property to be controlled unilaterally by certain individuals or groups, has different
implications for fulfilling the ethical principles (such as human rights and social and
environmental justice) than does understanding it as a fragile ecosystemic component of a
common ecosystem upon which we all depend in myriad ways. Of particular interest in the
chapter, therefore, will be the convergence between eco-systemic and public health
perspectives, on the one hand, and the appropriate ethical use of water to sustain and promote
human and eco-systemic health, on the other.
Taken together the ethical values of efficiency, equity, and stewardship can form a basis of a set
of ethical principles that can normatively guide water management and public health policy.
Additional principles of water ethics will be based on procedural and decision-making process
values, such as democratic governance rights, active participation, transparency, accountability,
and public-private collabor- ation and partnership. Implementing these ethical ideals and
obligations in practice is shaped by a number of factors: Who participates in the decisionmaking process? Is participation active and involved in formulating options or is it passive and
reactive to proposals that are already well-developed? What kind of information is open to the
public? How do professionals interact with non-professionals? Is there respect for cultural
diversity and traditional beliefs and practices? And finally, how is a balance determined
between the needs of human development and the need to preserve our natural resources?
With these ethical orientations and practical considerations in mind, we offer the following
principles of water ethics. In each case there is a meaningful application of the principle to the
relationship between humans and water and the effects of the various technologies of water
utilization (purification, sanitation, groundwater mining, agricultural irrigation, and the like).
Similar principles have been formulated by the Waters of Wisconsin Project and by UNESCO’s
International Hydrology Programme (IHP), intercultural and interdisciplinary working group on
the Ethics of the Uses of Fresh water and by the COMEST Sub-Commission on the Ethics of
Fresh Water Use.
In respect to water management in a political point of view there are two main chains of
thought on the question: should water be privatised? One believes and recognizes the “right to
water” of all citizens of a given country and their collective responsibility, so there should be a
public management of the quality of sanitary service. The other called Neoliberal view does not
recognize the so called “right to water” to citizens and see water as a commercial good and can
accept terms like the “water market”, the “water industry” or the “water business”. This view
defends that the water from rivers, lakes, and other resources are property of the State in
name of the Nation but since human intervention transforms a natural resource into a service
that requires costs and investment, it is transformed in something with economical value,
which can be traded and appropriated. This concept has been accepted in the International
Conference on Water and Development organized by the United Nation in Dublin1992. It is
based on a principal that private investment is the motor of economical and social development
and that public investment should create a favorable environment for private investment. In an
ethical approach it may seem far from the principal of equity and justice but in an economical
point of view there are no individual or collective rights inherent to human beings, just civil
rights, so each person is merely a consumer or a client. There is a difference between
ownership and management of a resource and the private sector should benefit from their
public service even though it doesn’t have the political power of decision over the natural
resource. According to this point of view liberalization can assure the equal repartition of goods
and services by total and equal access to the market, and it is more a question of efficiency of
the market that determines social equality. The problem with this mercantilist view is that it is
very profitable for the private sector and stockholders but in fact it does not provide an actual
solution for populations with no sanitary systems especially from poor and developing
countries. There is a dis-equal disperse of private investment geographically and this situation
reinforces dis-equality which can prove the failure of this kind of neoliberal model, as the
private sector has failed to success in developing countries. Private enterprises have serious
problems with financial risks and contractual risks and restrictions in developing countries
which make it non-profitable to invest in the poorest areas. Also in Europe there are problems
of equity. For example in France the prices practiced by private companies are 15 to 20% higher
than the public sector. The government has to guarantee user rights monitoring the prices and
evaluating them in connection with transport costs to irrigation and water supply, purification
costs. Data must be shared with decision makers so they give have the tools to choose the best
solutions and increase efficiency of systems of utilization of water. They need to be technically
and morally informed (user rights, transaction costs, conflicts between users – i.e.
transboundary and common waters). In order with this assumption we have to consider
different situations in the world. In many regions women are the principal managers of water
resources in the society. Especially in small villages and communities where they use it for
domestic works, they are employed in irrigation more than men. But they rarely participate in
the debate about water management and this leads back to problem of involvement and
sharing information. In that sense, safeguarding women rights, in some cases means also
optimizing the utilization of goods. International co-operation plays a fundamental role in the
management of transboundary and common waters. To evaluate the value of this argument we
have to consider that 40% of the world population lives downstream and depends from the
water flow to survive; moreover the most part of major river systems are shared by five or
more countries because of their lengthiness, and all countries depend on the one where the
flow originates. In this case dams, withdrawals to irrigate, industrial pollution, salinization,
deforestation and soil erosion can decrease the amount of water for the depending countries. It
could be a great motive of international conflicts, especially if the involved nations have military
potential. The international community tried to solve also this problem by creating a plan for
regulation of shared water. The Food and Agriculture Organization (FAO) has identified many
treaties about non-navigational waters related in the years and based on rights, needs and
efficiency. The United Nation Convention on the Non-Navigational Uses of International
Watercourses, approved in 1997, gives a leading low to share fresh waters taking in
consideration geographic, ecological, economic and ethical notions. Unquestionably the “water
framework Directive 2000 / 60/ CE”, settled on 23 October 2000 by European Parliament, is the
most representative document about water resource management. It establishes a framework
to protect and improve the quality of aquatic ecosystem and to promote sustainable water use.
It also encloses every kind of water except the sea one: - Surface water (i.e. watercourses,
lakes, etc.) - Underground water - Coastal water (i.e. water estuary, etc.) The water framework
Directive arranges four important objectives: - protecting the aquatic ecosystem: acting a
dilation of toxic polluting substances, as mercury, atrezin, plumb, nickel; recycling and using
flowing back purified waters (art. 6); prevention and restoring of natural condition in case of
disasters; - promoting cooperation between different countries about international water ports
- management: fixing common methods to preserve water healthiness; - ensure drinking water
supplies: ensuring the right quantity of water when and where it’s necessary according to
solidarity’s common sense; - optimize water as a consumer good; - recognition of
hydrographical areas, which are defined as the whole of terrestrial and sea areas, including just
one or more than one bordering basin within respective underground and sea water of a limit
zone; - monitorising a correct pricing of services related with water. The principle goal of the
Directive would be the restore of “good water condition” for any European Union State within
2015. In a second term it aims to obtain an equal distribution and destination of the resource
between all involved countries and their citizens and to ensure a correct charge of the costs on
the users and managers. Moreover, it aspires to establish a correct way to manage the different
realities of hydrographical areas.
Chapter 4: Theory I
4.1- Introduction:
The theory section discusses the important components like the sensor and their
functionalities and several applied applications are also discussed. The process of how
the components are connected and used are also described.
4.2- The List of Components used in the project:
Necessary information was collected for the design to be successful and the required hardware
was collected accordingly. Various tools were used to build the circuit and assemble the
prototype. Also measures were taken to hold and protect the assembled circuitry and hold it
safely and protect the device. In this section, all the components that were used for the
purpose of building the project prototype has been provided along with all the specifications
for the sensors that were used for this Water Monitoring Device. The components that were
used to make this project are listed below with their working protocol and description:
1. Arduino UNO- Arduino Uno is a microcontroller board supported on the
ATmega328P (datasheet). It has fourteen digital input/output pins (of that six
pins may be used as PWM outputs), and the other half dozen as analog inputs, a
sixteen MHz quartz crystal, a USB connection, a power jack, ICSP header and a
reset button. It contains everything required to support the microcontroller;
merely connect it to a laptop or a computer with a USB cable or power it with an
AC-to-DC adapter or battery to get started. The operating voltage is 5V and there
are 14 digital I/O pins, it has one LED built in and is very lightweight.
Fig 4.1: Arduino UNO
2. Solar panel: A solar panel is a gathering of solar cells together which converts
light energy into electricity. There is no need of outside source of power when
solar panel is used. Using solar panels sunlight that is free can be converted to
electricity easily. Silicon is mostly used for solar panels. Photovoltaic solar panels
absorb sunlight as a source of energy to generate electricity. A photovoltaic (PV)
module is a packaged, connected assembly of typically 6x10 photovoltaic solar
cells. Photovoltaic modules constitute the photovoltaic array of a photovoltaic
system that generates and supplies solar electricity in commercial and residential
applications. In this project we have used a 10 watt solar panel which starts to
charge from the sunlight after it reaches 12volts.This made our project selfsufficient as the device do not need outside sources of power to generate itself.
Fig 4.2: Solar Panel
3. Analog Oxidation-Reduction Potential (ORP) sensor- ORP (Oxidation
Reduction Potential) is a standard water quality parameter that is ordinarily
measured as the voltage between a platinum measuring electrode and a
reference conductor. Usually ORP is based on standard hydrogen electrode as a
reference but commercial ORP’s use AgCl. The result from the ORP sensor
measures the oxidation and reduction reactions in the sample of water. Positive
results indicate oxidizing setting and negative result indicates a reducing setting.
ORP is measured in millivolts. The ORP sensor helps to determine the cleanliness
of water and to break down the impurities in water. An ORP sensor has probes
that dips into water, the electrode is made either of platinum or gold which in a
reversed manner loses its electrons to the oxidiser. The parameter set for our
ORP sensor was less than or equal to 400mv.
Fig 4.3: Oxidation-Reduction Potential Sensor
4. Analog Dissolved Oxygen (DO) sensor- Dissolved oxygen is one of the
foremost production factor in Bangladesh in fish culture. Loss of fish because of
reduction in dissolved oxygen content of water is not uncommon in fish ponds of
Bangladesh. Low level of oxygen decrease appetite and rate of growth of fish.
Continuous exposure to low dissolved oxygen makes the fish prone to diseases.
Oxygen deficiency seems a frequent hazard issue once the intensity of fish
production gets enlarged. The dissolved oxygen sensor helps to determine the
amount of oxygen dissolved or carried in the water body. The parameter that
has been set for DO sensor is below 4.00.
Fig 4.4: Dissolved Oxygen Sensor Probe
5. Analog Turbidity Sensor-Turbidity is the measure to which extend the water
loses its clarity due to presence of deferred particulates. This unwanted
substances present in the water makes it murky and cloudy and turbidity sensor
is used to measure the degree of transparency of water. This effects the life of
fish in water greatly as less freshwater means the yield of fish would decrease,
also more amount of fish would die. This arduino based sensor detects water
quality by its active level of muddiness. It can distinguish suspended particles in
water by assessing the light transmittance and scattering rate which varies with
the amount of suspended particle in water.
Fig4.5: Analog Turbidity Senso
6. Analog pH Sensor-The analog pH sensor detects the pH level of water that is it
should be less than 7.00 more accurately around 6.00. This pH sensor has probes
to measure pH level of the water by calculating the voltage or potential
difference of the solution in which it is dipped. By measuring potential
difference, hydrogen ion concentration can be calculated using the Nernst
equation which gives the relationship between Hydrogen ion concentration and
Voltage or Potential. Since the Arduino receives only analog readings from the
sensor, the values had to be manipulated from 0- 1023 into the standard for
reading pH levels which is from 0-14.
Fig 4.6: Analog pH Sensor
7. Electrical Conductivity/Salinity Sensor: The electrical conductivity
measures the capacity of water to conduct electrical current, it is directly related
to the concentration of salts dissolved in water and hence to the total dissolved
solids. Electrical conductivity can be measured using sensors and portable
meters. The commonly used units for measuring electrical conductivity of water
are microSiemens/cm or deciSiemen/cm. The parameter that is used for the EC
sensor is 550 us/cm. The electrical conductivity of the water depends on the
water temperature: the higher the temperature, the higher the electrical
conductivity would be.
Fig4.7: Analog Electrical Conductivity Sensor
8. Temperature Sensor-The temperature sensor plays a very important role in
many applications. They have contact sensors which includes thermocouples and
thermistors that touch the object they are to measur e and noncontact sensors
measure the thermal radiation a heat source releases to determine its
temperature. These are used to measure the water temperature to determine
how hot or cold it is.
Fig 4.8: Temperature Sensor (DS18B20)
9. Bluetooth Module- The Bluetooth module that is used in the project is HC 05.
It is connected to the android app that was created later on.
Fig 4.9: Bluetooth module (HC-05)
10. One LCD monitor was also used in the device to project the results on the
screen, a buzzer was implemented which goes off when the sensors cross their
parameters in lower or higher ranges.
Fig 4.10: LCD screen 20x4, (DIS00014)
11. Three batteries each of 4.2volts were used in the device. The purpose of the
batteries are to provide power to the prototype in case other external power
supplies are not used, and to store power from the 12V solar panel.
12. Wooden framework for solar panel and box. To hold the device and its
components safely.
Fig 4.11: Wooden frame and box.
13. A buzzer was used as an alarm in case of a harmful change in water conditions.
Fig 4.12: Buzzer Alarm for Arduino.
Chapter 5: Theory II:
5.1- Introduction:
The design of the device and connections to the circuitry are discussed in this section.
The various functionalities of different components used for the prototype are discussed
and how they were assembled and put together. The overall functionality of the device,
the working principle, as well as the different configurations are discussed as well.
5.2- Working Principle:
The goal of the device is to successfully sense some important factors in water
conditions. To achieve the goal, various sensors for the appropriate measurements are
chosen. Analog sensors are chosen so that the electronic data sent to the Arduino can
from the components can be manipulated with the Arduino code according to
convenience of the user. Analog Oxidation Reduction Potential (ORP) sensor, Analog
Dissolved Oxygen (DO) sensor, Analog pH sensor, Analog Salinity/Conductivity sensor
and Analog Turbidity sensor has been connected to the analog inputs of the
ArduinoUNO (A0, A1, A2, A4, A5). A Digital temperature sensor (DS18B20) has been
used for the fact that the digital temperature sensor is more reliable and further
manipulation of input signals is not required for temperature readings. It is connected to
a digital input of the ArduinoUNO (D2). All the connections to the microcontroller are
connected according to requirements and are coded for output to the LCD display and
via the Bluetooth module. The digital connections from the LCD display are connected
from the digital PWM of the ArduinoUNO (D3, D4, D5, D6, D9, D10), and the power
supply and ground connections for the LCD display is taken from the 5V supply of the
microcontroller. The Bluetooth module (HC-05) is connected to the digital PWM for
receiving and transmission of data, and similarly the power for the module is connected
to the supply and ground of the ArduinoUNO. A buzzer has been used on the for the
alarm, which is connected to the digital PWM of the ArduinoUNO (D11). A veroboard
has been cut, to solder and assemble an extension to the 5V and GND connections of
the ArduinoUNO as every module of the sensors and other components has significant
use of it, and the ArduinoUNO does not have enough connection ports. The whole
device explained is perfectly capable transmitting data to any handheld or Bluetooth
supported device and of displaying the information of water conditions on the LCD
Finally, the main power supply used for this device is a set of 3, 4.2V rechargeable
batteries which are series connected for a total of 12.6V, as the ArduinoUNO power
input is capable of handling voltages from 7-20 volts. The battery is connected to a 10W
Solar Panel which helps to charge the battery, in sunlight, making the device sustainable
and capable of fully charging the batteries for a great amount of runtime. This feature
makes the device capable of having self-sustained power, given the right conditions.
5.3- General Sensor Module Connections:
Each of the Analog sensor comes with a module which is a chip to connect the sensor to
any other microcontroller devices like the ArduinoUNO used for the prototype. Here,
the modules are designed by DFRobot, and are consisting of three significant
connections; power supply connections to the module for “+”, the GND connections for
“-” and the analog signal connections for the converted electric signals from the sensors
to be received into any microcontroller or converter device. The signals received from
the modules are usually in the range of 0 to 5 volts.
For the prototype, the “+” power supply are connected to a common node from the 5V
supply of the ArduinoUNO supply panel, which has been extended by the use of a
veroboard. Similar connections are established for the GND from ArduinoUNO to all the
GND of the sensor modules. A general circuit of the connections of the sensors to the
ArduinoUNO is shown below in Fig 5.1.
Fig 5.1: A general connection of the sensor module to the ArduinoUNO.
The actual connections are a lot more complicated, but eventually all the connections of
the modules follow to same pattern. All the analog connections are to the PWM of the
Arduino board from the modules, and connected to A0, A1, A2, A4, A5. The actual
connections are show below in Fig 5.2.
Fig 5.2: The connections of the complete device.
5.4: Battery and Solar panel:
A 10 Watts, 12V solar panel has been used which is connected to a set of three
batteries, each of which are 4.2 Volts. The batteries are rechargeable and are connected
in series to each other, and in parallel to the solar panel. The solar panel is capable of
charging the batteries under sunlight. Connecters has been used on the batteries and
the wires of the solar panel to use the connection of the battery and the solar panel
according to convenience, so a person could keep the solar panel separate from the
device when necessary. Another connector has been used to connect the battery to the
Arduino board, to provide power to the rest of the device.
Fig 5.3: Batteries connectio n.
Fig 5.4: Connectors from battery .
5.5: Analog Dissolved Oxygen (DO) Sensor:
Dissolved oxygen is one of the most important parameters for water quality. A good
water quality is very important for aquatic lives and water with greater DO is a sign of a
good water quality, and water with low DO will lead to difficulty in breathing for aquatic
lives and threaten the lives of aquatic organisms. The sensor used in the device is a
galvanic probe, the kind which usually uses a zinc or lead anode and a gold or silver
cathode and an electrolyte solution. Such sensors use 2 different types of metal and the
difference in them with the electrolyte results in an electromotive voltage. That voltage
is sent to the Arduino via the module and the information is received. The DO is
measured in milligrams per litre (mg/L).
Fig 5.5: The module for the DO sensor.
Analog Signal Output (0~3.0V)
VCC (3.3~5.5V)
Probe Cable Connector
Since, the sensor is a galvanic probe, some measures were taken to ensure the
calibration of the sensor. The electrolyte used in this sensor was NaOH solution. For a
new dissolved oxygen probe, 0.5 mol/L NaOH solution was added into the membrane
cap firstly as the filling solution. Also it was suggested that, if the probe has been used
for some time and the error grows greatly, it is time to change the filling solution.
Fig 5.6: The process of adding the solution to the probe.
Then, the sensor was connected to the Arduino board and dipped in water. The serial
monitor is used to calibrate the sensor to the electrolyte against the dissolved oxygen in
water. After calibration, the sensor is ready to be used for a long time. It was also
observed that the readings for the DO shows a great value initially when the device is
started or just dipped into water with different levels of DO, but the reading stabilized in
about 30-60 seconds.
5.6- Analog (ORP) Meter, pH Meter, Salinity Meter:
The analog oxidation reduction potential (ORP) meter is an important part of the device
which senses the ORP levels of the water. It is significant because in the current ever
growing world, contamination of water has become a great issue and water is the most
critical control point of contact where proper treatment can greatly reduce the
microbes, thereby reducing the chances of illness and pollution. ORP (OxidationReduction Potential) is a measure of the ability of oxidation and reduction of aqueous
solution, characterization of oxidizing or reducing the relative degree. Unlike a pH
measurement that follows a logarithmic curve and therefore requires more calibration
adjustments, ORP follows a linear relationship and does not need instrument
adjustment as much as it needs electrode maintenance. ORP has proven to be a reliable
method of measuring water quality and provides the operator with a single value of
measurement regardless of which product, commodity, operation, treatment or
sanitizer is used, and regardless of varying field conditions or method by which chemical
is applied. For the prototype the ORP is measured in millivolts (mV) and ranges from 2000mV to +2000 mV.
Fig 5.7: ORP reducing and oxidizing agents
A positive ORP indicates that the substances present in the water are oxidizing agents
and the negative indicates that the water has a presence of reducing agents. Beyond
this range of -400 to +400mV the water becomes harmful for aquatic life, hence the
device is designed to set off its alarm on such changes.
The ORP meter is connected to the Arduino in the same way as shown in the general
circuit connections for the sensor modules as shown in Fig 5.1.
For the pH sensor, any value below 7 indicates an acidic water and above 7 indicates
alkaline waters.
Fig 5.8 pH characteristics.
The device has been designed to set off the alarm when the pH is less than 6 or when it
greater than 8. A value below 6 would mean the water is acidic and unsuitable for
aquatic life, and a value above 8 would mean the water is alkaline and unsuitable for
many fishes in ponds. Fishes most thrive in waters that are closer to a pH of 7.
The Salinity/Conductivity of the water is measured by the analog salinity sensor. This
sensor functions similarly to the ORP and pH meter but in this case it is measure in
microSeimens or milliSeimens. For our device, it triggers the alarm when the electric
conductivity (EC) is greater than 550 microseimens since it is the condition where fresh
water aquatic organisms cannot thrive in such conditions or even not survive.
5.7- Digital temperature sensor and alarm:
The digital temperature sensor (DS18B20) is a waterproof probe that is useful for
measuring in any wet conditions. The sensor works properly up to 125 oC, while the
cable is jacketed with PVC, so must be kept under 100oC. Since the signal is digital, there
is no degradation in values and the reading for the temperature is highly accurate. The
temperature sensor is connected to the D2 terminal of the Arduino board, and proper
codes for it were placed for the device to show the value of the temperature in oC to the
nearest one decimal place.
The alarm has been connected to the D10 port of the Arduino board. It responds to
certain conditions of the water like conductivity, ORP, DO and pH. For harmful water
conditions, the Arduino is coded to set the alarm off. For example, when the ORP is
greater than +400mV, or when EC is greater than 500microSeimens, or when pH is less
than 6 or greater than 8, and when DO is lower than 4 mg/L, the alarm will set off and
not stop until the conditions have change to normal. The code for this is shown below:
Fig 5.9: Codes for the alarm conditions.
5.8- LCD display and Bluetooth module connections:
The LCD display used is a 20x4 display that always shows the values of the readings from
the sensors. Bluetooth module is connected according to its function where the
transmission of the Arduino is connected to the receiving end of the Bluetooth module,
and the receiving mode of the Arduino is connected to the transmission of the
Bluetooth module. The connections of the display and the Bluetooth module to the
Arduino board is shown below:
Fig 5.10: Circuit diagram of LCD and BT module.
5.9- Android application:
The android application is designed to connect to the Bluetooth (HC 05) only. It can
show the paired devices and connected devices and only connect to the HC-05. When
connected, the app displays the values that are shown on the LCD screen, on the display
portion of the android app as shown below in Fig 5.11:
Fig 5.11: Android app displaying the readings from the Arduino.
5.10- Finished Device and LCD reading:
The final product is shown in Fig 5.12 where the device has been enclosed in a wooden
casing and the sensors are put in a solution with a high pH value.
Fig 5.11: Final device.
Fig 5.12: LCD readings.
Chapter 6: Results and Observations
6.1- Requirement Analysis (Survey) :
We did a survey asking different people’s opinion on what could help them increase the yield of fish,
also what problems they face in the production process and this is the result:
From a private fish farmer—(Munshiganj, Sirajdikhan)
What is the main problem to maintain the yield of fish production?
-----The feed of the fish and to make sure the water is not overcrowded.
What conditions should be monitored for best water quality for fish production?
----- Water quality is not the main concern here, as they do not mostly understand it, for being a
small farm. But they want the water to be cleaner.
What measurements are being taken currently?
-----Any water quality was not necessary according to the farmer, but the depth of the water
and the area of the pond was important according to him.
What are they doing to maintain the conditions currently?
-----No specific things are being done to maintain the water conditions.
What solution can be provided?
-----Something that can help to increase the amount of fish production in a small area of pond,
at a lower cost.
What is the amount of loss?
----Sometimes the fish die due to bad water conditions and build-up of waste in the water. Fish
also die sometimes due to overcrowding of the pond. So, the losses vary depending on the
state, but usually they make a profit, since they buy fingerlings from the market and already
expect some of them to die.
How frequently does the loss happen?
-----Does not happen too frequently.
What is their response? How quick can they solve the problem?
-----They attempt to clean the pond of dead fish using a net and wait a few days before
releasing more fish.
What percentage of the fry/fingerling survive in the pond?
-----Around 30-40% of the fingerling die in the first few days of being introduced to the pond.
Are they using any devices? If so, what is the main function of the device and is it
working out for them?
-----No devices are being used.
What condition is required for specific type of fish?
-----Nothing specific for the type of fish they are using.
How much are they willing to spend, to maintain the water quality?
----- According to them, it will depend on the kind of device. But currently they are willing to
spend 10,000- 20,000 Tk on a working device if it actually helps to increase the yield, as they are
just a small fish farm and not a fishery.
AKM Fazlur Rashid
Owner, Rashfia Agro and Fisheries, Mymensingh
What conditions of water quality are needed to be monitored for fish production?
Basically we try to monitor the pH, Dissolved oxygen and Salinity of the water to our first
priority. Then comes the minerals part in the list.
What are the factors causing you troubles at most?
Dissolved oxygen so far is the biggest concern for us and the salinity is also a thing to be careful
about. Cause lack of oxygen and imbalance of salinity both lead to casualties.
What measurements are taken currently for the problems?
We have two caretakers for the fishery who check the water condition manually at regular
What steps do you take if you see any problems?
On the basis of our caretakers’ reports we tend to supply the necessary elements.
How much time do you need for the response to the raised problems?
There’s no fixed time yet that we have calculated. Sometimes it takes up to 6-8 hours to figure
out the real problem for us.
Why is that so? As you have said that you have men who keep tracks?
Yes we have them but they are not that skilled to minimise the loss.
How much money do you lose during the problems ?
On December, 2017 we lost 400 Kgs of fishes worth of 1,20,000 taka.
How frequently do these losses occur ?
Yearly we at least experience these losses twice.
Which fishes are high on demand if you have to save among the whole?
Generally we try to save as much as we can and to be honest you can’t even figure out which to be
saved initially when the conditions are against you. Still if i have to pick from the lot then I’ll go for the
Are you using any device for prevention?
No. Not yet.
Are you willing to own a device which will give you prevention from majority of these problems?
Yes. If that can alert us in advance then we would definitely give it a look.
How much are you willing to spend for a device which can alarm you?
We haven’t thought about that yet. Depends on the machine actually like what things it can
alarm about. But if it’s a complete device with the ability of detecting pH, temperature,
dissolved oxygen, minerals then I can spend 50,000 taka.
From a small private farm :( near Narayanganj,Sonargaon)
Personal interview was taken and various kind of answers were received through it.
How many ponds do you have in your farm?
Ans: Three ponds altogether connected by a common drainage system.
How many kinds of fish do you grown each year?
Ans: Many kinds of fish are grown or cultivated in the ponds like Rui,Katla,Hilsha,Shoal etc other
tiny fishes are also grown.
What process do you use to rear fish?
Ans: Very basic process is adapted by them to rear fish. We use limestone to keep the water
clean for the fish. Small fish or eggs of them are released in the water. Provides the fish with
fish food which are already made with many substances to keep them alive.
Do you use any devices to keep the quality of water well?
Ans: No.
What conditions are required for the fish to grow?
Ans: Nothing specific only good weather and to make sure the water doesn’t overflow or dry
What are the chances of loss in their business?
Ans: Loss does not occur frequently unless its market or economy related. Fish could die in any
uncertain way but it’s rare. Unless there is use of poison in the water, fish remains healthy.
Do you think if the water condition was better there would be even less loss?
Ans: “Maybe”. As they were not sure of it. Their concern is not that much about the water
quality because they are not aware of it.
8) What percentage of the fry/fingerling survive in the pond?
Ans: Few of them dies in the first few days. But as they start growing it gets better.
9) What is their investment throughout a year? Or how much are they willing to pay?
Ans: They would invest about 20,000 to 30,000 a year for the fish to rear and grow.
10) What is their response time when fish dies or loss occurs? How do they solve it?
Ans: They usually clean the water and try to pick out the dead fish by using a net. Sometimes
they change the food and put new fingerlings or small fish in the pond for them to grow.
11) Would you be willing to use a device that could track your problems in water and give you
less loss yearly and more benefit?
Ans: Yes we would at least consider to try it out.
6.2- Real life test result:
Water quality is deteriorated day by day due to numerous biological, physical and chemical
variables causing water toxicity. When concentration of any element or compound exceeds the
tolerance limit for organisms that element is treated as pollutants. Research work has been
carried out to determine some vital water quality parameters those abate the water quality and
find out the most vulnerable location of both Dhanmondi and Ramna Lake.The device was
tested in Dhanmondi Lake and the pond inside Ramna Park where there is production of fish in
the water. The pH value that we got in the Dhanmondi Lake water was 11.00 which is very high
as the average pH is between 6.00-7.00 . The EC value was also very high around 800 hence the
buzzer went off and an alert was sent to the device. When tested on the water in Ramna Park
the pH came around 8.5 which is also very high but not as high as the water in Dhanmondi Lake,
the turbidity value came around 4.5 NTU. The EC/Salinity value came around 650us/cm. The
alarzm went off this time as well because the collected values were higher than the expected
Chapter 7: Future Works
7.1- Introduction:
All the things discussed in this section will improve the efficiency of the target device
and even increase its functionalities and even make it more user friendly and decrease
its price to make it more available to people. By addition of some more equipment and
the use of better and improved sensors, the device can be improved in various ways.
The possible additional features are various mineral sensors, sensors for water
parameters, improved microcontrollers, improved sensors, better batteries and solar
panels, upgrading the android application, or even water proofing the device and
making it smaller and more portable.
7.2- More Sensors:
It is possible to add more sensors to the prototype given the right resources. The device
is perfectly capable of handling more sensors and receiving more data and sending the
necessary information to the users. Additional sensors for parameters such as
Ammonium ion (NH4), Nitrate ion (NO3-) and Nitrite ion (NO2+), since these are the
main factors that indicate the presence of excretory substances from living organisms,
so monitoring such factors could help to improve aquatic conditions for fishes. Also
other sensors for minerals and other ions can be used, for example, sensors for ions
(Fluoride (F-), Calcium (Ca2+), Chloride (Cl-), Iodide (I-), Lithium (Li+), Magnesium
(Mg2+), Potassium (K+), Sodium (Na+), Iron (Fe2+/Fe3+) etc. The detection of the
presence of such ions can be a great improvement to the overall capacity of output for
this device and enhance its capabilities. Some of these are already used by some
products such as Libelium, as discussed before.
7.3- Microcontrollers and ports:
The use of a similar microcontroller chip like the ATMega328P used in the ArduinoUNO,
into a different and more improved microchip can cause a great improvement in device
performance and fewer connections. In the current project, a lot of connections were
needed, due to the various sensors and all the required supplies, GNDs and analogs; but
the ArduinoUNO did not have enough supply ports for all the sensors, hence an
extension of a veroboard was used, where all the 5V supply and grounds were
extended. Also, the ArduinoUNO has a limited number of analog inputs which could
limit the amount of analog sensors used in case of an improvement in device. It can be
considered to design a custom microcontroller similar to the ArduinoUNO, but with
greater number of supply inputs and outputs, for it to be capable of supporting a lot
more components like the sensors.
7.4- Improved sensors:
Better sensors can greatly bring improvements to the quality of the device as it can then
provide data with better efficiency. Probes with better materials for the cathodes and
anodes used within them can help to give electronic readings of greater accuracy. Also
the price of the overall device can be reduced if the sensors were produced locally
instead of being required to import.
7.5- Improved batteries and solar panels:
The use of better batteries and solar panels can bring changes to the self-sufficient
factor of the device. A better battery can sustain a greater load and store a lot more
energy for the device to run throughout the day. An improved solar panel can sustain
better current flow in case of light, since the current solar panel requires a bright
sunlight for it to function properly. A better battery and solar panel tech can eventually
lead to better charge storage throughout the day, so the device can function on its
charge by night without a problem.
7.5- Upgraded Android App:
Newer features can be added to the android app to make it more user friendly and
according to the convenience of the user. Features like notifying the user during any
harmful changes in water conditions, saving daily data on the device so the user can
access it anytime one wants. The app can be made to graphically represent all the data
throughout the day and compare it to the conditions from another time. Also a cloud
server can be used to store send or receive information from the device and access it
through the app.
7.6- Actuators:
The use of actuators can be a very significant addition to this device since then it will not
only be capable of viewing the data to the user, but also take certain actions when
certain water conditions are at a harmful level. For example, in a scenario where the
water has lower levels of dissolved oxygen, an actuator can be a certain type of motor
which activates when the device detects that the oxygen levels in the water has
lowered. This motor in turn increases the oxygen levels of the water and eventually
when the sensors detect that the oxygen levels have improved, the device can send
signals to the motors again to make it stop. Such actuator devices can be used for all the
parameters of water accordingly to gain control over the conditions in water.
7.7- Waterproof device:
Since the main function of the device is around water bodies, its feasibility could have
been improved by making the whole device completely waterproof and floatable. A
waterproof device would be much easier for fish farmers to use as it becomes easier for
them to carry around water. Also, if the device is floatable, the device could be left on a
pond as the user receives data from it via Bluetooth or a cloud server if the right module
is used.
7.8- Conclusion:
Bangladesh is a fast growing and developing country and pollution hazard is an
enormous problem in this country where proper there are still shortages of proper
sanitation, drainage system and sewage treatment systems. All the pollution and
environmental changes are causing great changes to the water bodies of the nation and
could be affecting fish production.
It is necessary to monitor water conditions for safety measures and for the marine
organisms to survive as their survival is a necessity for the economy and the survival of
the people in general.
Through this project, we have learned various skills and learned the various significance
of such devices and how these can come to use. Its applications can be of great benefits
to the fishery and hatchery industries of Bangladesh,
Arduino Code
SoftwareSerial bt(7, 8);// for bt connection pin rx,tx
//#include <SoftwareSerial.h> // use the software uart
//SoftwareSerial bluetooth(0, 1); // RX, TX
#include <avr/pgmspace.h>
#include <EEPROM.h>
// stast EC
#include <OneWire.h>
#define StartConvert 0
#define ReadTemperature 1
int buzzer = 11;
LiquidCrystal lcd(3, 4, 5, 6, 9, 10);
const byte numReadings = 20;
//the number of sample times
byte ECsensorPin = A5; //EC Meter analog output,pin on analog 1
byte DS18B20_Pin = 2; //DS18B20 signal, pin on digital 2
unsigned int AnalogSampleInterval = 25, printInterval = 700, tempSampleInterval = 850; //analog sample interval;serial print
interval;temperature sample interval
unsigned int readings[numReadings];
byte index = 0;
// the readings from the analog input
// the index of the current reading
unsigned long AnalogValueTotal = 0;
// the running total
unsigned int AnalogAverage = 0, averageVoltage = 0;
// the average
unsigned long AnalogSampleTime, printTime, tempSampleTime;
float temperature, ECcurrent;
//Temperature chip i/o
OneWire ds(DS18B20_Pin); // on digital pin 2
// end EC
//start do
#define DoSensorPin A4 //dissolved oxygen sensor analog output pin to arduino mainboard
#define VREF 5000 //for arduino uno, the ADC reference is the AVCC, that is 5000mV(TYP)
float doValue;
//current dissolved oxygen value, unit; mg/L
//float temperature = 25; //default temperature is 25^C, you can use a temperature sensor to read it
#define EEPROM_write(address, p) {int i = 0; byte *pp = (byte*)&(p);for(; i < sizeof(p); i++) EEPROM.write(address+i, pp[i]);}
#define EEPROM_read(address, p) {int i = 0; byte *pp = (byte*)&(p);for(; i < sizeof(p); i++) pp[i]=EEPROM.read(address+i);}
#define ReceivedBufferLength 20
char receivedBuffer[ReceivedBufferLength + 1]; // store the serial command
byte receivedBufferIndex = 0;
#define SCOUNT 30
// sum of sample point
int analogBuffer[SCOUNT]; //store the analog value in the array, readed from ADC
int analogBufferTemp[SCOUNT];
int analogBufferIndex = 0, copyIndex = 0;
#define SaturationDoVoltageAddress 12
#define SaturationDoTemperatureAddress 16
//the address of the Saturation Oxygen voltage stored in the EEPROM
//the address of the Saturation Oxygen temperature stored in the EEPROM
float SaturationDoVoltage, SaturationDoTemperature;
//float averageVoltage;
const float SaturationValueTab[41] PROGMEM = {
14.46, 14.22, 13.82, 13.44, 13.09,
12.74, 12.42, 12.11, 11.81, 11.53,
11.26, 11.01, 10.77, 10.53, 10.30,
10.08, 9.86, 9.66, 9.46, 9.27,
9.08, 8.90, 8.73, 8.57, 8.41,
8.25, 8.11, 7.96, 7.82, 7.69,
7.56, 7.43, 7.30, 7.18, 7.07,
6.95, 6.84, 6.73, 6.63, 6.53,
//end do
//saturation dissolved oxygen concentrations at various temperatures
float pHpin = A0; // Connect the sensor's Po output to analogue pin 0.
float Po; // for data store
float turbidity = A2; // connect with turbidity sensor
float turvalue;
float turvoltage;
#define VOLTAGE 5.00 //system voltage
#define OFFSET 0
//zero drift voltage
double orpValue;
#define ArrayLenth 40 //times of collection
#define orpPin A1
//orp meter output,connect to Arduino controller ADC pin
int orpArray[ArrayLenth];
int orpArrayIndex = 0;
double avergearray(int* arr, int number) {
int i;
int max, min;
double avg;
long amount = 0;
if (number <= 0) {
printf("Error number for the array to avraging!/n");
return 0;
if (number < 5) { //less than 5, calculated directly statistics
for (i = 0; i < number; i++) {
amount += arr[i];
avg = amount / number;
return avg;
else {
if (arr[0] < arr[1]) {
min = arr[0]; max = arr[1];
else {
min = arr[1]; max = arr[0];
for (i = 2; i < number; i++) {
if (arr[i] < min) {
amount += min;
min = arr[i];
if (arr[i] > max) {
amount += max; //arr>max
max = arr[i];
} else {
amount += arr[i]; //min<=arr<=max
avg = (double)amount / (number - 2);
return avg;
void setup(void) {
bt.begin(9600); // communication degler for bt
lcd.begin(20, 4);
for (byte thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
TempProcess(StartConvert); //let the DS18B20 start the convert
AnalogSampleTime = millis();
printTime = millis();
tempSampleTime = millis();
pinMode(DoSensorPin, INPUT);
//read Characteristic Values calibrated from the EEPROM
pinMode(buzzer, OUTPUT);
pinMode(13, OUTPUT); // for LED status
//bluetooth.begin(9600); // start the bluetooth uart at 9600 which is its default
delay(200); // wait for voltage stabilize
//bluetooth.print("AT+NAMEmcuhq.com"); // place your name in here to configure the bluetooth name.
// will require reboot for settings to take affect.
delay(3000); // wait for settings to take affect.
void loop(void) {
turvalue = analogRead(turbidity);// read the input on analog pin 0:
Po = 1023 - analogRead(pHpin); // Read and reverse the analogue input value from the pH sensor.
Po = map(Po, 0, 1023, 0, 14); // Map the '0 to 1023' result to '0 to 14'.
turvoltage = turvalue * (5.0 / 1024.0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
static unsigned long orpTimer = millis(); //analog sampling interval
static unsigned long printTime = millis();
if (millis() >= orpTimer)
orpTimer = millis() + 20;
orpArray[orpArrayIndex++] = analogRead(orpPin); //read an analog value every 20ms
if (orpArrayIndex == ArrayLenth) {
orpArrayIndex = 0;
orpValue = ((30 * (double)VOLTAGE * 1000) - (75 * avergearray(orpArray, ArrayLenth) * VOLTAGE * 1000 / 1024)) / 75 OFFSET;
//convert the analog value to orp according the circuit
// start EC
if (millis() - AnalogSampleTime >= AnalogSampleInterval)
AnalogSampleTime = millis();
// subtract the last reading:
AnalogValueTotal = AnalogValueTotal - readings[index];
// read from the sensor:
readings[index] = analogRead(ECsensorPin);
// add the reading to the total:
AnalogValueTotal = AnalogValueTotal + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
// calculate the average:
AnalogAverage = AnalogValueTotal / numReadings;
Every once in a while,MCU read the temperature from the DS18B20 and then let the DS18B20 start the convert.
Attention:The interval between start the convert and read the temperature should be greater than 750 millisecond,or the
temperature is not accurate!
if (millis() - tempSampleTime >= tempSampleInterval)
tempSampleTime = millis();
temperature = TempProcess(ReadTemperature); // read the current temperature from the DS18B20
//after the reading,start the convert for next reading
Every once in a while,print the information on the serial monitor.
if (millis() - printTime >= printInterval)
printTime = millis();
averageVoltage = AnalogAverage * (float)5000 / 1024;
//Serial.print("Analog value:");
//Serial.print(AnalogAverage); //analog average,from 0 to 1023
//Serial.print(" Voltage:");
//Serial.print(averageVoltage); //millivolt average,from 0mv to 4995mV
//Serial.print("mV ");
//Serial.print(temperature); //current temperature
float TempCoefficient = 1.0 + 0.0185 * (temperature - 25.0); //temperature compensation formula: fFinalResult(25^C) =
float CoefficientVolatge = (float)averageVoltage / TempCoefficient;
if (CoefficientVolatge < 10)Serial.println("No solution!"); //25^C 1413us/cm<-->about 216mv if the
voltage(compensate)<150,that is <1ms/cm,out of the range
else if (CoefficientVolatge > 3300)Serial.println("Out of the range!"); //>20ms/cm,out of the range
if (CoefficientVolatge <= 448)ECcurrent = 6.84 * CoefficientVolatge - 64.32; //1ms/cm<EC<=3ms/cm
else if (CoefficientVolatge <= 1457)ECcurrent = 6.98 * CoefficientVolatge - 127; //3ms/cm<EC<=10ms/cm
else ECcurrent = 5.3 * CoefficientVolatge + 2278;
ECcurrent /= 1000; //convert us/cm to ms/cm
Serial.print(ECcurrent, 2); //two decimal
// start do
static unsigned long analogSampleTimepoint = millis();
if (millis() - analogSampleTimepoint > 30U) //every 30 milliseconds,read the analog value from the ADC
analogSampleTimepoint = millis();
analogBuffer[analogBufferIndex] = analogRead(DoSensorPin); //read the analog value and store into the buffer
if (analogBufferIndex == SCOUNT)
analogBufferIndex = 0;
static unsigned long tempSampleTimepoint = millis();
if (millis() - tempSampleTimepoint > 500U) // every 500 milliseconds, read the temperature
tempSampleTimepoint = millis();
//temperature = readTemperature(); // add your temperature codes here to read the temperature, unit:^C
static unsigned long printTimepoint = millis();
if (millis() - printTimepoint > 1000U)
printTimepoint = millis();
for (copyIndex = 0; copyIndex < SCOUNT; copyIndex++)
analogBufferTemp[copyIndex] = analogBuffer[copyIndex];
averageVoltage = getMedianNum(analogBufferTemp, SCOUNT) * (float)VREF / 1024.0; // read the value more stable by the
median filtering algorithm
//Serial.print(temperature, 1);
doValue = pgm_read_float_near( &SaturationValueTab[0] + (int)(SaturationDoTemperature + 0.5) ) * averageVoltage /
SaturationDoVoltage; //calculate the do value, doValue = Voltage / SaturationDoVoltage * SaturationDoValue(with
temperature compensation)
//Serial.print(F(", DO Value:"));
//Serial.print(doValue, 2);
lcd.setCursor(0, 3);
lcd.print(F("DO Value:"));
lcd.print(doValue, 2);
if (serialDataAvailable() > 0)
byte modeIndex = uartParse(); //parse the uart command received
doCalibration(modeIndex); // If the correct calibration command is received, the calibration function should be called.
// end do
if (millis() >= printTime) //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
printTime = millis() + 800;
//Serial.print("ORP: ");
//Serial.print("Turbidity: ");
//Serial.print(temperature); //current temperature
//Serial.println(" C");
//Serial.print(ECcurrent, 2); //two decimal
//Serial.print(F("DO Value:"));
//Serial.print(doValue, 2);
lcd.setCursor(0, 0);
lcd.setCursor(8, 0);
lcd.setCursor(0, 1);
lcd.setCursor(9, 2);
lcd.print(ECcurrent*850, 1); //two decimal
lcd.setCursor(0, 2);
lcd.print((int)temperature); //current temperature
//lcd.setCursor(0, 3);
//lcd.print(F("DO Value:"));
//lcd.print(doValue, 2);
String no1 = " PH: ";
String no2 = " ORP ";
String no3 = "mV " ;
String no4 = " Turbidity: ";
String no5 = "V ";
String no6 = " temp: ";
String no7 = "C ";
String no8 = " EC: ";
String no9 = "us/cm ";
String no10 = " DO Value: ";
String no11 = " mg/L ";
String E = String(ECcurrent*850, 2);
String D = String(doValue,2);
String main = no1 + Po + no2 + orpValue + no3 + no4 + turvoltage + no5 + no6 + temperature + no7 + no8 + E + no9 + no10 +
D + no11;
//bt.print("PH: ");
//bt.print("ORP: ");
// bt.println("mV");
// bt.print("Turbidity: ");
// bt.print(turvoltage);
// bt.println("V");
// bt.print("temp:");
// bt.print(temperature); //current temperature
// bt.println(" C");
// bt.print(ECcurrent*1000, 2); //two decimal
// bt.println("ms/cm");
// bt.print(F("DO Value:"));
// bt.print(doValue, 2);
// bt.println(F("mg/L"));
// bt.println("");
// bt.println("");
if (Po > 8.00 || Po < 6.00 || (int)orpValue > 400||(ECcurrent*850) > 550 || doValue < 4.00)
digitalWrite(buzzer, HIGH);
digitalWrite(buzzer, LOW);
Serial.print("ORP: ");
bt.print("PH: ");
bt.print("ORP: ");
float TempProcess(bool ch)
//returns the temperature from one DS18B20 in DEG Celsius
static byte data[12];
static byte addr[8];
static float TemperatureSum;
if (!ch) {
if ( !ds.search(addr)) {
Serial.println("no more sensors on chain, reset search!");
return 0;
if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return 0;
if ( addr[0] != 0x10 && addr[0] != 0x28) {
Serial.print("Device is not recognized!");
return 0;
ds.write(0x44, 1); // start conversion, with parasite power on at the end
else {
byte present = ds.reset();
ds.write(0xBE); // Read Scratchpad
for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
byte MSB = data[1];
byte LSB = data[0];
float tempRead = ((MSB << 8) | LSB); //using two's compliment
TemperatureSum = tempRead / 16;
return TemperatureSum;
/// start do
boolean serialDataAvailable(void)
char receivedChar;
static unsigned long receivedTimeOut = millis();
while ( Serial.available() > 0 )
if (millis() - receivedTimeOut > 500U)
receivedBufferIndex = 0;
memset(receivedBuffer, 0, (ReceivedBufferLength + 1));
receivedTimeOut = millis();
receivedChar = Serial.read();
if (receivedChar == '\n' || receivedBufferIndex == ReceivedBufferLength)
receivedBufferIndex = 0;
return true;
} else {
receivedBuffer[receivedBufferIndex] = receivedChar;
return false;
byte uartParse()
byte modeIndex = 0;
if (strstr(receivedBuffer, "CALIBRATION") != NULL)
modeIndex = 1;
else if (strstr(receivedBuffer, "EXIT") != NULL)
modeIndex = 3;
else if (strstr(receivedBuffer, "SATCAL") != NULL)
modeIndex = 2;
return modeIndex;
void doCalibration(byte mode)
char *receivedBufferPtr;
static boolean doCalibrationFinishFlag = 0, enterCalibrationFlag = 0;
float voltageValueStore;
switch (mode)
case 0:
if (enterCalibrationFlag)
Serial.println(F("Command Error"));
case 1:
enterCalibrationFlag = 1;
doCalibrationFinishFlag = 0;
Serial.println(F(">>>Enter Calibration Mode<<<"));
Serial.println(F(">>>Please put the probe into the saturation oxygen water! <<<"));
case 2:
if (enterCalibrationFlag)
Serial.println(F(">>>Saturation Calibration Finish!<<<"));
EEPROM_write(SaturationDoVoltageAddress, averageVoltage);
EEPROM_write(SaturationDoTemperatureAddress, temperature);
SaturationDoVoltage = averageVoltage;
SaturationDoTemperature = temperature;
doCalibrationFinishFlag = 1;
case 3:
if (enterCalibrationFlag)
if (doCalibrationFinishFlag)
Serial.print(F(">>>Calibration Successful"));
Serial.print(F(">>>Calibration Failed"));
Serial.println(F(",Exit Calibration Mode<<<"));
doCalibrationFinishFlag = 0;
enterCalibrationFlag = 0;
int getMedianNum(int bArray[], int iFilterLen)
int bTab[iFilterLen];
for (byte i = 0; i < iFilterLen; i++)
bTab[i] = bArray[i];
int i, j, bTemp;
for (j = 0; j < iFilterLen - 1; j++)
for (i = 0; i < iFilterLen - j - 1; i++)
if (bTab[i] > bTab[i + 1])
bTemp = bTab[i];
bTab[i] = bTab[i + 1];
bTab[i + 1] = bTemp;
if ((iFilterLen & 1) > 0)
bTemp = bTab[(iFilterLen - 1) / 2];
bTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2;
return bTemp;
void readDoCharacteristicValues(void)
EEPROM_read(SaturationDoVoltageAddress, SaturationDoVoltage);
EEPROM_read(SaturationDoTemperatureAddress, SaturationDoTemperature);
if (EEPROM.read(SaturationDoVoltageAddress) == 0xFF && EEPROM.read(SaturationDoVoltageAddress + 1) == 0xFF &&
EEPROM.read(SaturationDoVoltageAddress + 2) == 0xFF && EEPROM.read(SaturationDoVoltageAddress + 3) == 0xFF)
SaturationDoVoltage = 1127.6; //default voltage:1127.6mv
EEPROM_write(SaturationDoVoltageAddress, SaturationDoVoltage);
if (EEPROM.read(SaturationDoTemperatureAddress) == 0xFF && EEPROM.read(SaturationDoTemperatureAddress + 1) == 0xFF
&& EEPROM.read(SaturationDoTemperatureAddress + 2) == 0xFF && EEPROM.read(SaturationDoTemperatureAddress + 3) ==
SaturationDoTemperature = 25.0; //default temperature is 25^C
EEPROM_write(SaturationDoTemperatureAddress, SaturationDoTemperature);
Android app:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:text="Toggle LED"
android:textStyle="bold" />
android:text="Reading From Arduino"
android:textStyle="bold|italic" />
android:text="&lt;Read Buffer>" />
android:textStyle="bold" />
android:text="&lt;Bluetooth Status>"
android:textStyle="bold" />
android:text="Bluetooth ON" />
android:text="Bluetooth OFF" />
android:text="Show paired Devices" />
android:text="Discover New Devices" />
android:choiceMode="singleChoice" />
package com.mcuhq.simplebluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
// GUI Components
private TextView mBluetoothStatus;
private TextView mReadBuffer;
private Button mScanBtn;
private Button mOffBtn;
private Button mListPairedDevicesBtn;
private Button mDiscoverBtn;
private BluetoothAdapter mBTAdapter;
private Set<BluetoothDevice> mPairedDevices;
private ArrayAdapter<String> mBTArrayAdapter;
private ListView mDevicesListView;
private CheckBox mLED1;
private final String TAG = MainActivity.class.getSimpleName();
private Handler mHandler; // Our main handler that will receive callback notifications
private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random"
unique identifier
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
protected void onCreate(Bundle savedInstanceState) {
mBluetoothStatus = (TextView)findViewById(R.id.bluetoothStatus);
mReadBuffer = (TextView) findViewById(R.id.readBuffer);
mScanBtn = (Button)findViewById(R.id.scan);
mOffBtn = (Button)findViewById(R.id.off);
mDiscoverBtn = (Button)findViewById(R.id.discover);
mListPairedDevicesBtn = (Button)findViewById(R.id.PairedBtn);
mLED1 = (CheckBox)findViewById(R.id.checkboxLED1);
mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mDevicesListView = (ListView)findViewById(R.id.devicesListView);
mDevicesListView.setAdapter(mBTArrayAdapter); // assign model to view
// Ask for location permission if not already allowed
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
mHandler = new Handler(){
public void handleMessage(android.os.Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
if(msg.what == CONNECTING_STATUS){
if(msg.arg1 == 1)
mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj));
mBluetoothStatus.setText("Connection Failed");
if (mBTArrayAdapter == null) {
// Device does not support Bluetooth
mBluetoothStatus.setText("Status: Bluetooth not found");
Toast.makeText(getApplicationContext(),"Bluetooth device not found!",Toast.LENGTH_SHORT).show();
else {
mLED1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(mConnectedThread != null) //First check to make sure thread created
mScanBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mOffBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mListPairedDevicesBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
mDiscoverBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
private void bluetoothOn(View view){
if (!mBTAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
mBluetoothStatus.setText("Bluetooth enabled");
Toast.makeText(getApplicationContext(),"Bluetooth turned on",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
// Enter here after user selects "yes" or "no" to enabling radio
protected void onActivityResult(int requestCode, int resultCode, Intent Data){
// Check which request we're responding to
if (requestCode == REQUEST_ENABLE_BT) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
private void bluetoothOff(View view){
mBTAdapter.disable(); // turn off
mBluetoothStatus.setText("Bluetooth disabled");
Toast.makeText(getApplicationContext(),"Bluetooth turned Off", Toast.LENGTH_SHORT).show();
private void discover(View view){
// Check if the device is already discovering
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
if(mBTAdapter.isEnabled()) {
mBTArrayAdapter.clear(); // clear items
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
final BroadcastReceiver blReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name to the list
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
private void listPairedDevices(View view){
mPairedDevices = mBTAdapter.getBondedDevices();
if(mBTAdapter.isEnabled()) {
// put it's one to the adapter
for (BluetoothDevice device : mPairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
if(!mBTAdapter.isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
// Spawn a new thread to avoid blocking the GUI one
new Thread()
public void run() {
boolean fail = false;
BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
// Establish the Bluetooth socket connection.
try {
} catch (IOException e) {
try {
fail = true;
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
if(fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, BTMODULEUUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if(bytes != 0) {
buffer = new byte[1024];
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
} catch (IOException e) {
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes();
//converts entered String into bytes
try {
} catch (IOException e) { }
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
} catch (IOException e) { }
Random flashcards
Arab people

15 Cards


39 Cards


30 Cards


17 Cards

Create flashcards