You are on page 1of 77

DEVELOPMENT OF AN AUTOMATIC WATER

TANK TEMPERATURE CONTROL BASED ON


ARDUINO MICROCONTROLLER

NORSYAZWAN HAZMI BIN NORZAIDI

UNIVERSITI MALAYSIA PAHANG


DEVELOPMENT OF AN AUTOMATIC WATER TANK TEMPERATURE CON-
TROL BASED ON ARDUINO MICROCONTROLLER

NORSYAZWAN HAZMI BIN NORZAIDI

This thesis is submitted as partial fulfilment of the requirements for the award of the
Bachelor of Electrical Engineering (Hons.) (Electronics)

Faculty of Electrical & Electronics Engineering


Universiti Malaysia Pahang

JUNE 2016
i

UNIVERSITI MALAYSIA PAHANG

DECLARATION OF THESIS AND COPYRIGHT

Student’s Full Name : NORSYAZWAN HAZMI BIN NORZAIDI


Identification Card No : 931217-12-6452
Title : DEVELOPMENT OF AN AUTOMATIC WATER
TANK TEMPERATURE CONTROL BASED ON
ARDUINO MICROCONTROLLER

Academic Session : SEMESTER II 2015/2016

I declare that this thesis is classified as:


(Contains confidential information under the
CONFIDENTIAL Official Secret Act 1972)

(Contains restricted information as specified by


RESTRICTED the organization where research was done)*

I agree that my thesis to be published as online


OPEN ACCESS open access (Full text)

I acknowledge that Universiti Malaysia Pahang reserve the right as follows:


1. The Thesis is the Property of University Malaysia Pahang.
2. The Library of University Malaysia Pahang has the right to make copies for the purpose
of research only.
3. The Library has the right to make copies of the thesis for academic exchange.

Certified by:

(Student’s Signature)

931217-12-6452 Ahmad Nor Kasruddin B. Nasir


New IC / Passport Number Name of Supervisor

Date: 1 JUNE 2016 Date: 1 JUNE 2016


ii

SUPERVISOR’S DECLARATION

I hereby declare that I have checked this thesis and in my opinion, this thesis is adequate
in terms of scope and quality for the award of the degree of the Bachelor Degree of
Electrical Engineering (Hons.) (Power Systems).

Signature :
Name of Supervisor : Dr. Ahmad Nor Kasruddin Bin Nasir
Position : Lecturer
Date : 1 JUNE 2016
3

STUDENT’S DECLARATION

I hereby declare that the work in this thesis is my own except for quotations and summaries
which have been duly acknowledged. The thesis has not been accepted for any degree and
is not concurrently submitted for award of other degree.

Signature :
Name : Norsyazwan Hazmi Bin Norzaidi
ID Number : EA12017
Date : 1 JUNE 2016
4

A special thankful is dedicated to my beloved mother, father, brothers and lectur-


ers for support and encouragement.
5

ACKNOWLEDGMENTS

First of all, I would like to convey my gratitude to Almighty Allah for giving me
the strength and the abilit to complete this project of “Development of an automatic water
tank temperature control based on Arduino microcontroller”.
I am using this opportunity to express my deepest appreciation and special
thanks to my supervisor, Dr. Ahmad Nor Kasruddin bin Nasir who in spite of being
extraordinarily busy with his duties, took time out to hear, guide and keep me on correct
path and allowing me to carry out the final year project. His endless encouragement for
me to finish the better results is appreciated.
My deepest heartfelt gratitude to my family especially my parents, for all what
they do and still doing, to help me be at this level and for their continuous support and
encouragement that made this task becomes much easier to be implemented.
Last but not least, I would like to dedicate a special thanks to my friends,
housemates, and those who involve directly or indirectly in this project. Finally, I hope
all the experience and knowledge gained during this process can give benefit and ad-
vantage to all. Thank you.
6

ABSTRACT

The purpose of this project is to develop and modelling of water tank for tem-
perature control automatically using Arduino microcontroller. The prototype of 10 litre
water tank consists of temperature sensor, level sensor, Arduino microcontroller, water
pump, heating element, LCD display and the system performance is analysed by Matlab
software. First, a prototype of water tank is built. The water pump will stop automatical-
ly pump the water into the tank when the level of water reach the highest point of water
level sensor. After that, the heating element starting to heat the water until reach the
desired temperature. The current temperature of water, the desired temperature of water
and the level of water is displayed on the LCD. Then run some tests on the prototype to
collect data of input and output of the system. The important part of this project is to
control the system in order to make it automatic. PID controller will be used to control the
temperature of water so that the temperature will maintain at its desired temperature.
vii

ABSTRAK

Tujuan projek ini adalah untuk membangunkan dan pemodelan tangki air untuk
kawalan suhu automatik menggunakan mikropengawal Arduino. Prototaip tangki air 10
liter terdiri daripada sensor suhu, sensor tahap, mikropengawal Arduino, pam air, ele- men
pemanas, paparan LCD dan prestasi sistem di analisis oleh perisian Matlab. Per- tama,
prototaip tangka air dibina. Pam air akan berhenti secara automatik mengepam air ke
dalam tangka apabila paras air mencapai titik tertinggi sensor paras air. Selepas itu,
elemen pemanasan bermula untuk memanaskan air sehingga mencapai suhu yang
dikehendaki. Suhu semasa air, suhu yang dikehendaki air dan paras air dipaparkan pada
LCD. Kemudian menjalankan beberapa ujian ke atas prototaip untuk mengumpul data
input dan dan output system. Bahagian yang penting dalam projek ini adalah untuk
mengawal system untuk membuat ia automatic. PID pengawal akan digunakan untuk
mengawal suhu air supaya suhu akan dikekalkan pada suhu yang dikehendaki.
88
8

TABLE OF CONTENTS

Page
SUPERVISOR’S DECLARATION ii
STUDENT’S DECLARATION iii
DEDICATION iv
ACKNOWLEDGEMENT v
ABSTRACT vi
ABSTRAK vii
TABLE OF CONTENTS viii
LIST OF TABLES xi
LIST OF FIGURES xii
LIST OF ABBREVIATIONS xiv

CHAPTER 1 INTRODUCTION
1.1 Introduction 1
1.2 Problem statement 2
1.3 Objectives 3
1.4 The scopes of project 3
1.5 Thesis roadmap 4

CHAPTER 2 LITERATURE REVIEW


2.1 Arduino
2.1.1 Arduino UNO 6
2.2 Temperature sensor 7
2.3 Soil moisture sensor 8
2.4 Heating element 9
2.5 Water pump 10
2.6 Relay 11
2.6.1 Electromechanical relay 11
9

2.6.2 Solid state relay 14


2.7 Liquid crystal display 16
2.8 PID controller 17

CHAPTER 3 METHODOLOGY
3.1 Project flow chart 21
3.1.1 Title of project 22
3.1.2 Research/Literature review 22
3.1.3 Learn and training 22
3.1.4 The installation hardware and software 22
3.1.5 Result and analysis 22
3.2 System flow chart and block diagram 23
3.3 Hardware implementation 26
3.3.1 Soil moisture sensor module circuit 27
3.3.2 Temperature LM35 sensor circuit 28
3.3.3 The heating element and relay circuit 29
3.3.4 The water pump circuit 30
3.3.5 The LCD display circuit 31
3.4 Software implementation 32
3.4.1 Standalone coding system 34
3.4.2 Analysis coding system 35

CH PTER 4 RESULTS AND DISCUSSION


4.1 Introduction 37
4.2 Hardware maintenance and repairing 37
4.3 PID controller analysis 38
4.3.1 The analysis of P mode 39
4.3.2 The analysis of PI mode 42
4.3.3 The analysis of PID mode 44
4.4 The limitation of project 47
1
0

CHAPTER 5 CONCLUSION AND RECOMMEN-


DATION
5.1 Conclusion 48
5.2 Recommendation/future work 49

REFERENCES 50
APPENDICES 51
A The program code for standalone system 51
B The program code for analysis system in 54
Arduino IDE software
C The program code for analysis system in 57
Matlab software
1
1

LIST OF TABLES

Table No. Title Page


2.1 Pin configuration of LM35 7

2.2 Soil moisture sensor pin description 8

2.3 The parts of relay and its function 12

2.4 The 16×2 LCD pin description 16

3.1 Pin connection of I2C LCD display and Arduino Uno 31

4.1 The effect of PID controller 38


xii

LIST OF FIGURES

Figure No. Title Page


2.1 Arduino UNO 6

2.2 LM35 sensor 7

2.3 Soil moisture module and LM393 driver 8

2.4 The immersion coil heating element 9

2.5 12V DC water pump 10

2.6 The design of relay 12

2.7 Songle SRD-05VDC-SL-C Relay 13

2.8 SSR-25 DA circuit 15

2.9 SSR-25 DA Relay 15

2.10 16×2 alphanumeric LCD 16

2.11 PID loop 17

2.12 The effect of varying the Kp 18

2.13 The effect of varying the Ki. 19

2.14 The effect of varying the Kd 20

3.1 Project flow chart 21

3.2 Flow chart of automatic water tank temperature control 24

3.3 Closed loop block diagram 25

3.4 The placement of temperature LM35 sensor 25

3.5 The block diagram of input and output system 26

3.6 Placement of soil moisture sensor 27

3.7 Connection of soil moisture sensor and LM 393 driver 28


13

3.8 Heating element circuit 29

3.9 The water pump circuit 30

3.10 I2C 16×2 LCD display connection 31

3.11 Flow chart of software development 32

3.12 Error in the coding 33

3.13 Arduino IDE software 34

3.14 Matlab software 35

3.15 The graph of temperature response 36

4.1 Burnt heating element 37

4.2 The data P1 graph 39

4.3 The data P2 graph 40

4.4 The data P3 graph 41

4.5 The data PI.1 graph 42

4.6 The data PI.2 graph 43

4.7 The data PI.3 graph 43

4.8 The data PID.1 graph 45

4.9 The data PID.2 graph 45

4.10 The data PID.3 graph 46

4.11 The ideal PID parameters for this project 47


14

LIST OF ABBREVIATIONS

A Ampere

AC Alternate current

AO Analog output

ASCII American Standard Code for Information Interchange

DC Direct current

DO Digital output

IDE Integrated Development Environment

LCD Liquid crystal display

LED Light emitting diode

PID Proportional Integral Derivative

PV Process variable

PWM Pulse width modulator

SP Set point

USB Universal Serial Bus

V Volts
CHAPTER 1

INTRODUCTION

1.1 INTRODUCTION

Nowadays, it is important to have automatic control system especially involving


the processes in the industry. In industrial processes, control system are important to
control process variables like temperature, pressure, concentration and level so that they
are in specific range of set points. Basically, this project is about development of an
automatic system which can control temperature of water in a tank without human in-
tervention. For this project, temperature is selected as process variables.

Temperature control has been widely used in many industry processes, e.g.,
heating boilers/tanks/barrels for various chemical and metallic products, crystal ovens and
electric-resistance furnaces [1]. The temperature control system is a system with a high
thermal inertia which is the responsiveness of materials to the variation of the tem-
perature [2]. Therefore it is always challenging to have a good control system. Usually
during the heating process of materials in order to achieve desired temperature shows a
certain range of heating. This is due to the heat convection or radiation loss into the en-
vironment.

Besides that, the processes in the industry involving controlling the temperature
have their certain limit of temperature that they must follow according to the law. This
show the importance of temperature control in the industry so that they can operate the
business legally [3].
2

1.2 PROBLEM STATEMENTS

There is gradual development or evolving in industrial process nowadays. Back


to the past few years, industrial process has the difficulties of controlling the process
variables to reach and maintain it at some desired or set points. For example, fermenta-
tion tank that produce methane which is hard to detect the reaction temperature product
gas. Generally methane reactions are difficult to control without automatic control sys-
tems. Methane is a combustible and unstable gas so it is important to control the con-
centration of output gas [4]. It is vital for industrial process to have an automatic system
in their control processes.

The demanding of temperature control systems kept increasing in this modern life.
In order to follow the rapid growing of this control system, a new control system which
can keep and control temperature at the desired temperature without paying atten- tion to
it is designed. This is because the limitation for human supervision that is not last long for
several days or hours. A continuous control of temperature is essential in most- ly of
chemical processes and human are not able to monitor it for a certain long period. An
extra worker is needed to monitor it thus will result in addition cost. Besides that,
automatic temperature control system will reduce the safety risk of charge man where
no one is responsible to control the temperature of chemical substances.
3

1.3 OBJECTIVES

The main objectives for this project are:


1) To develop a temperature control system that can be implement at water
tank so it can be an automatic system which can achieve desired tem-
perature of water.
2) To fabricate the automatic water tank temperature control Arduino based
using PID controller.

1.4 THE SCOPES OF PROJECT

The scope for this project is limited to the measuring and control temperature
range between 40°C and 60°C. Hence the main requirement for this project are:

1) The users are allow to insert the desired value of temperature between the
ranged given.
2) Display the current temperature, desired temperature and current water level on
LCD.
4

1.5 THESIS ROADMAP

This project consists of five chapters:

Chapter 1: An overview of the project with introduction of automatic control


systems. It also explain about the problem statements, objectives and scope of
the project.

Chapter 2: The literature review is more focus on the explanation of the com-
ponents and devices used for this project.

Chapter 3: Covers the methodology and process flow chart of the system. The
discussion about implementation of hardware and software is detailed.

Chapter 4: The experiment is carried out and all the experimental result is dis-
cussed in this section.

Chapter 5: Concludes the overall project and recommend for the future studies.
CHAPTER 2

LITERATURE REVIEW

This chapter will explain about the component or device required for this project. Some
research need to do first based on previous project which is related to this project before
identify and specify the types and details of the component that will be used.

2.1 ARDUINO

Arduino is an open-source prototype that using single-board microcontroller


which is written in Arduino programming language, a simplified version of C++ pro-
gramming language. There are sixteen versions of the Arduino board that have pro-
duced which are:
1) Arduino 101/Genuino 101
2) Arduino Zero
3) Arduino Due
4) Arduino Yun
5) Arduino Leonardo
6) Arduino UNO
7) Arduino Mega 2560
8) Arduino Ethernet
9) Arduino Fio
10) Arduino Nano
11) Lilypad Arduino
12) Arduino Pro
13) Arduino Mega ADK
6

14) Arduino Esplora


15) Arduino Micro
16) Arduino Pro Mini

2.1.1 Arduino UNO

Arduino UNO is selected for this project. Arduino board is expensive compared
to the other microcontroller platforms. Besides that, it is simple and clear programming
environment which is easy-to-use for the beginner but flexible enough for advanced
users to take advantages of as well.

Figure 2.1: Arduino UNO

Arduino UNO is a microcontroller based on the ATmega328P. It has 14 digital


input and output pin where 6 of it can be used as PWM outputs, 6 analog inputs, a 16
MHz quartz crystal, a USB plug, a reset button, a power jack, and an ICSP header. It
contains everything needed to support the microcontroller, simply connect it to a com-
puter with a USB cable or power it with an AC-to-DC adapter or battery to get started.
7

The board can operate on an external supply from 6 volts to 20 volts. If sup-
plied with less than 7V, however, the 5V pin may supply less than 5V and the board
become unstable. If using more than 12V, the voltage regulator may overheat and dam-
age the board. The recommended board range is 7 to 12 volts. There is a feature of most
Arduino boards that they have an LED and load resistor connected between pin 13 and
ground, a convenient feature for many simple tests.

2.2 TEMPERATURE SENSOR

The temperature sensor used for this project is LM35. LM35 is a precision inte-
grated circuits that output voltage is linearly proportional to the Celsius (°C) tempera-
ture. The LM35 can operate over a temperature range of -55°C to +150°C with accura-
3 1
cies ±4°C and ±4°C at room temperature. It is suitable for this project which temperature
range is from 40°C to 60°C. The sensor circuitry of LM35 is sealed, so it is not subject-
ed to oxidation and other processes. Therefore the temperature measured with LM35 is
more accurate compared to temperature measured with thermistor.

The LM35 can be supplied from 4V to 30V and for this project, it is directly
supplied with 5V from Arduino microcontroller. The output voltage varies by 0.01V in
response to every °C rise/fall in ambient temperature. It also has low self-heating and does
not cause more than 0.1°C temperature rise in still air.
8

Figure 2.2: LM35 sensor

Table 2.1: Pin configuration of LM35


Pin No. Pin Name Function
1 Vcc Supply voltage (-2V to +35V)
2 Output Output voltage (-1V to +6V)
3 Ground Ground (0V)

2.3 SOIL MOISTURE SENSOR

Basically, soil moisture sensor is used to measure the water content in the soil.
And mostly the application area of this sensor is at water plant irrigation system. It will
determine how much of water needed to irrigate the plant. For this project, soil moisture
sensor is used to detect the presence of water at certain level in the tank. There is two parts
of the soil moisture sensor which soil moisture module and the LM393 driver. The soil
moisture module is connected to the LM393 driver as shown in Figure 2.3.

Figure 2.3: Soil moisture module and LM393 driver

LM393 driver have two independent low voltage comparators that operate
from a single supply over a wide range of voltages from +2V to +36V or ±1V to ±18V.
It also have a unique characteristic that is input common-mode range voltage includes
ground.
9

Table 2.2: Soil moisture sensor pin description.


Pin No. Pin Name Description
1 Vcc Supply voltage (5V)
2 Ground Ground (0V)
3 DO Digital output interface (0 and 1)
4 AO Analog output interface

2.4 HEATING ELEMENT

In this project, immersion heating element is used to heat the water in the tank.
The heating element convert the electrical energy into the heat energy. For this project,
the smart heater is needed that consist of heating element with necessary arrangement and
control for sending current through it safely. The heating element is generated when the
current passed through the heating element. It works with 220V AC power supply. The
capacitance of heating element is sometimes permanently installed in the tank or vessels
in the industries to heat liquid or viscous materials.

Figure 2.4: The immersion coil heating element


10

2.5 WATER PUMP

12V DC water pump is used in this project to supply water into the tank auto-
matically. The motor used for this water pump is DC brush motor. The operating volt-
ages of this pump from 9V to 12V while minimum operating current is 0.2A. The flow
rate of water pump is 200 litre per hour or 2-3 litre per minute. The maximum suction
lift is 1.5 metre and the water flow out can lift up till 3 metre. The water temperature
that can be handle by this water pump is 80°C which suitable for this project.

Figure 2.5: 12V DC water pump


11

2.6 RELAY

Relay is a switch that can works electrically or electromechanically which is


actuated by a relatively small current that can turn on or off a much larger electric cur-
rent by having an amplifying effects. This is because a small voltage applied to a relay
coil can cause a large voltage being switched by the contacts. Relay is used as protective
relays that detect and isolate all the faults such as overload and reverse current during
transmission and prevent equipment from damage. They are also used to provide delay
time when open and close contacts. Besides that, relays also used to switch the starting
coils, heating elements and pilot lights. There are two types of relays which are:
i. Electromechanical relay (EMR)
ii. Solid state relay (SSR)

2.6.1 Electromechanical Relay (EMR)

Electromechanical relay is a device of electro-magnetic that convert magnetic


flux into a pulling mechanical force when a low voltage electrical control signal either
direct current (DC) or alternate current (AC) is applied across the relays terminal which
operates the electrical contacts within the relay. The electromechanical relay is rated by
amount of the current that its switch contact can handle. Typical application using
EMRs include computers, copy machine, and other consumer electronic equipment and
appliances.
12

There are four basic parts in electromechanical relay:

Table 2.3: The parts of relay and its function


No. Name Function
1 Armature A relays moving part that close or open the contacts.
A spring is attached to armature so it can return to its
original position.
2 Coil The coil of wire that wound around a metal core
which produces an electromagnetic field.
3 Contacts The conducting part of the switch that closes or opens
a circuit.
4 Frame A heavy duty frame that contains and supports the
parts of relay.

Figure 2.6: The design of relay


13

The EMR design is divided into two circuit which are energizing circuit that has coil
and the contact circuit that has relay contacts. When the current is flow through the coil,
the coil is energized hence creates a magnetic field. The magnetic field will attract a
plate which is part of armature. The metal frame is attached to the one end of armature,
so that the armature can pivot, while the other end can break or connect the contacts.
There are several number of configuration in contacts which depends on number of
Poles, Breaks, and Throw. For example, Single Pole Single Throw (SPST) or Double
Pole Double Throw (DPDT). These configuration will give an indication of the design
and function of relays. The relay used for this project is single 5v relay board 3 pin in-
terface.

Figure 2.7: Songle SRD-05VDC-SL-C Relay

With a simple high or low signal, this relay can control high-power devices up to 10A.
The required voltage for relay power is 5V DC and its input signal voltage is from 3.3V
to 5V while the requirement current for this relay power is 85mA. Besides that, it has 3
pin servo-style header for power/signal interface. It also provides isolation between the
microcontroller and the device being controlled. This relay can operated at temperature
between -25°C and +70°C. The advantages of EMRs are low cost, multiple poles are
available, no heat sink is required, and easy to switch AC or DC.
14

2.6.2 Solid State Relay (SSR)

In electromechanical relay, the contacts are open or close by magnetic force but
opposite with solid state relay because there is no contacts and switching is totally elec-
tronic. SSR is divided into three parts of circuit:

i. Input circuit
The part of a relay frame that connected the control component. Its func-
tion same as the coil of EMR which the circuit is energized when a volt-
age higher than maximum specified Pickup Voltage of the relay is ap- plied
to the relays input. The circuit is de-energized when the voltage is lower
than the relays specified minimum Dropout Voltage. The range of voltage
between 3 VDC and 32 VDC.

ii. Control circuit


The part of relays that determine when the output component is activated
or de-activated. The function of control circuit is as the coupling between
the input and output circuits.

iii. Output circuit


The part of relay that switches on the load and same function as the me-
chanical contacts in EMR. Usually, the solid state relay has one output
contact only.
15

Figure 2.8: SSR-25 DA circuit

The semiconductor device of SSR used light from light emitting diode (LED)
usually infrared (IR) LED instead of magnetism to turn on a switch. When power is
applied to the output of the device, the LED light will turn on and shines across an open
space. The light emitted from other side will trigger the solid state switch on the load
side to open or close the circuit under control. The advantages of the solid state relays
are no contact bounce so no moving part, fast response and long life when properly
used.

Figure 2.9: SSR-25 DA Relay

The model used for this project is SSR-25 DA which operated load current
rated at 25A. The range input voltage between 3V DC and 32V DC. The current needed
to trigger the solid state relay is 7.5mA and the control method for this model is zero
cross trigger. The range output voltage for this model between 24 V AC and 380 V AC.
16

2.7 Liquid Crystal Display (LCD)

Liquid crystal display (LCD) commonly used in electronic projects to display


the messages or values of variable. There are many types of LCD depending on the var-
ious sizes and shapes on the configurations. The most widely used nowadays is 16×2
alphanumeric LCD. The most important part of LCD is a liquid crystal coating which
placed between two polarized glasses.

The 16×2 alphanumeric LCD as shown in Figure 1.7 is used for this project to
display the current water level and temperature. A 16×2 alphanumeric LCD means that
it has 32 characters for 2 horizontal lines which is display 16 characters for every row.
The characters can be displayed from ASCII values ranging from 0 to 255.

Figure 2.10: 16×2 alphanumeric LCD

Table 2.4: The 16×2 LCD pin description


17

2.8 Proportional Integral Derivative (PID) Controller

PID controller is widely used algorithm in industrial control systems for the pur-
posed of achieving and maintaining of a process set point. It is a control loop feedback
mechanism that attempt to correct the error which the difference between the current value
of process variable and the desired value. [5] In order to control loops to work properly,
the PID controller must be tuned properly. The PID controller can adjust the outputs of
the process based on history and rate of change in error signal that give more accurate
and stable control. [6] Based on the Figure 2.10, the ideal equation of PID con- troller can
be obtained.

where u(t) is the control signal and e is the control error. The process variable, PV, is
also called the desired value and SP is set point.

Figure 2.11: PID loop


18

Based on this formula, the control signal is the summation of three parameters which
are:

1) Proportional term (Kp)

Proportional term gives an output value that is proportional to the current error.
In order to adjust the proportional response, a constant Kp, called the proportion-
al gain is multiply with error. The proportional term is given by:

where Pout is proportional output, Kp is proportional gain, e is error which (e =


SP – PV) and t is the present time or instantaneous time.

The effect of varying the proportional gain will change the output response. A
small proportional gain will cause a small output response to a large input error
and a less sensitive or less responsive controller while a high proportional gain
will cause a large change in the output for a given change in the error. If the
proportional gain is too high, the system will become unstable.

Figure 2.12: The effect of varying the Kp


19

2) Integral term (Ki)

The integral term is the average past error over time. The simple proportional
system either moving back and forth around the set point due to the there is
nothing to remove the error when it oscillates, stabilize or overshoots. When the
process input is added up by a proportion of the average errors, the average dif-
ference between set point and process output can be reduced. The integral term
is given by:

The integral time speed up or boost the movement of the process towards set
point and eliminate the residual steady-state error. But when the integral term is
respond to accumulate errors from the past, it can cause the present value to
overshoot the set point value.

Figure 2.13: The effect of varying the Ki.


20

3) Derivative term (Kd)

The derivative term in simple words is the prediction of future errors based on
linear interpolation. It also called as “Predictive controller”. The derivative term
can control the response to a change in the system. The higher the derivative
term, the faster the controller responds to change in the output of process. A PID
controller loop can be categorized as a filter applied to a complex frequency-
domain system. It is helpful to calculate whether it will actually reach a stable
value. The derivative term is given by:

The rate of change of controller output is slow when use the derivative term. The
magnitude of the overshoot produced by integral component is reduced as result
of controlling derivative. It also improve the combined controller-process stabil-
ity. The derivative controller is highly sensitive to noise in the error term due to
the differentiation of signal amplifies noise in the signal. If the noise and the de-
rivative gain is high, there is high possibility that the process become unstable.

Figure 2.14: The effect of varying the Kd


CHAPTER 3

METHODOLOGY

In order to complete this project, some methodologies are used to achieve the
objectives and complete the project. A systematic planning will give a good result and
finish it on time as scheduled. There are some methodologies used for this project that
will be discussed in this chapter.

3.1 PROJECT FLOWCHART

Start Title

project

Research/
Literature Review

Learn and training

Install hardware
& software Result

& Analysis End

Figure 3.1: Project flow chart


22

3.1.1 Title of project

This project started when student need to find the title of final year project that is
listed by faculty. After getting approval from supervisor chosen, the objective, the scope
and problem statement of project need to be clear.

3.1.2 Research/Literature review

All the research that is related to the title project have been done. At this stage, all
the equipment and component that is used for this project is determined and studied like
Arduino board, water pump, heating element and others.

3.1.3 Learn and training

At this stages, its all about familiarize with Arduino microcontroller and pro-
gramming in software used which is Matlab. Each functions in the Arduino program-
ming language and Matlab need to be learnt. Attend some courses that is related to this
project such as real-time control and monitoring with Simulink – Arduino.

3.1.4 The installation hardware and software

The most important part of this project which is installation of all the component
and equipment used such as Arduino board, relay, heating element and others. All the
circuit designed is tested. Besides that, all the program that has been write in the Ar-
duino sketch is uploaded into the Arduino board. Troubleshooting is crucial at this stag-
es if the circuit designed or the programming is not working.

3.1.5 Result and analysis

At this stages, all the data from the Matlab is collected. Then analysis is made
based on the data collection.
23

3.2 SYSTEM FLOWCHART AND BLOCK DIAGRAM

The automatic water tank temperature control is generally designed for control-
ling the heating element that will automatic off when temperature of water reach set
point setting by user. The prototype of automatic water tank is designed based on
the system flow chart, block diagram, and control diagram. Flow chart in Figure 3.1
shows the process of automatic water temperature control using PID controller.

The type of process loop used in this project is closed loop (Figure 3.2). The us-
er will enter desire temperature of water which is the process variable of this project.
The difference between the desired temperature and the current temperature is called
the error and determine whether water is overheated or not. Then water is pump into
the tank. The water pump will continue pumping the water until the level of water
reach certain level which soil moisture sensor situated. When there is water around
the soil moisture sensor, the pump will automatically stopped.

After that, the heating element is turn on. The temperature LM35 sensor is sit-
uated at the bottom of the tank as shown in Figure 3.3. This sensor will measure the
current temperature of water in tank and then sending the current ampere signal to
the PID controller. Based on the desired temperature inserted, the actions of per-
centage voltage applied to the coil of relay is determined. If the current temperature
of water is lower than the desired temperature, the PID controller will send the sig-
nal to the solid state relay to continue increase the current flow through the heating
element so that increase the temperature of heating element. If the current tempera-
ture of water is higher than the desired temperature, the PID controller will send the
signal to solid state relay to cut off the current flowing through heating element for a
specific period of time hence decrease the current temperature until reach the de-
sired temperature. The process of turn on and turn off the heating element is contin-
uous to reach the desired temperature of water.
24

Start

Enter desired
temperature

Water is pump
into tank

Yes
Add water?

No
Water pump stop

Heating element
is turn on

Is Tcurrent > No
Tdesired?

Yes

Heating element
is turn off

LCD display current tem-


perature and level of water

End

Figure 3.2: Flow chart of automatic water tank temperature control


25

Figure 3.3: Closed loop block diagram

LM35

Figure 3.4: The placement of temperature LM35 sensor


26

3.3 HARDWARE IMPLEMENTATION

The equipment and device used have been introduced in the previous chapter.
For this section, the connection from one equipment to another is explained here.

Figure 3.5: Block diagram of input and output system

As shown in the Figure 3.4 above, the inputs of this project are soil moisture
sensor and temperature LM35 sensor. The soil moisture sensor is used as water level
indicator while the LM35 sensor is used measure the current temperature of water in the
tank.

A controller is needed to control all the process of the project and the micro-
controller used for this project is Arduino UNO. The Arduino can heat the water by
turning on the heating element (which is control) and it can measure the temperature
with temperature sensor (which is feedback). PID algorithm is a type of feedback con-
trol. PID algorithm is needed in order to keep the temperature of water stable at desired
temperature.
The outputs of this project are 12V DC water pump, heating element and 16×2
LCD display.
27

3.3.1 Soil moisture sensor module circuit

Soil moisture sensor is placed at the top of tank as shown in the Figure 3.5 to
indicate the highest level of water can reach. Soil moisture sensor is connected to the
LM393 driver as shown in the Figure 3.6. The ground pin of the soil moisture is con-
nected to ground pin of LM393 driver and the signal pin of soil moisture sensor is con-
nected to the signal pin of LM393 driver. Then there are 3 pin of LM393 driver is con-
nected to the Arduino Uno which is:
1) Reading is retrieved from analog input pin 1 of Arduino (A1) is connected to the
analog output pin (AO) of LM393 driver.
2) The ground pin of LM393 is connected to the ground pin of Arduino Uno.
3) The power supply 5V from Arduino is connected to the Vcc of the LM393 driv-
er.

The LM393 driver that is connected to the soil moisture module gives a low
output when there is no presence of water near the sensor and vice versa. Based on the
input pin A1, the Arduino gives a low output that will display on the LCD when no
presence of water near the sensor and gives a high output when the water touch the sen-
sor.

Soil moisture
sensor

Figure 3.6: Placement of soil moisture sensor


28

Figure 3.7: Connection of soil moisture sensor and LM 393 driver

3.3.2 Temperature LM35 sensor circuit

The temperature LM35 sensor as shown in Figure 2.2 is used for this project to
sense the temperature of water in the tank. The LM35 sensor is connected to the Ar-
duino through the analog input pin A0, 5V supply pin and ground pin. When this sensor
sense the current temperature of water, the data in output voltage is sent to the Arduino
through analog input pin A0. Then this data is converted into byte value in the down-
loaded Arduino program by multiplying with (2^8 bits/5V). This bytes value is convert-
ed in decimal value to display it on the LCD. The byte values are used to represent the
temperature range that will trigger the output devices. If the current temperature of wa-
ter is below the desired temperature, the relay circuit is activated to turn on the heating
element for heating purpose.
29

3.3.3 The heating element and relay circuit

Figure 3.8: Heating element circuit

The heating element and relay is the most important device in this project. It is
because the power from Arduino microcontroller output alone is not possible to control
the heating element which is AC voltage. Figure 3.7 above shows the connection of
Arduino, relay and heating element.

1) The analog output pin (AO11) from Arduino is connected to input 3 relay pin.
2) The pin 4 of SSR is grounded to ground pin of Arduino.
3) Pin 1 of SSR is connected to the live wire of plug switch (power supply).
4) Pin 2 of SSR is connected to the live wire of heating element.

Then the neutral wire of plug switch and heating element is combined and connected.
Same goes to ground wire from plug switch and heating element is connected. The relay
is activated when input voltage of relay is higher than maximum specified Pickup Volt-
age of the relay and deactivated when the voltage is lower than minimum Dropout Volt-
age.
30

3.3.4 The water pump circuit

Figure 3.9: The water pump circuit

12V DC water pump is used in this project to pump water into the tank auto-
matically. The connection wire of the water pump circuit can be seen in the Figure 3.8.

1) The analog output of the pin 7 (AO7) is connected to the input pin of relay.
2) The ground pin of Arduino is connected to the ground pin of relay.
3) The 5V supply voltage of Arduino is connected to the Vcc pin of relay.
4) The normally open (NO) pin of relay is connected to the negative/ground pin of
water pump.
5) The COM pin of relay is connected to the negative/ground of DC power supply.
6) The positive/Vcc pin is connected to the positive pin of DC power supply.

The range voltage of water pump is between 9V to 12V. The principle used for this wa-
ter pump is Bernoulli’s principle that states the speed of fluid increase when the pres-
sure is decrease. Air is flow along with water and there is an impeller inside the pump.
This impeller makes the air move fast that causing a pressure drop. The low pressure
inside the impeller cause the water to be drawn up the bottom tube and flow out the
tube.
31

3.3.5 The LCD display circuit

The I2C interface 16×2 LCD display is used in this project to display the current
temperature of water, the desired temperature of water and the level of water. The ad-
vantage of this I2C LCD is the data can be display by connecting only 2 wires. Besides
that, the contrast of LCD can be adjusted by spinning the potentiometer clockwise to
increase contrast and spinning anti-clockwise to decrease it.

Figure 3.10: I2C 16×2 LCD display connection

Table 3.1: Pin connection of I2C LCD display and Arduino Uno
32

3.4 SOFTWARE DEVELOPMENT

There are two software used which is Arduino Integrated Development Envi-
ronment (IDE) and Matlab. For Arduino software (IDE), the programming in this pro-
ject is separated into two type coding systems which are standalone system and analysis
system. Standalone system will start operate automatically when 5v power supply is
connected to the Arduino. It means that once coding is uploaded to the Arduino, it will
do specific task on one’s own in condition Arduino is connected to the 5v power supply.

The analysis system is specifically programmed to do analysis of the result


which for this project, the Matlab is used to show the graph of temperature response.
For this analysis system, there are two coding which are the coding at Arduino IDE
software and the coding in Matlab. There are many ways to write PID algorithm. The
PID library in Arduino IDE software that self-contained is used to write PID algorithm.
Hence it is easier to understand the coding. Besides that, it also can do complex stuff
such as having 8 PIDs in the same program.

Start

Study some coding of


devices used from pre-
vious projects

Write coding for all sen-


sors and devices used.

Error in cod- Troubleshoot


ing? the errors

Uploaded into the Ar-


duino

End
33

Figure 3.11: Flow chart of software development.

The Figure 3.10 shows the process of software development in this project. First of all,
the process learning and studies of the Arduino IDE software and Matlab is done in or-
der to achieve the objectives of this project. Besides that, the research about some pro-
jects which used both software that is related with this project. Then after familiarize
with some functions and files in both software, the coding is written and verify it. If
there is an error in the coding, it will shows at which line of coding that is wrong like in
Figure 3.11 below. Then troubleshoot the errors based on the warning given at the bot-
tom of Arduino IDE software.

Figure 3.12: Error in the coding


34

3.4.1 Standalone coding system

For standalone system, the software used only Arduino IDE software. All the
coding is written in this Arduino IDE software. Then verify the coding to ensure there is
no error in the coding. If there is no error, the coding is uploaded to the Arduino board.
But before upload the coding, the USB port must be checked first whether it is connect-
ed to the right COM port. The coding of standalone system can be refer at the appendix.

Figure 3.13: Arduino IDE software.


35

3.4.2 Analysis coding system

The analysis coding system involves two software which are Arduino IDE soft-
ware and Matlab software. The files of program in the Matlab can have code for more
than one function. The main function is visible to other files and the main function for
this project is MainScript.m as shown in Figure 3.13 below. While subroutines is the
additional functions within the files. The subroutine can occur in any order as long as
the main function appear first. Each function begins with its own function definition
line. There are two subroutines in this project which are readTemp.m and setupSerial.m.
There is slightly difference of the standalone coding system but the method to upload it
still same. After upload the coding in Arduino IDE software, then run the coding in the
Matlab software. Later the graph in Figure 3.14 will pop-up to show the current temper-
ature of water in certain time. The analysis coding system can be refer in the appendix.

Figure 3.14: Matlab software


36

Figure 3.15: The graph of temperature response


CHAPTER 4

RESULTS AND DISCUSSION

4.1 INTRODUCTION

In this project, the experiment is carried out repeatedly in order to get variation
of data and determined the best performance of result. Besides that, there is some hard-
ware damage during this project is carried out. The cause of hardware damage and its
solution is discussed in this chapter.

4.2 HARDWARE MAINTENANCE AND REPAIRING

During this project is carried out, the heating element is burnt as the effect of the
heating element is not properly dip into the water. After that incident, water level sys- tem
is proposed in order to overcome this matter. With this system, the heating is only
switched on when the water flow into the tank reach certain level of tank which is safe
for heating element to start heat. The burnt heating element is replaced with the new
one.
38

Figure 4.1: Burnt heating element


4.3 PID CONTROLLER ANALYSIS

PID controller tuning the system means that three gain which are Kp, Ki and Kd
is adjusting by sum up the various amount of these function in order to get the sys-
tem achieve the objectives of this project. Based on the Table 4.1 below, all the PID
parameters is tested by using method trial and error. This is the simplest method to
tune the PID controller. The integral gain and derivative gain is set first to zero.
Then the proportional gain is increased until the output of control loop oscillates at
a constant rate. An increasing of proportional gain will make the response of sys- tem
faster.

Table 4.1: The effect of PID controller


39

This project is carried out by varying each of PID parameters which the analysis upon
the tank filled with water had been made into 3 section:
1. P Mode
2. PI Mode
3. PID Mode
All set point (SP) temperature in this experiment is set to 45°C because faster result can
be obtained.

4.3.1 – The analysis of P mode

A high proportional gain (Kp) will cause a large change in the output for a given
change in the error. In this project, the proportional gain will affect the time taken
of heater to heat. The higher the P gain, the longer time taken by heater to heat be-
fore it rest. In P mode, the integral gain and derivative gain is set to zero first. Then
the proportional gain is increased until the control loop output oscillates at a con-
stant rate. Test and verify that the proportional gain maintaining at minimum offset
and overshoot while allows maximum rise to set point. The three set of parameters
is stated as below:

1) Data P1: Kp=50; Ki=0; Kd=0.


2) Data P2: Kp=300; Ki=0; Kd=0.
3) Data P3: Kp=900; Ki=0; Kd=0.
40

Figure 4.2: The data P1 graph

If the P gain is small gain (less than 50), the heating element will heat only a while be-
fore it rest. There is no overshoot happened because the water is heat so slow. A small
proportional gain will cause a small output response to a large input error and resulting
a less sensitive or less responsive controller.
41

Figure 4.3: The data P2 graph

Figure 4.4: The data P3 graph


42

Based on the Figure 4.3 and Figure 4.4, the system become unstable as result of too
high proportional gain where the heating element still continue to heat even after tem-
perature of water reach the desired temperature of water because high proportional gain
take longer heating time before rest. For examples in the graph of data P3, the first
overshoot is at 58°C and the heating element will heat quite along again because high
proportional gain cause large change in error and will make the system become unsta-
ble.

Too low of proportional gain will result the system take a long time to reach
desired temperature while too high proportional gain will result the system is unstable.
The proportional gain should be around 100 and 150 where gain over 150 will result of
unstable system.

4.3.2 – The analysis of PI mode

Once the proportional band is optimum and stable, the integral gain is set to reduce
the oscillations gradually. The integral gain is adjusted until the steady-state error is
reduced. However it may cause the system is overshoot. In this mode, P is made
constant to 150 and D gain is set to 0. The three set of parameters is stated as be- low:

1) Data PI.1: Kp=150; Ki=100; Kd=0.


2) Data PI.2: Kp=150; Ki=500; Kd=0.
3) Data PI.3: Kp=150; Ki=1000; Kd=0.
43

Figure 4.5: The data PI.1 graph.

Figure 4.6: The data PI.2 graph.


44

Figure 4.7: The data PI.3 graph.

The integral gain is respond to accumulate errors from the past and it
can cause the present value to overshoot the set point value. If the integral gain
is high, a faster output is obtained hence encourage faster process toward desired
temperature eliminate residual steady-state error that occurs with a P only con-
troller. For this project, integral gain affect the time taken of heating element
will rest before resume heating. Based on all the 3 graphs above, the shape of the
graph starting to oscillate compare to the P mode analysis.

If the integral gain is too high, it will give faster rise time but promotes
the output to oscillate and higher overshoot as shown in Figure 4.7. From the
Figure 4.5, too low integral gain will give lower rise time and encourage oscil-
lating as well. The graph of PI.2 also give output to oscillate, but the overshoot
is lower compare to the others two. The integral gain recommended is between
500 and 600 in order to get fast response of output.
45

4.3.3 – The analysis PID mode

After proportional gain and integral gain is set to a minimal steady state error, the
derivative gain is increase until the system give fast respond to its set point. An in-
creasing of derivative gain will decrease the overshoot of the controller response. In
this PID mode, the proportional gain and the integral gain are made constant to 150
and 600. The derivative gain is varies to get the variation in result. The three set of
parameters is stated as below:

1) Data PID.1: Kp=150; Ki=600; Kd=200.


2) Data PID.2: Kp=150; Ki=600; Kd=700.
3) Data PID.3: Kp=150; Ki=600; Kd=1000.

Figure 4.8: The data PID.1 graph.


46

Figure 4.9: The data PID.2 graph.

Figure 4.10: The data PID.3 graph


47

The derivative gain have a tendency to slow the rate of change of controller out-
put but for this project, the system only consist heating mechanism and there is
no cool down mechanism so the derivative gain plays minor role compare to the
proportional gain and integral gain. But theoretically the derivative gain act as
counter part of proportional gain and integral gain which is to overcome the in-
stability and overshoot. And usually the derivative gain is 4 times smaller of in-
tegral gain or lower than that.

Based on the Figure 4.8, the graph shows small overshoot and smooth rise time
which is optimum for this system while the graph in Figure 4.9 and Figure 4.10,
the system is unstable and high overshoot. The recommended derivative gain is
between 100 and 150 in order to get the best ideal for this project system. The
ideal value of PID parameters are Kp=150; Ki=600; Kd=150.

50

45

40

35

30

25

20

15
0 5 10 15 20 25 30 35 40 45 50

Figure 4.11: The ideal PID parameters for this project.


48

4.4 THE LIMITATIONS OF PROJECT

The project limitation come up after simulation which the hot water in the tank
which is being heated up to desired temperature need to cool down until reach room
temperature. It takes a long time to wait the water in the tank totally cooled down before
starting next experiment to get a new data.

Besides that, limitation of project happened at PID application which there is


no cool down mechanism when the water temperature is higher than desired tempera- ture
that caused overshoot. The only way to achieve steady state after is by cool down
naturally. So there must be some improvement for the future works.
CHAPTER 5

CONCLUSION AND RECOMMENDATION

5.1 CONCLUSION

The development of the automatic water tank temperature control based on Ar-
duino microcontroller has been presented. The implementation of hardware and the
simulation software achieved the objectives of this projects which to fabricate a temper-
ature control system at water tank so it can be an automatic system which can achieved
the desired temperature of water and developed the automatic temperature control Ar-
duino based using PID controller. For this project, the research of the PID theory has been
proved as the result of the analysis from the graphs obtained for each parameters and
tuning it until reach desired temperature.
50

5.2 RECOMMENDATION/ FUTURE WORK

Based on the results of this project, there are some suggestion for improvement
of this system that are:

1) Design a system of water flow out of the tank so the hot water can be renew with
new water at room temperature. So the next experiment can be done quickly
since does not need to wait water temperature cool down to room temperature.
2) Design a system that has cool down mechanism which can maintain the temper-
ature at its desired water temperature. For example, use PID controller to control
the speed of fan in order to maintain the desired temperature of water.
51

REFERENCES

This guide is prepared based on the following references;

[1] Tao Liu, Ke Yao and Furong Gao , “ Identification and auto-tuning of temperature
control system with application to injection molding”, IEEE transactions on control
systems technology, vol. 17, no. 6, November 2009.

[2] Md Mafizul Islam and Md Abdul Salam, “Modelling and control system design to
control water temperature in heat pump”, December 2013.

[3] P.Bhargava, B.Prasanna Kumar, J.Ramesh Babu and S.Venkatesh, “Temperature


control using analog PID controller”, 2012

[4] Ziyu Liu, “Automatic control for a gas system using PIC microcontroller”, March
2013

[5] Mohd Aizuddin Bin Abu Bakar, “Development of a PID controller for DC motor
using Microsoft Visual Basic”, November 2008.

[6] Muhd Asran Bin Abdullah, “Water level in tank using level sensor and PID control-
ler”, November 2008.
52

APPENDIX A

The program code for standalone system


53

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);
#include <PID_v1.h>
int w=8;
int pump=7;
#define PIN_INPUT 0
#define PIN_OUTPUT 9
int val = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters


double Kp=1.50, Ki=1, Kd=0;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
int pidsetpoint = 45;
void setup()
{
//initialize the variables we're linked to
Serial.begin(9600);
//Serial.println('a');
//char a = 'b';
// while (a != 'a')
// {
// a = Serial.read();
// }
lcd.init(); // initialize the lcd

// Print a message to the LCD.


lcd.backlight();

pinMode(11,OUTPUT);
pinMode(pump,OUTPUT);
pinMode(w,INPUT);
//turn the PID on
myPID.SetMode(AUTOMATIC);
}

void loop()
{

int pidtemp = 0.388567*analogRead(PIN_INPUT); //


int w1 = digitalRead(w);
//while (Serial.available() == 0)
// {
// }
54

// if (Serial.available() > 0)
// {
// val = Serial.read();
// if (val == 'R')
// {

// Serial.println(pidtemp);
// }
//}

if( pidtemp > pidsetpoint)


{
digitalWrite(11,LOW);

}
else
{

digitalWrite(11,HIGH);
}

if (w1 == HIGH)
{
digitalWrite(pump,LOW);
}
else
{
digitalWrite(pump,HIGH);
}

delay(200); lcd.clear();
lcd.print("TEMP=");
lcd.print(pidtemp);
lcd.print(" ");
lcd.print("SET=");
lcd.print(pidsetpoint);
lcd.setCursor(0,1);
lcd.print("Water level=");
lcd.print(w1);
55

APPENDIX B

The program code for analysis system in Arduino IDE software


56

#include <PID_v1.h>

#define PIN_INPUT 0
#define PIN_OUTPUT 9
int val = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters


double Kp=200, Ki=50, Kd=0;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
int pidsetpoint = 45;
void setup()
{
//initialize the variables we're linked to
Serial.begin(9600);
Serial.println('a');
char a = 'b';
while (a != 'a')
{
a = Serial.read();
}
Setpoint = 60;

pinMode(11,OUTPUT);
//turn the PID on
myPID.SetMode(AUTOMATIC);
}

void loop()
{

int pidtemp = 0.388567*analogRead(PIN_INPUT);


while (Serial.available() == 0)
{
}

if (Serial.available() > 0)
{
val = Serial.read();
if (val == 'R')
{

Serial.println(pidtemp);
}
}
57

if( pidtemp > pidsetpoint)


{
digitalWrite(11,LOW);

}
else
{

digitalWrite(11,HIGH);
}

delay(20);
}
58

APPENDIX C

The program code for analysis system in Matlab software


59

Mainscript coding:

clc
clear all
%%
% Save the serial port name in comPort variable.

comPort = 'com4';
%%
% It creates a serial element calling the function "stupSerial"

if(~exist('serialFlag','var'))
[arduino,serialFlag] = setupSerial(comPort);
end

%%
% Time to create our plot window in order to visualize data collectoed
% from serial port readings

if (~exist('h','var') || ~ishandle(h))
h = figure(1);
set(h,'UserData',1);
end

if (~exist('button','var'))
button = uicontrol('Style','togglebutton','String','Stop',...
'Position',[0 0 50 25], 'parent',h);
end

%%
% After creating a system of two axis, a line object through which the
data
% will be plotted is also created

if(~exist('myAxes','var'))

buf_len = 50;
index = 1:buf_len;
zeroIndex = zeros(size(index));
tcdata = zeroIndex;
limits = [15 50];

myAxes = axes('Xlim',[0 buf_len],'Ylim',limits);


grid on;
60

l = line(index,[tcdata;zeroIndex]);
drawnow;
end
%%

mode = 'R';

while (get(button,'Value') == 0 )

tc = readTemp(arduino,mode);

tcdata = [tcdata(2:end),tc];

set(l,'Ydata',tcdata);

drawnow;
pause(1);
end

readTemp.m coding:

function [output] = readTemp(s,command)


% Serial send read request to Arduino
fprintf(s,command);

% Read value returned via Serial communication


output = fscanf(s,'%f');

end
61

setupSerial.m coding:

function[obj,flag] = setupSerial(comPort)
% It accept as the entry value, the index of the serial port
% Arduino is connected to, and as output values it returns the serial
% element obj and a flag value used to check if when the script is
compiled
% the serial element exists yet.
flag = 1;
% Initialize Serial object
obj = serial(comPort);
set(obj,'DataBits',8);
set(obj,'StopBits',1);
set(obj,'BaudRate',9600);
set(obj,'Parity','none');
fopen(obj);
a = 'b';
while (a~='a')
a=fread(obj,1,'uchar');
end
if (a=='a')
disp('Serial read');
end
fprintf(obj,'%c','a');
mbox = msgbox('Serial Communication setup'); uiwait(mbox);
fscanf(obj,'%u');
end

You might also like