SlideShare a Scribd company logo
1 of 82
Download to read offline
Author: Nemanja Marjanovic
ID: G00263151
Supervisor: Niall O’Keeffe
B.Eng. (Hons) Computer and Electronic Engineering
April 2015
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
2
Table of Contents
Table of Figures......................................................................................................................................4
Abstract...................................................................................................................................................7
Acknowledgments...................................................................................................................................9
1 Introduction........................................................................................................................................10
1.1 The Problem........................................................................................................................10
1.2 Research..............................................................................................................................11
1.3 Findings...............................................................................................................................11
Heart rate monitoring benefits ............................................................................................11
Apps....................................................................................................................................12
Heart rate monitoring technologies.....................................................................................12
1.4 Project Aims and Objectives...............................................................................................14
1.5 Project Plan.........................................................................................................................15
2 Methodology......................................................................................................................................16
Abstract.....................................................................................................................................16
2.1 Approaching the problem....................................................................................................17
2.2 Hardware Overview...........................................................................................................19
Heart Rate Detection...........................................................................................................19
Heart Rate Calculation & Bluetooth Transmission.............................................................20
2.3 Software Overview .............................................................................................................21
Android ..............................................................................................................................21
Android networking...........................................................................................................22
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
3
Java Servlet & Database .....................................................................................................22
Desktop Application ...........................................................................................................22
Semester Two......................................................................................................................23
2.4 Hardware Implementation...................................................................................................24
Embedded Software............................................................................................................25
2.5 Software Implementation....................................................................................................27
The Android Application ....................................................................................................27
Tab 1 – Create Account ......................................................................................................28
Tab 2 & 3 – Sign In & Details ............................................................................................35
Tab 4 – Heart Rate ..............................................................................................................38
Tab 5&6 – Diet and Workout Plans....................................................................................48
Tab 7 & 8– Cardio & Outdoor Tab.....................................................................................51
Tab 9 – Performance Graphing...........................................................................................65
Servlet Operations...............................................................................................................69
Database Construction ........................................................................................................72
Desktop GUI.......................................................................................................................74
3 Conclusion .........................................................................................................................................78
3.2 Achievements.....................................................................................................................79
3.3 Future Work.......................................................................................................................79
4 Appendices.........................................................................................................................................80
5 References..........................................................................................................................................82
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
4
Table of Figures
Figure 1 – Project Plan.............................................................................................................15
Figure 2 – Chest Strap Device and Transmitter.......................................................................19
Figure 3 – FRDM-K20D50M development platform & HC_06 Bluetooth module ...............20
Figure 4 – Hardware Block Diagram.......................................................................................24
Figure 5– Interrupt Service Routine ........................................................................................25
Figure 6 – Programmable Interrupt Timer...............................................................................26
Figure 7– Create account .........................................................................................................28
Figure 8 – Weight calculation formula ....................................................................................29
Figure 9– Maximum heart rate and calorie needs formulas ....................................................30
Figure 10 – Katch-McArdle formula .......................................................................................30
Figure 11 - Heartrate zones table.............................................................................................31
Figure 12 – Heartrate zone calculations...................................................................................31
Figure 13- Creating an entry in the database ...........................................................................32
Figure 14 – Hash map class .....................................................................................................33
Figure 15 - URlContentPost.....................................................................................................34
Figure 16 – Sign In & Details Tab...........................................................................................35
Figure 17 - Data transfer & sending the query to the servlet...................................................36
Figure 18 - Data retrieval using getString................................................................................37
Figure 19 – Heart Rate Tab......................................................................................................38
Figure 20 – Bluetooth On button .............................................................................................39
Figure 21 – Find Bluetooth method.........................................................................................40
Figure 22 – Open Bluetooth method........................................................................................41
Figure 23– beginListeningForBTData method........................................................................42
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
5
Figure 24 – Resting Heart Rate Zone Algorithm selection......................................................43
Figure 25 - Resting Heart Rate Chart ......................................................................................43
Figure 26 - Resting Heart Rate Algorithm...............................................................................44
Figure 27 - Training Heart Rate Algorithm .............................................................................45
Figure 28 - Calories Burned Algorithm...................................................................................47
Figure 29 - Diet & Workout Plan Tabs....................................................................................48
Figure 30 - Image View XML .................................................................................................48
Figure 31 - setAdapter ()..........................................................................................................49
Figure 32 - getView ()..............................................................................................................49
Figure 33 - Selecting Images from Gallery View....................................................................50
Figure 34 - Cardio & Outdoor Tab ..........................................................................................51
Figure 35 - Cardio Tab Algorithm Flow..................................................................................52
Figure 36 - Stopwatch Algorithm ............................................................................................53
Figure 37 - Linking Google Play Services to Project ..............................................................55
Figure 38 - Google Console Obtaining maps API key ............................................................56
Figure 39 - Google Console API key.......................................................................................56
Figure 40 - Android: value.......................................................................................................57
Figure 41 - Google Maps Permissions & Features ..................................................................57
Figure 42 - XML fragment addition ........................................................................................57
Figure 43- Load Google Map Code.........................................................................................58
Figure 44 - Start Service Intent................................................................................................59
Figure 45 - onCreate Myservice3 ............................................................................................60
Figure 46 - Distance between two coordinates........................................................................61
Figure 47- OnLocationChanged ()...........................................................................................62
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
6
Figure 48- Broadcast Receiver.................................................................................................63
Figure 49 - Plotting of Markers for run path............................................................................64
Figure 50 - Performance Graphing Tab...................................................................................65
Figure 51 - Heart Rate/Time graphing.....................................................................................66
Figure 52 - Heart Rate/Time graphing.....................................................................................67
Figure 53 - getDay () of the week............................................................................................68
Figure 54 - Generate distance bar chart ...................................................................................69
Figure 55 - doPost () ................................................................................................................69
Figure 56 - JSON object checking...........................................................................................70
Figure 57 - Retrieve from JSON and Execute Prepare Statement...........................................71
Figure 58 - Database creation ..................................................................................................72
Figure 59 - Database columns creation....................................................................................73
Figure 60 - Database viewer in Heidi ......................................................................................73
Figure 61 - Eclipse’s Window Builder ....................................................................................74
Figure 62 - Gym_Buddy Desktop GUI....................................................................................75
Figure 63 - Calories Burned Graph Creation...........................................................................76
Figure 64 - Data Gathering and Array Storage........................................................................76
Figure 65 - Dataset creation.....................................................................................................77
Figure 66 - Array being passed to Dataset...............................................................................77
Figure 67- System block diagram............................................................................................78
Figure 68- Samsung Galaxy S3 Mini Specifications...............................................................80
Figure 69 - FRDM K20D50M Pinout......................................................................................81
Figure 70 Vernier Receiver pinout ..........................................................................................81
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
7
Abstract
“Coronary heart disease is the most common type of heart disease, killing nearly 380,000
people annually” – According to National Vital Statistics Report (2013). This is a worrying
statistic and it shows the importance of monitoring your own health and fitness in relation to
coronary heart disease. Whether you want to improve your daily workouts or train for a
marathon, a heart rate monitoring system is a valuable companion. Tracking your personalized
heart rate zones helps you control the intensity of your workout for long-term stamina, high-
calorie burn or for other health or fitness goals.
As a regular gym user with experience with using tailored diet and workout plans that
would always include cardiovascular routines with specific heart rate zones in order to achieve
the desired goal, I felt that the issue of inaccurate cross trainers and treadmills was a major
problem. With our generation being so heavily dependent on mobile device applications I felt
that a solution for the problem of usage of multiple different applications for different uses
such as a pdf viewer for you workouts and a clock app for your timing or a map app for and
outdoor run, could be solved by compacting all of these features to a single all in one mobile
application.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
8
In order to demonstrate a solution for the problem an all in one fitness systems was developed
that included a heart rate monitoring system with a desktop application and a database enabled
mobile device application.
The system consist of the following features:
 Heart rate measurement with heart rate zones for exercise and resting
 Calorie burn calculation
 GPS tracking with live heart rate, distance & speed
 Diet & workout plan storage
 Single session post workout performance graphing
 Database user account creation and sign in features
 Multiple sessions performance graphing on a desktop application
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
9
Acknowledgments
I would like to take this opportunity to express my gratitude to my supervisor Niall O’Keeffe
for his exemplary guidance, monitoring and constant encouragement throughout the course of
my final year project. I would like to extend my sincere thanks to the staff members of GMIT
(Galway Mayo Institute of Technology), for the valuable information provided by them in their
respective fields. I am grateful for their cooperation during the period of my assignment. Lastly
I would like to thank my friends and family for their constant encouragement without which
this assignment would not be possible.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
10
Introduction
1.1 The Problem
Heart disease is Ireland's number one killer with approximately 10,000 people dying each year
from cardiovascular disease (CVD) - including coronary heart disease (CHD), stroke and other
circulatory diseases. CVD is the most common cause of death in Ireland, accounting for 33%
of all deaths. The largest number of these deaths relate to CHD - mainly heart attack - at 5,000.
13% of premature deaths (under age 65) are from CVD. Getting regular exercise for people
who have a heart disease is important as it makes your heart muscle stronger and it helps you
be more active without chest pains or other symptoms. Evidence from many scientific studies
shows that reducing these risk factors decreases the chance of having a heart attack or
experiencing another cardiac event, such as a stroke, and reduces the possibility of needing a
coronary revascularization procedure (bypass surgery or coronary angioplasty).
Regular exercise has a favourable effect on many of the established risk factors for
cardiovascular disease. For example, exercise promotes weight reduction and can help reduce
blood pressure. As with all the benefits of exercise there a risk factors involved for people
suffering with heart disease. Placing too much strain on your heart during exercise will result
in one of the main symptoms showing up first in CVD (Cardiovascular disease) patients which
is irregular heartbeats or pulse. As person who is highly interested in health and fitness and
with a family member who is affected by heart disease I was highly motivated to research
monitoring of heart rate zones in more detail and to provide an all in one fitness system solution
not only for a regular gym goer but also for a person affected by a cardiovascular disease so
that they would be more comfortable during exercise.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
11
1.2 Research
Detailed research was completed before the final decision to go ahead with this project was
made. The main fields of research were; current heart rate monitoring technologies with mobile
devices and desktop application support and health and fitness factors that could be established
from heart rate monitoring.
1.3 Findings
Heart rate monitoring benefits
- Improved performance - training in your appropriate target heart rate will allow you to
progress faster with less wasted effort.
- Increased knowledge - knowledge of the hearts functions, the effects of stress and health
problems on heart rate, and how heart rate varies during training will encourage you to
take more responsibility for your own training.
- Objective Assessment - the heart does not lie! The heart shows the response of the body at
any moment in time allowing you to assess intensity and recovery.
- Objective training - are you burning fat or are you burning carbohydrates? Training in
appropriate heart rate zones takes the guesswork out of your cardiovascular program by
customizing the proper exercise intensity for your goals.
- Recent large epidemiologic studies have confirmed earlier studies that showed resting
heart rate measurement to be an independent predictor of cardiovascular and all-cause
mortality in men and women with and without diagnosed cardiovascular disease.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
12
There are many benefits of heart rate monitors. Your workouts become more time efficient and
safe, intensity can be measured simply and reliably. Your goals are more easily set and reached,
progress or lack of progress toward fitness is easily tracked and motivation to improve
increases through greater awareness, and knowledge replaces guesswork.
Apps
There are numerous applications on the market that aid a person’s fitness regime with majority
having a GPS tracker that will follow the user’s route when they are walking/running. The data
is then uploaded to a site that can be accessed by the user at any time to view their route. Other
application focused primarily on having heart rate monitoring without any other interesting
features included with the data being stored only on the device itself. This restricted the user to
only viewing the data for that single measurement on the phone. Other application existed but
where consisted of a cluttered user interface and had to rely heavily on other applications for
other health data.
Heart rate monitoring technologies
“For the casual user looking to get a resting heart rate, wrist-based devices are fine. No
manufacturer claims that these bands work for extreme athletes, and most make it clear that
this style of band is for casual use only -- never for medical use -- and that they work only when
you're still. Usually, manufacturers package the heart-rate sensing technology with tried-and-
true motion sensors that track steps and activity, too.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
13
But aside from gauging huffing and puffing, heart rate tracking during exercise is one of the
best ways to evaluate overall fitness. If you're looking to hit a target heart rate while moving,
you may be better off using a chest-strap device or even the ol' finger-to-the-wrist method”
CNET – “Do wristband heart trackers actually work? A check-up “
From research about different heart rate monitoring technologies I stumbled upon an article
provided by CNET UK which put five leading smart devices with heart rate monitors to the
test, measuring their accuracy with an EKG (Electrocardiogram) and the results were that if
you were looking to hit a target heart rate while moving that the best solution was using a chest-
strap device as it was the most accurate when comparing to an EKG. From these findings I
firmly decided to use a chest strap device as I wanted high accuracy heart rate readings.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
14
1.4 Project Aims and Objectives
The overall aim of the project was to provide an accurate heart rate monitoring system which
could be used to accurately record and store resting and exercise heart rate zones that would
not only benefit CVD (Cardiovascular Disease) patients but also regular gym user’s. An
additional aim was to provide the user with a mobile application that would determines heart
rate zones depending on recording taken from chest-strap device which would also contain
other useful features that would be beneficial for a gym user. With this in mind the following
objectives were drafted:
 Develop an accurate heart rate monitoring systems
 Design a simple to use android app
 Implement heart rate zones depending on data of user
 Implement diet and workout plan storage
 Include a GPS tracker with live heart rate ,calorie burn and distance data being recorded
 Apply Indoor & Outdoor cardiovascular training modes
 Apply Database storage of exercise data recorded with single session performance
graphing
 Design a desktop application for viewing and graphing of recorded data
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
15
1.5 Project Plan
The project plan was designed in September 2014. Initially the project progress was on track
however, with the additional workload of other modules the progress was soon stalled. Due to
this delay some elements and a few new additions, the project took longer than expected. Figure
1 below shows the original project plan designed in September 2014.
Figure 1 – Project Plan
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
16
2 Methodology
Abstract
In this chapter of the report the method in which features were designed developed and tested
will be described, the theory behind the project and each of its individual features will be
explained as well as the research and steps taken during the development phase of the feature
in question, as well as the approach taken to solve any problems that were encountered. First
of all the general research and methods will be explained then the actual way in which features
were implemented will be explained.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
17
2.1 Approaching the problem
The problem was approached by breaking down the overall project down into smaller
individual components that were later combined to form a fully functional system. The
breakdown of the project is as follows.
 Hardware – Embedded System
- Heart Rate Detection Using Vernier Exercise Heart Rate Monitor
- Heart rate measurement & calculation on a Freescale FRDM-K2050DM microcontroller
- Transmission of heart rate data using HC_06 Bluetooth module
 Software
- Android Application with networking for heart display of heart rate data and other fitness
factor
- Server Application & Database Construction
- Desktop application for viewing of data stored on database & performance graphing
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
18
As a person with Agile software methodology experience which was gained as part of a six
month placement in Intel Shannon working in an team that followed this type of software
development process. I learned that it was best to tackle projects was feature-by-feature instead
of in big phases. With this knowledge a goal oriented modular approach was taken, small goals
that were flexible were established and the above features were never developed from start to
finish individually as some aspects of one feature might have been dependant on another aspect
of another feature. This resulted in all of the features progressing gradually which in result
allowed the developer to jump from one part of the system to another.
What this resulted in was small blocks of functionality that could easily be adapted to
the main project, removed or modified. The design process of each of the blocks started with a
goal, research on how this goal should be achieved and then implementing the knowledge into
a small project which would later be merged with the main project. This type of approach
continued until the completion of the systems, this practice was adopted due to the fact that it
made bug fixing easier and it also added an element of safety due to the fact that it wasn’t
implementing new functionality to the main project but first being thoroughly tested before the
additions was applied and this method made sure that new code wouldn’t jeopardize the
functionality of the main code and even if it were to cause problems it was easy to extract and
fix.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
19
2.2 Hardware Overview
Heart Rate Detection
On initial research of heart rate monitoring techniques and the equipment used the findings that
I have found were pointing in the direction of using a chest-strap device as it was the most
accurate method of monitoring. With these findings I spoke to my supervisor Niall O’Keeffe
who provided me with an exercise heart rate monitor consisting of a wireless transmitter belt
and a receiver module that originally plugged in to a Vernier interface. The transmitter belt
senses the electrical signals generated by the heart much like an EKG. For each heart beat
detected, a signal is transmitted to the receiver module, and a heart rate is determined. As this
unit was designed to be used with one of Vernier’s interfaces it required a low power
microcontroller to replace that equipment.
Figure 2 – Chest Strap Device and Transmitter
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
20
Heart Rate Calculation & Bluetooth Transmission
As part of a 4th
year Embedded Systems module Freescale K60 development board was used
which not only familiarised me with the Freescale product’s and documentation but also with
the development tool that is CodeWarrior which a complete integrated development
environment (IDE) that provides a highly visual and automated framework to accelerate
development of the most complex embedded applications. With this familiarity and the need
of a low power microcontroller and guidance of my supervisor I turned to a Freescale product
which was the FRDM-K20D50M ultra-low-cost development platform enabled by the Kinetis
K20 USB MCU family built by ARM Cortex M4 processor. Features include the Freescale
open standard embedded serial and debug adapter (OpenSDA), providing easy access to MCU
I/O, battery-ready, low-power operation, a standard-based form factor with expansion board
options and a built-in debug interface for flash programming and run-control. With the idea of
Bluetooth transmission in mind this development platform offered easy access to MCU I/O via
Arduino R3 compatible I/O connectors which was perfect for the HC-06 Bluetooth module
planned. This module permits any microcontroller with a standard RS232 serial port to
communicate with a PC or a Smartphone equipped with a Bluetooth Master module
Figure 3 – FRDM-K20D50M development platform & HC_06 Bluetooth module
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
21
2.3 Software Overview
Android
As a person who is highly interested in mobile device applications I knew that this was the
route I wanted go down in my final year project. Mobile Device Programming module was
introduces to us in the first semester of 5th
year and in a short period of time I was proficient in
android development using Eclipse (IDE) combined with android SDK .With this newly
acquired skill set I was able to design an Android application with the theme in mind. Originally
the applications main objective was display heart rate data and zones belonging to that heart
rate but as time went on other ideas were created by problems recognised during daily
cardiovascular and training activity. Ideas included were the addition of diet and workout plans
and also contribution by my lecturers which included Michelle Lynch’s idea of adding GPS
tracking of an outdoor run with live heart rate data and also the option to see the route taken.
My supervisor Niall O’Keeffe provided me with valuable tips letting me know that in order for
this systems to be a fully functional systems that it needed to include data base storage with an
option of a back end solution to view data recorded and with this information I dedicated myself
to achieve this feature also.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
22
Android networking
As part of the mobile device programming module android networking information was
provided which included the basic transfer of basic data types to a servlet that could return
modified values of the data that was sent, the medium in which this data was send was via
JSON objects. A basic project was then developed with Android networking for testing
purposes so more could be learned on how to apply it to the main systems.
Java Servlet & Database
Mobile Device Programming and Server Client Programming modules provides us with
necessary skills to achieve full functionality of a java servlet to database communication so
this area required very little research. In order to achieve the communication between a java
servlet and SQL database the use of a JDBC driver software component was needed which was
responsible for enabling the Java application to interact with the database.
Desktop Application
With great advice from my supervisor a desktop GUI was developed as a back end solution for
the system. At the time MigLayout had only recently been learned during the previous semester
in the Software Engineering 1 module of the course, however its usability and advantages were
immediately obvious. The GUI was designed to access player’s performance information that
was stored on a database by an Android application which allowed the user to view five session
performance graphs.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
23
Semester Two
For most of semester one research was the main focus of the project. Once the appropriate
background research had been completed and a great deal had been learnt in terms of the needed
technologies and java programming techniques that would help to complete the project. Work
first started on the embedded side of the project which included interfacing the heart rate
receiver module to the Freescale freedom board.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
24
2.4 Hardware Implementation
Figure 4 – Hardware Block Diagram.
The project consists of a low power Freescale freedom board which has interfaced to it a Heart
Rate Receiver Module. Heart Rata Data is gathered using the Exercise Heart Rate Monitor
which is fitted firmly on a person chest which then monitors that person’s heartbeat.
The transmitter detects each heartbeat through two electrodes and transmits heart rate
information to the receiver with a low frequency electromagnetic field.
Heart Rate Receiver is connected to the Freescale board and once the heart beat is detected it
is put in a formula which calculates the heart rate and is sent via Bluetooth to the app.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
25
Embedded Software
Embedded side of the project consisted of development using C-Programming in a
CodeWarrior IDE. Once the board was setup the programming could begin. As the receiver
detects a heartbeat transmitted by a chest-strap device a hardware interrupt is caused and the
following snippets of code is executed:
Figure 5– Interrupt Service Routine
HeartRateCounter variable is incremented of every interrupt detected which is responsible for
keeping the data of the number of heartbeats. PIT is then used which is a 16-bit timer that
provides precise interrupts at regular intervals with minimal processor intervention. The timer
counts at the peripheral clock frequency. The timers count down from an initial count value to
0 and set an interrupt flag. The timer is then reloaded with the initial count value and the
countdown continues. This was used to countdown ten seconds and transmit heart rate data
gathered over Bluetooth.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
26
Figure 6 – Programmable Interrupt Timer
Once the counterSec counter reached ten seconds the data gathered was cast to an unsigned
char and passed to uart_putchar for transmission over Bluetooth.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
27
2.5 Software Implementation
The Android Application
The Android application, from a project point of view, was the central element. Android
provides a rich application framework that allows you to build innovative apps for mobile
devices in a Java language environment. The software for the app was all developed in Java
using the Android Development Tools (ADT) plugin for Eclipse IDE (Integrated Development
Environment). ADT plugin extends the capabilities of Eclipse to allow the user to quickly set
up new Android projects, develop Android applications, add packages based on the Android
Framework API, debug your application using android SDK (Software Development Kit)
tools, and also allowing you to distribute your application on the Google play store. An activity
represents a single screen with a user interface. All the GUI (Graphical User Interface) design
for the activity is created using the layout.xml filet which is included in the Android project.
The Gym Buddy application consists of two activities with the first activity being a welcome
screen. The main activity consists of Android Tab Host which provides a nice way to present
multiple thing on a Single Screen. These things are presented by Tabs. Gym Buddy fitness app
contains nine tabs. These tabs are for create account, sign in, details, heart rate, gym plans, diet
plans, cardio, outdoor run and post workout graphing.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
28
Tab 1 – Create Account
Tab one was designed for the user to insert all of the required information for the heart rate
zones and other fitness factors to be determined.
Figure 7– Create account
The user was asked to enter the following details name & password which would ensure that it
would be only them that could access their accounts and impact their statistics and the password
was decided as feature to uphold the integrity of the user’s statistics provided to them by the
application. Age, gender and height were the most important pieces of information entered by
the user as these pieces would help determine heart rate zones and the maximum daily calorie
allowance. Once the user entered the following information the first bit of calculation that was
required was the weight. As the calorie burn formula required the use of pounds it would be
necessary to allow the user to enter either kilograms or pounds as
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
29
his choice of measurement. Depending of the choice taken a suitable conversion method would
be implemented. If the user selected kilograms as the weight measurement a formula to convert
to pounds was used. Multiplying the kilograms entered by 2.2046 returned the correct weight
in pounds.
Figure 8 – Weight calculation formula
The second calculation and probably the most important component of the system was
establishing the maximum heart rate of the user. Depending on the gender and age of the person
using the system a calculation was required to determine maximum heart rate. The formula for
male is as follows 220 – Age = Maximum Heart rate and for females is 226 – Age = Maximum
Heart Rate. So once the user has entered their age and gender the following snippet of code
was used.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
30
Figure 9– Maximum heart rate and calorie needs formulas
Depending on the gender and age of user maximum heart rate would be calculated. The Katch-
McArdle formula was used to determine the maintenance calories which required the use of
weight entering by the use. The formula is as follows for both men and women: BMR = 370 +
(21.6 x Lean Body Mass (kg)). This is a newer formula that accounts for your lean body mass,
which generally gives you a more accurate estimate of your basal metabolic rate (BMR).
Figure 10 – Katch-McArdle formula
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
31
One last calculation is required before the details recorded are stored on a data base and this is
the different heart rate zones. As the maximum heart rate zones was calculated this data could
then be used for determination of heart rate zones.
Figure 11 - Heartrate zones table
Using the figure above code was written to get warm-up, fat burning, aerobic, high intensity
and maximum heart rate zones. This was achieved in the following manner.
Figure 12 – Heartrate zone calculations
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
32
In order to get a zone a calculation was used by which the percentage of the maximum heart
rate was calculated to get the necessary data to display different zones. As an example we take
the fat burning zone, by looking at the diagram your body is in fat burning zone when you heart
rate is at 60-70 % of your max heart rate so by getting 60% this would be the lower zone of fat
burning and getting 70 % of the heart rate would be the higher zone of fat burn and as long as
the heart rate was in the range of these values it would be considered within the fat burning
zone. With all of the necessary data entered and calculated the create account button could then
be activated in order for the data gathered to be stored in a data base.
Figure 13- Creating an entry in the database
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
33
The first thing this activity does is acquire twelve strings that of the inputted name and the
desired password and other inputted data and it creates a new instance of my class
DataBaseData class that takes in twelve string variables in this case they are the name,
password, age , gender , units , weight , max heart rate, average heart rate , calories needed,
calories burned , speed ,instance and create, the create string is a tag that is used to tell the
server that it will be a creating an entry in the database for a new user but there will be more
on that later, the DataBaseData class just places these strings into a hash map.
Figure 14 – Hash map class
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
34
A new JSON object is then created and the hash map is passed to it. A new string is then created
using the static urlContentPost in the httpUtils class here is the method the below.
Figure 15 - URlContentPost
This method was responsible for posting the parameters passed to it to a URL passed to it in
its parameters in this case the URL of my servlet running on an apache tomcat server.
http://localhost:8080/NemanjaTest/Servlet
The JSON object was then converted to a string and was also given the name “User Data” this
gave the content post method all the variables in required, the address, the name parameter and
the value parameter, the doPost method on the servlet side then waited to receive the JSON or
multiple JSON objects with a certain name parameter and responded accordingly with a string
which you could pass to a JSON object and use to extract data sent back by the server. This
was the method was how the data was sent and received by the Android device, the IP address
the data was sent to was different depending which network the pc was connected to . As my
application needed to be used in an environment where WIFI wasn’t always available it needed
to be able to transfer the data over the 3G network.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
35
Port forwarding needed to be setup on the router for demonstration purposes. I began by
logging in to router and activating port forwarding on port 8080. Then getting the PC’s global
IP which was then used in the Android applications on the same port. The data transfer was
always threaded as not to freeze the applications UI as it took care of the task. Placing of data
into hash maps and inserting them into JSON objects and sending them via the content post
method was how all the data transfer in the app, whether it be sending or receiving was handled.
Tab 2 & 3 – Sign In & Details
Figure 16 – Sign In & Details Tab
After a successful method was discovered to send data to the server and insert it into the
database, all that was left to do was for the client to receive data from the servlet upon it
receiving a query and searching the database for the player query information sent by the client.
The sign in tab was created to give the user the facility to search for his name and information
already stored under and he would get the relevant user information loaded to a
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
36
details tab with an option to update some information. A simple UI (User Interface) was
designed with two text field and two buttons, text fields were there for entering of user’s names
and password and one button for activation of data transfer and sending the query to the servlet
but this time data was expected in return also. The other button’s feature was to clear the text
field allowing the user to clear the information entered.
Figure 17 - Data transfer & sending the query to the servlet
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
37
From the figure above it can be seen that the string that is being returned by the URL content
post method is used to create a new JSON object by the name of jsonDataReturn , then the
variables are being extracted from this JSON object which are the desired variables requested
by the client. Prior to this name and password is retrieved from the text area and stored in a
hash map that has a “Sign In” key as part of it. New JSON object is created and the hash map
containing three strings which are name, password and “Sign in “ are passed in to it to be sent
to the servlet. Prior to this name and password is retrieved from the text area and a new instance
of DataBaseSignIn is created which takes in two strings which are name and password and a
command string tag. Then a JSON is being sent to the servlet containing the hash map with the
necessary data with a tag to define that it wishes to query the database. The jsonResult JSON
object hold the response sent back by the servlet. Data is then retrieved by using the getString
which will get the string associated with the key.
Figure 18 - Data retrieval using getString
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
38
Once the data is retrieved it is all then stored in details tab for the user to review and change if
needed. As well as the user being able to review the data the information loaded is also used
for calculation of necessary factors for the app to function accordingly. Age, gender, weight &
max heart rate is used to determine heart rate zones & calories burned throughout exercise.
Tab 4 – Heart Rate
Tab four was responsible for the activation of Bluetooth and the display of heat rate and the
zones assigned to that zone.
Figure 19 – Heart Rate Tab
The UI (User Interface) of this tab consisted of two buttons, one being responsible for the
activation of Bluetooth and the other for de-activation. Two check box selection option was
displayed for the user for selection of either resting or training heart rate zones.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
39
The tab also included a heart image which was animated to pulse on a pulse received as well
as a graph which also included a circle that would bounce when a pulse was detected with a
sound animation included. On activation of the Bluetooth on button two methods were called
findBluetooth () and openBluetooth ().
Figure 20 – Bluetooth On button
As name might suggest findBluetooth () method was responsible for device discovery.
BluetoothAdapter class was used which lets you perform fundamental Bluetooth tasks , such
as an initiate device discovery , query list of bonded (paired) devices, instantiate a
BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen
for connection from other devices, and start a scan for Bluetooth LE device. In the figure below
we can see how this was achieved.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
40
Figure 21 – Find Bluetooth method
Firstly it was checked if a bluetooth adapter was available and once this was established I
checked if bluetooth adapter is enabled and if not an intent was created for enabling of
bluetooth. Once you have the local adapter , you are able to get a set of BluetoothDevice object
representing all paired devices with getBondedDevices(). And if the paired device had the
name of HC-06 which was the embedded bluetooth module device it was assigned to a
Bluetoothdevice mmDevice variable.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
41
On successful pairing of the devices I then moved on to the openBluetooth() method, where a
Bluetooth socket for communication for with the paired device was created and opened. To
create a Bluetoothsocket for connecting to the paired device
BluetoothDevice.createRfcommSocketToServiceRecord(uuid) method was used and started
using BluetoothSocket.Connect to initiate connection. This also performed an SDP lookup of
the given uuid to determine which channel to connect to. Once the socket was connected IO
stream was opened by calling getInputStream () on the socket and then that socket was assigned
to an InputStream which is used for reading byte based data, one byte at a time.
BeginListeningforBTData () method was then called which was responsible for interpretation
of the incoming data
Figure 22 – Open Bluetooth method
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
42
The biggest chuck of programming was done within this method as it was the spine of the
whole application. The first part that was done was getting and estimated number of bytes
and if the bytes received where greater than zero a byte array of the estimated size was
created. Use of the read () method of an InputStream returns an integer which contains the
byte value of the byte read. Once the read () method returns -1, the end of stream has been
reached, meaning there is no more data to read in the InputStream. The byte array is then
checked for an ASCII 10 (“End Line”) and decoded in to a string. That string is then looped
through and checked for the character stored in it. This character is then cast to an integer and
multiplied by six to give us beats per minute.
Figure 23– beginListeningForBTData method
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
43
Now that out beats per minute have been identified checking of heart rate zones could be done.
Beats per minute was stored in a integer variable called btsPM which on every heart rate
received over Bluetooth was used to check what heart rate zone it belonged to. If the resting
check box was selected and beats per minute were lower than warm up zone, age and btsPM
variable were passed to a method for calculation of resting heart rate zones and the method also
relied on the gender of the user.
Figure 24 – Resting Heart Rate Zone Algorithm selection
Which was developed using the help of the following table.
Figure 25 - Resting Heart Rate Chart
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
44
Below here is a code snipped of how the algorithm was achieved.
Figure 26 - Resting Heart Rate Algorithm
As an example we take a male in the age bracket of 18 to 25 and the heart rate between 49 and
55 which tells the user that he has an excellent heart rate resting conditions. The zones are rated
from athlete-excellent-good-above average-average-below average and poor so if the user was
in the age bracket specified heart rate between 49 up to 82+ was used to determine the zone. If
the training check box was selected and the heart rate recorded was greater or equal to the warm
up zone the following algorithm was implemented.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
45
Figure 27 - Training Heart Rate Algorithm
As we can see in the above figure that if the heart beat recorded was greater or equal to warm
up low zone (Calculated by getting 50% of maximum heart rate) and less than warm up high
zone and as long as training check box was active the user would be displayed with his heart
rate zone on the UI (User Interface) and also the method pumpHeart() was called which
produced the animation of the beating heart with a heartbeat noise which also used an instance
of the graphView class which was responsible for drawing of a graph with a circle being
animated to represent a pulse. The same principal was applied to the rest of heart rate zone
measurement.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
46
Beats per minute recorded were stored in to an array list which was passed to a method which
was responsible for the calculation of the average heart rate. Reason that this was needed was
for the calorie burned formula which needed the average heart rate calculated. Within the
method array list was looped through and all the data stored in the array list was summed and
then divided by the size of the array to get the average. With this average recorded the formula
for calories burned from the Journal of Sports Science could be used which was as follows:
Men Calories Burned:
= [(Age x 0.2017) - (Weight x 0.09036) + (Heart Rate x 0.6309) -55.0969] x Time / 4.184.
Women Calories Burned:
= [(Age x 0.074) - (Weight x 0.05741) + (Heart Rate x 0.4472) - 20.4022] x Time / 4.184.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
47
Algorithm developed for calculations was as outlined below.
Figure 28 - Calories Burned Algorithm
So depending on gender of the user a specific formula was used to calculate calories burned
which would then be displayed in the indoor or outdoor cardio tabs.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
48
Tab 5&6 – Diet and Workout Plans
Figure 29 - Diet & Workout Plan Tabs
Tabs four and five were used for displaying images of diet and workout plans that were stored
on the phone. This was achieved using android Galley and Image View.
Android xml needed to be modified in order at include gallery view and image view. Figure
below explains how this was achieved.
Figure 2.27 Gallery View XML
Figure 30 - Image View XML
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
49
Once the xml was setup we then needed to set Adapter to the gallery.
Figure 31 - setAdapter ()
Set adapter provides the data and the views to represent the data in this widget.
WorkoutImageAdapter class contained all of the images that held workout plans.
getView () method within the class was responsible for dealing with the images.
Figure 32 - getView ()
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
50
From this a gallery view with workout images could then be viewed within workout plan’s tab.
To enable the user to click on the gallery image and display it in a larger image view plain the
use of setOnItemClick listener was used with onItemclick responsible for setting the
imageView with image clicked on in the gallery view.
Figure 33 - Selecting Images from Gallery View
The technique used for workout plan images was also mimicked for diet plan information also.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
51
Tab 7 & 8– Cardio & Outdoor Tab
Cardio tab was designed to allow the user to select between indoor and outdoor cardio and
depending on that selection calories burned and heart rate data would either be displayed in the
indoor cardio tab or on an outdoor tab containing a google map fragment. The layout out of the
tab included two check boxes. One was used for indoor selection and the other for outdoor with
two areas below to display heart rate and calorie burned information. Stopwatch interface was
also included as part of the GUI.
Figure 34 - Cardio & Outdoor Tab
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
52
If the indoor option is selected and the stopwatch started the user is able to see his heart rate
with the zones and also the calorie being burnt within the cardio tab.
Figure 35 - Cardio Tab Algorithm Flow
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
53
In order to enable a stopwatch feature Android SystemClock was used. To update the value of
the timer the use a handler was needed. The Handler takes a runnable object and it schedules
its execution; it places the runnable process as a job in an execution queue to be run after a
specified amount of time. The runnable was run on the thread to which this handler is attached.
Figure 36 - Stopwatch Algorithm
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
54
timerinMilisec was updated using an Android System clock method which returns millisecond
since boot, not counting time spent in deep sleep. Which is then taken away from startTime
variable which is assigned in the same method except in the onCreate part of the activity. From
this method all of the necessary components were gathered for the stopwatch to be displayed.
Outdoor selection was used to show the user a google map fragment which display’s users
heart rate, calories burned and distance of run which uses an Android Service for GPS (as it is
CPU intensive and it needs to run in the background away from the main UI).
Before any of Android service programming was done the setup before the use of
Google maps needed to be done. This included downloading Google play services within the
Android SDK Manager followed by importing the downloaded library into the eclipse
workspace. Getting the Google map key was the next step as for use of Google maps you need
to create a valid Google Maps API key.
The key itself is free and you can use it with any other application that call the Maps
API and it also supports unlimited number of users. You get this key via the Google APIs
Console. You have to provide your application signature key and the application package name.
This is based on the key with which you sign your Android application during deployment.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
55
During development with Eclipse, Eclipse automatically creates and uses a debug key.
Creating a SHA-1 for you signature key was the next path that needed to be taken. To generate
SHA-1 fingerprint using java keytool open your terminal and execute the following command
to generate SHA-1 fingerprint.
keytool -list -v -keystore "%USERPROFILE%.androiddebug.keystore" -alias
androiddebugkey -storepass android -keypass android
Once the command is executed in the output you will be able to see SHA1 finger print. The
next step was to open Google API Console and select Services on left side of the panel and
turn on Google Maps Android API v2.
Figure 37 - Linking Google Play Services to Project
Next order of business was to select API access on left side and on the right side click on Create
new Android key.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
56
Figure 38 - Google Console Obtaining maps API key
Once you have clicked on Create new Android key a popup window is activated asking for the
SHA1 and package name. This is where the obtained SHA1 and your android project package
name separated by a semicolon were entered. And also take note of the API key which will be
required later in the project.
Figure 39 - Google Console API key
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
57
Once the previous steps were completed and all of the necessary information was gathered we
could then move on to modifying the AndroidManifest.xml. Replacing the android: value with
your map key was then done.
Figure 40 - Android: value
Google maps also needed the following permissions and features.
Figure 41 - Google Maps Permissions & Features
Once all of the initial setup was completed focus could be turned to displaying a Google map
fragment within the tab itself. Once the fragment was added to the tab in the following way:
Figure 42 - XML fragment addition
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
58
It was quiet easy to display the map itself in the fragment with the use of the following code.
Figure 43- Load Google Map Code
With Google maps being now present within the tab the use of android services was required.
A service is an application component that runs in the background, not interacting with the user
for an indefinite period of time. Services, like other application objects (activities, broadcast
listeners…), run in the main thread of their hosting process. This means that, if your service is
going to do any CPU intensive (such as MP3 playback) or blocking (such as networking)
operations, it should spawn its own thread in which to do that work and this is exactly what
was done. Each service class also must have a corresponding declaration in its package's
AndroidManifest.xml. Android Service class responsible for GPS locations was activated using
an intent which was started on initiation of start stopwatch button only if outdoor mode of
cardio was selected.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
59
Figure 44 - Start Service Intent
Once the service was kicked off Myservice3 class broadcasted GPS locations. onCreate () for
the class was responsible for getting the GPS status and requesting GPS updates in the time
provided and on specified distance moved.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
60
Figure 45 - onCreate Myservice3
As the minimum distance for location update was set to very low OnLocationChanged() was
called often which provided the user with new latitude and longitude and each time these were
placed in to a hash map which was used for the calculation of distance between locations.
Outlined below is the code responsible for this.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
61
Figure 46 - Distance between two coordinates
The difference between previous and current latitude and longitude was calculated and this
data was then used for the haversine formula to compute the distance from the two locations.
This formula assumes that the Earth is a plain sphere. Once the distance was returned by the
method the latitude, longitude and distance were sent to a broadcast receiver which was present
in the main activity.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
62
Figure 47- OnLocationChanged ()
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
63
Once the data was received by the broadcast receiver which included latitude, longitude and
distance markers of the initial start of run and path of movement could be displayed as well as
the distance being travelled by the user could also be displayed on the Google Map Fragment.
Figure 48- Broadcast Receiver
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
64
Markers were dropped on every 20 meters to portray the path of the user’s movement. Below
is the described algorithm.
Figure 49 - Plotting of Markers for run path
On initial start of movement first markers is dropped and then on every 20th
meter. On end of
outdoor cardio the user would stop the stopwatch and in results the data recorded (Average
Heart Rate, Distance, Calories Burned and Speed) for the duration of the workout would be
sent to the database in the same method as previously described and performance graphs would
be shown in the next tab.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
65
Tab 9 – Performance Graphing
Figure 50 - Performance Graphing Tab
Tab seven was where all of the gathered information throughout the duration of the single
session were graphed. To achieve this a graphing library called MPAndroidChart created by
Philip Jahoda was used. The data that was graphed was heart rate average and heart rate over
timer as well as calories burned graphed on a pie chart versus daily calorie needs. Distance was
also graphed on a bar chart specifying the distance that was covered on a particular day. Plotting
the heart rate average and heart rate over time the following code snippet was used.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
66
Figure 51 - Heart Rate/Time graphing
In the figure above we can see a method which is responsible for creation of a line chart and
which is part of MPAndroidChart library, array lists containing minutes and heart rate were
used in order to graph the required data.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
67
Pie chart graphing required the use of calorie needs and calories burned calculated for plotting.
With this data supplied a clear graphs of calories burned vs calories allowed was achieved.
Figure 52 - Heart Rate/Time graphing
Distance calculated throughout the outdoor run was graphed on a bar chart which specified the
distance that was covered on a particular day of the week. In order to get the day of the week
Android Calendar was used and the following algorithm was developed.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
68
Figure 53 - getDay () of the week
Day of the week was got using the calendar. Get (Calendar.DAY_OF_WEEK) and depending
on a day an array list would be populated with a string corresponding to a name of that day.
Days were then used to display to the user what day of the week he had covered which distance.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
69
Figure 54 - Generate distance bar chart
Servlet Operations
The servlet’s role in the project was to receive and send data back to android device and store
and request data from the database. All data was sent and received from the servlet’s do post
method, this method waits on a post from the client in this case Android device.
Figure 55 - doPost ()
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
70
The string “inputString” is the JSON object in string format, the “UserData” was the name
value that was passed to the content post method that is how the servlet was able to distinguish
individual JSON objects being sent from the client. The servlet in this case always received
one JSON object with the same name value but a unique string in each hash map was used to
differentiate between a query command for the database and an insert command.
Figure 56 - JSON object checking
In the above figure a JSON is being created using the string received in Figure 2.43 and the
string “Command” is being defined as whatever string is in that JSON’s hash map with the
name value of “Command”, the name value “Command” was default for all JSON object being
sent but what this string was equals to was unique depending on the data inside the JSON
object. As we can see from the figure above the string is then being checked if it is equal to
“Create”, if this is true the code will go into that block and execute appropriate code. This is
how the servlet distinguished between different contexts and commands that the client needed
such as queries and insertions in to the database.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
71
In the instance for the create account activity the string with the name “Command” was equal
to “Create” which led the servlet to enter the block of code that was used to create a new entry
in the data base for the new user. Where the data passed was retrieved and a prepare statement
was used to insert that data in to the data base.
Figure 57 - Retrieve from JSON and Execute Prepare Statement
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
72
Database Construction
Once the client-server communication was achieved, it was time to implement a database. The
software program HeidiSQL was used to set up the database. XAMPP was used in conjunction
with this to run the database. Constructing a database with Heidi was very simple and the first
by the name of “GymBuddyDB” was created.
Figure 58 - Database creation
The Gym buddy database was created on the local host and could be connected to via port
3306. Once the data base was created within that session it was then populated with the required
fields. Below you are able to see database filled with some statistic columns.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
73
Figure 59 - Database columns creation
Figure 60 - Database viewer in Heidi
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
74
Desktop GUI
The final feature that was implemented in the project was a desktop GUI, its functionality was
to include.
 Searching the database for a user and displaying their fitness statistics
 Graphs the users fitness performance
The layout of the GUI was designed in Eclipse’s Window Builder GUI designer. This
extensions allowed the user to design the GUI with a graphical representation of the layout
desired. By selecting text fields, buttons and positions of the window code would then be
generated for the creation and position of these components.
Figure 61 - Eclipse’s Window Builder
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
75
Figure 62 - Gym_Buddy Desktop GUI
The user simply enters his name and password that he created within the android application
and presses the sign in button. This action takes the requested name and password and queries
the database for the user. The operations for searching for a player in the database in this
instance is the same as it was in the Android application but no transmission to the server was
needed as it read the database directly from the local host. One thing the GUI project needed
was the addition of the JDBC driver like what was done with the Java servlet. On successful
loading of data from data base recorded data would be displayed and four performance graphs.
Throughout research and advice from a lecturer it was decided that JFreeChart graphing library
would be used for performance graphing. From below figure we can see how the creation of
one of the graphs was established.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
76
Figure 63 - Calories Burned Graph Creation
As with android graphs arrays would be expected to be passed to the graph functions. Data
loaded from the database would be retrieved and parsed to required data type that would then
be added to an array.
Figure 64 - Data Gathering and Array Storage
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
77
The gathered data would then be added to a data set that was created.
Figure 65 - Dataset creation
Figure 66 - Array being passed to Dataset
As we can see in the above figure the array created from the data gathered from the database
was then added to a dataset which would then be used to portray a graphical image of the
performance graphs.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
78
3 Conclusion
Overall the project was a success. All objectives were met and the Gym Buddy System turned
out to be a fully functioning fitness system that successfully monitored user’s heart rate date as
per the project description. The following diagram shows all of the components that the project
has incorporated.
Figure 67- System block diagram
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
79
3.2Achievements
A complete solution for the problem proposed was achieved. The systems is a fully functioning
product that can support regular gym user or a patient that has cardiovascular disease and guide
them both their hearth condition monitoring or fitness goals. All aspects of the project
objectives were completed and implemented. The final features included are:
 Accurate Heart Rate Measurement using chest-strap device
 Simple to use and unique android app
 Heart Rate Zone Measurement
 Diet & Workout Plan Storage
 GPS tracker with live heart rate data, calorie burn and distance being recorded and
displayed on a Google Map
 Indoor & Outdoor cardiovascular training modes
 Database storage of exercise data recorded with single session performance graphing
 Desktop application for viewing and graphing of multiple sessions data
3.3Future Work
During development of the system, Android application itself was solely tested on the Samsung
Galaxy S3 mini phone. Tests will have to be conducted to ensure the app is compatible with
different android OS platforms and screen sizes. As the android application was tested with
connection for use on a single heart rate measurement device additional test will be required to
ensure same outcome of data recording.
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
80
4 Appendices
Figure 68- Samsung Galaxy S3 Mini Specifications
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
81
Figure 69 - FRDM K20D50M Pinout
Figure 70 Vernier Receiver pinout
Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015
82
5 References
1 FRDM-K20D50M Setup Guide and Documentation
http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=FRDM-K20D50M
2 Exercise Heart Rate Monitor Information & Data Sheet
http://www.vernier.com/products/sensors/heart-rate-sensors/ehr-bta/
http://www.vernier.com/files/manuals/hgh-bta.pdf
3 Android Google Map View Tutorial & Information
http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/
https://developers.google.com/maps/documentation/android/
4 Heart Rate Zone, Calorie Needs Information
http://www.freedieting.com/calorie_needs.html
http://fitnowtraining.com/2012/01/formula-for-calories-burned/
http://build-muscle-101.com/heart-rate-to-burn-fat/
5 Gallery View
http://developer.android.com/reference/android/widget/Gallery.html
http://developer.android.com/reference/android/widget/Adapter.htmlgo
6 Android Tab View Information
http://developer.android.com/training/implementing-navigation/lateral.html
7 Java IO
http://tutorials.jenkov.com/java-io/inputstream.html
8 Android Bluetooth
http://developer.android.com/guide/topics/connectivity/bluetooth.html

More Related Content

What's hot

C201 candy estimating & valuations - rev 5
C201   candy estimating & valuations - rev 5C201   candy estimating & valuations - rev 5
C201 candy estimating & valuations - rev 5Self-employed
 
The mysterious s_curve
The mysterious s_curveThe mysterious s_curve
The mysterious s_curveM.S. Aftab
 
Candy - Construction Estimating & Valuations - rev 2.01
Candy - Construction Estimating & Valuations - rev 2.01Candy - Construction Estimating & Valuations - rev 2.01
Candy - Construction Estimating & Valuations - rev 2.01Jerico Awat
 
Angular js notes for professionals
Angular js notes for professionalsAngular js notes for professionals
Angular js notes for professionalsZafer Galip Ozberk
 
React js notes for professionals
React js notes for professionalsReact js notes for professionals
React js notes for professionalsZafer Galip Ozberk
 
TOC training KeyCloak Redhat SSO core
TOC training KeyCloak Redhat SSO coreTOC training KeyCloak Redhat SSO core
TOC training KeyCloak Redhat SSO corePascal Flamand
 
TOC training Keycloak RedhatSSO advanced
TOC training Keycloak RedhatSSO advancedTOC training Keycloak RedhatSSO advanced
TOC training Keycloak RedhatSSO advancedPascal Flamand
 
BizTalk Practical Course Preview
BizTalk Practical Course PreviewBizTalk Practical Course Preview
BizTalk Practical Course PreviewMoustafaRefaat
 
TOC training Keycloak RedhatSSO UMA
TOC training Keycloak RedhatSSO UMATOC training Keycloak RedhatSSO UMA
TOC training Keycloak RedhatSSO UMAPascal Flamand
 
Angular2 notes for professionals
Angular2 notes for professionalsAngular2 notes for professionals
Angular2 notes for professionalsZafer Galip Ozberk
 
ARQUIVO ROUBADO
ARQUIVO ROUBADOARQUIVO ROUBADO
ARQUIVO ROUBADOD813061988
 
Jquery notes for professionals
Jquery notes for professionalsJquery notes for professionals
Jquery notes for professionalsZafer Galip Ozberk
 
Scholarship database management database (1)
Scholarship database management database (1)Scholarship database management database (1)
Scholarship database management database (1)Muhammad Zubair
 

What's hot (17)

C201 candy estimating & valuations - rev 5
C201   candy estimating & valuations - rev 5C201   candy estimating & valuations - rev 5
C201 candy estimating & valuations - rev 5
 
The mysterious s_curve
The mysterious s_curveThe mysterious s_curve
The mysterious s_curve
 
Candy - Construction Estimating & Valuations - rev 2.01
Candy - Construction Estimating & Valuations - rev 2.01Candy - Construction Estimating & Valuations - rev 2.01
Candy - Construction Estimating & Valuations - rev 2.01
 
Angular js notes for professionals
Angular js notes for professionalsAngular js notes for professionals
Angular js notes for professionals
 
TOC For MSA
TOC For MSATOC For MSA
TOC For MSA
 
React js notes for professionals
React js notes for professionalsReact js notes for professionals
React js notes for professionals
 
TOC training KeyCloak Redhat SSO core
TOC training KeyCloak Redhat SSO coreTOC training KeyCloak Redhat SSO core
TOC training KeyCloak Redhat SSO core
 
TOC training Keycloak RedhatSSO advanced
TOC training Keycloak RedhatSSO advancedTOC training Keycloak RedhatSSO advanced
TOC training Keycloak RedhatSSO advanced
 
BizTalk Practical Course Preview
BizTalk Practical Course PreviewBizTalk Practical Course Preview
BizTalk Practical Course Preview
 
TOC training Keycloak RedhatSSO UMA
TOC training Keycloak RedhatSSO UMATOC training Keycloak RedhatSSO UMA
TOC training Keycloak RedhatSSO UMA
 
Angular2 notes for professionals
Angular2 notes for professionalsAngular2 notes for professionals
Angular2 notes for professionals
 
ARQUIVO ROUBADO
ARQUIVO ROUBADOARQUIVO ROUBADO
ARQUIVO ROUBADO
 
Workbook vf
Workbook vfWorkbook vf
Workbook vf
 
Jquery notes for professionals
Jquery notes for professionalsJquery notes for professionals
Jquery notes for professionals
 
Rails4 Days
Rails4 DaysRails4 Days
Rails4 Days
 
Tommy Marker
Tommy MarkerTommy Marker
Tommy Marker
 
Scholarship database management database (1)
Scholarship database management database (1)Scholarship database management database (1)
Scholarship database management database (1)
 

Viewers also liked

Tugas matematika blog
Tugas matematika blog Tugas matematika blog
Tugas matematika blog yayanafla
 
AS Media OCR Evaluation Question: forms and conventions
AS Media OCR Evaluation Question: forms and conventionsAS Media OCR Evaluation Question: forms and conventions
AS Media OCR Evaluation Question: forms and conventionsthetaleofdemise
 
Rich relational data from thin air john stinson
Rich relational data from thin air   john stinsonRich relational data from thin air   john stinson
Rich relational data from thin air john stinsonJohn Stinson
 

Viewers also liked (6)

Conventions of horror
Conventions of horrorConventions of horror
Conventions of horror
 
Ideas powerpoint
Ideas powerpointIdeas powerpoint
Ideas powerpoint
 
Detective scene
Detective sceneDetective scene
Detective scene
 
Tugas matematika blog
Tugas matematika blog Tugas matematika blog
Tugas matematika blog
 
AS Media OCR Evaluation Question: forms and conventions
AS Media OCR Evaluation Question: forms and conventionsAS Media OCR Evaluation Question: forms and conventions
AS Media OCR Evaluation Question: forms and conventions
 
Rich relational data from thin air john stinson
Rich relational data from thin air   john stinsonRich relational data from thin air   john stinson
Rich relational data from thin air john stinson
 

Similar to NemanjaMarjanovicG00263151FinalYearProjectReport

Dissertation_katia_2015_ultima
Dissertation_katia_2015_ultimaDissertation_katia_2015_ultima
Dissertation_katia_2015_ultimaKatia Cuellar
 
Usability of Web Based Financial Services
Usability of Web Based Financial ServicesUsability of Web Based Financial Services
Usability of Web Based Financial ServicesAustin Dimmer
 
Optimization of an Energy-Generating Turnstile
Optimization of an Energy-Generating TurnstileOptimization of an Energy-Generating Turnstile
Optimization of an Energy-Generating TurnstileWayne Smith
 
OAuth with Restful Web Services
OAuth with Restful Web Services OAuth with Restful Web Services
OAuth with Restful Web Services Vinay H G
 
Senior Project: Methanol Injection Progressive Controller
Senior Project: Methanol Injection Progressive Controller Senior Project: Methanol Injection Progressive Controller
Senior Project: Methanol Injection Progressive Controller QuyenVu47
 
Paul Ebbs (2011) - Can lean construction improve the irish construction industry
Paul Ebbs (2011) - Can lean construction improve the irish construction industryPaul Ebbs (2011) - Can lean construction improve the irish construction industry
Paul Ebbs (2011) - Can lean construction improve the irish construction industryPaul Ebbs
 
Soa In The Real World
Soa In The Real WorldSoa In The Real World
Soa In The Real Worldssiliveri
 
Cryoserver v7 Administration Guide
Cryoserver v7 Administration GuideCryoserver v7 Administration Guide
Cryoserver v7 Administration Guidecryoserver
 
KnowledgeNet Support Manual
KnowledgeNet Support ManualKnowledgeNet Support Manual
KnowledgeNet Support ManualMohammed Ramadan
 
SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...
SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...
SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...Phil Carr
 
final SDC Evaluation Report-final-27-06-24
final SDC Evaluation Report-final-27-06-24final SDC Evaluation Report-final-27-06-24
final SDC Evaluation Report-final-27-06-24Izhar Hunzai
 
Smart attendance system using facial recognition
Smart attendance system using facial recognitionSmart attendance system using facial recognition
Smart attendance system using facial recognitionVigneshLakshmanan8
 
Minitab 090226133035 Phpapp01
Minitab 090226133035 Phpapp01Minitab 090226133035 Phpapp01
Minitab 090226133035 Phpapp01tmorfiny
 

Similar to NemanjaMarjanovicG00263151FinalYearProjectReport (20)

Dissertation_katia_2015_ultima
Dissertation_katia_2015_ultimaDissertation_katia_2015_ultima
Dissertation_katia_2015_ultima
 
Introduction to BIRT
Introduction to BIRTIntroduction to BIRT
Introduction to BIRT
 
Usability of Web Based Financial Services
Usability of Web Based Financial ServicesUsability of Web Based Financial Services
Usability of Web Based Financial Services
 
Optimization of an Energy-Generating Turnstile
Optimization of an Energy-Generating TurnstileOptimization of an Energy-Generating Turnstile
Optimization of an Energy-Generating Turnstile
 
e-Skills Match Handbook
e-Skills Match Handbooke-Skills Match Handbook
e-Skills Match Handbook
 
OAuth with Restful Web Services
OAuth with Restful Web Services OAuth with Restful Web Services
OAuth with Restful Web Services
 
Ostrander_Project_Final_Report
Ostrander_Project_Final_ReportOstrander_Project_Final_Report
Ostrander_Project_Final_Report
 
Tesi_Gasparetto_Walter
Tesi_Gasparetto_WalterTesi_Gasparetto_Walter
Tesi_Gasparetto_Walter
 
Senior Project: Methanol Injection Progressive Controller
Senior Project: Methanol Injection Progressive Controller Senior Project: Methanol Injection Progressive Controller
Senior Project: Methanol Injection Progressive Controller
 
Paul Ebbs (2011) - Can lean construction improve the irish construction industry
Paul Ebbs (2011) - Can lean construction improve the irish construction industryPaul Ebbs (2011) - Can lean construction improve the irish construction industry
Paul Ebbs (2011) - Can lean construction improve the irish construction industry
 
Soa In The Real World
Soa In The Real WorldSoa In The Real World
Soa In The Real World
 
Bwl red book
Bwl red bookBwl red book
Bwl red book
 
Cryoserver v7 Administration Guide
Cryoserver v7 Administration GuideCryoserver v7 Administration Guide
Cryoserver v7 Administration Guide
 
Comunis Project report
 Comunis Project report  Comunis Project report
Comunis Project report
 
KnowledgeNet Support Manual
KnowledgeNet Support ManualKnowledgeNet Support Manual
KnowledgeNet Support Manual
 
SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...
SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...
SSTRM - StrategicReviewGroup.ca - Workshop 2: Power/Energy and Sustainability...
 
Icp
IcpIcp
Icp
 
final SDC Evaluation Report-final-27-06-24
final SDC Evaluation Report-final-27-06-24final SDC Evaluation Report-final-27-06-24
final SDC Evaluation Report-final-27-06-24
 
Smart attendance system using facial recognition
Smart attendance system using facial recognitionSmart attendance system using facial recognition
Smart attendance system using facial recognition
 
Minitab 090226133035 Phpapp01
Minitab 090226133035 Phpapp01Minitab 090226133035 Phpapp01
Minitab 090226133035 Phpapp01
 

NemanjaMarjanovicG00263151FinalYearProjectReport

  • 1. Author: Nemanja Marjanovic ID: G00263151 Supervisor: Niall O’Keeffe B.Eng. (Hons) Computer and Electronic Engineering April 2015
  • 2. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 2 Table of Contents Table of Figures......................................................................................................................................4 Abstract...................................................................................................................................................7 Acknowledgments...................................................................................................................................9 1 Introduction........................................................................................................................................10 1.1 The Problem........................................................................................................................10 1.2 Research..............................................................................................................................11 1.3 Findings...............................................................................................................................11 Heart rate monitoring benefits ............................................................................................11 Apps....................................................................................................................................12 Heart rate monitoring technologies.....................................................................................12 1.4 Project Aims and Objectives...............................................................................................14 1.5 Project Plan.........................................................................................................................15 2 Methodology......................................................................................................................................16 Abstract.....................................................................................................................................16 2.1 Approaching the problem....................................................................................................17 2.2 Hardware Overview...........................................................................................................19 Heart Rate Detection...........................................................................................................19 Heart Rate Calculation & Bluetooth Transmission.............................................................20 2.3 Software Overview .............................................................................................................21 Android ..............................................................................................................................21 Android networking...........................................................................................................22
  • 3. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 3 Java Servlet & Database .....................................................................................................22 Desktop Application ...........................................................................................................22 Semester Two......................................................................................................................23 2.4 Hardware Implementation...................................................................................................24 Embedded Software............................................................................................................25 2.5 Software Implementation....................................................................................................27 The Android Application ....................................................................................................27 Tab 1 – Create Account ......................................................................................................28 Tab 2 & 3 – Sign In & Details ............................................................................................35 Tab 4 – Heart Rate ..............................................................................................................38 Tab 5&6 – Diet and Workout Plans....................................................................................48 Tab 7 & 8– Cardio & Outdoor Tab.....................................................................................51 Tab 9 – Performance Graphing...........................................................................................65 Servlet Operations...............................................................................................................69 Database Construction ........................................................................................................72 Desktop GUI.......................................................................................................................74 3 Conclusion .........................................................................................................................................78 3.2 Achievements.....................................................................................................................79 3.3 Future Work.......................................................................................................................79 4 Appendices.........................................................................................................................................80 5 References..........................................................................................................................................82
  • 4. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 4 Table of Figures Figure 1 – Project Plan.............................................................................................................15 Figure 2 – Chest Strap Device and Transmitter.......................................................................19 Figure 3 – FRDM-K20D50M development platform & HC_06 Bluetooth module ...............20 Figure 4 – Hardware Block Diagram.......................................................................................24 Figure 5– Interrupt Service Routine ........................................................................................25 Figure 6 – Programmable Interrupt Timer...............................................................................26 Figure 7– Create account .........................................................................................................28 Figure 8 – Weight calculation formula ....................................................................................29 Figure 9– Maximum heart rate and calorie needs formulas ....................................................30 Figure 10 – Katch-McArdle formula .......................................................................................30 Figure 11 - Heartrate zones table.............................................................................................31 Figure 12 – Heartrate zone calculations...................................................................................31 Figure 13- Creating an entry in the database ...........................................................................32 Figure 14 – Hash map class .....................................................................................................33 Figure 15 - URlContentPost.....................................................................................................34 Figure 16 – Sign In & Details Tab...........................................................................................35 Figure 17 - Data transfer & sending the query to the servlet...................................................36 Figure 18 - Data retrieval using getString................................................................................37 Figure 19 – Heart Rate Tab......................................................................................................38 Figure 20 – Bluetooth On button .............................................................................................39 Figure 21 – Find Bluetooth method.........................................................................................40 Figure 22 – Open Bluetooth method........................................................................................41 Figure 23– beginListeningForBTData method........................................................................42
  • 5. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 5 Figure 24 – Resting Heart Rate Zone Algorithm selection......................................................43 Figure 25 - Resting Heart Rate Chart ......................................................................................43 Figure 26 - Resting Heart Rate Algorithm...............................................................................44 Figure 27 - Training Heart Rate Algorithm .............................................................................45 Figure 28 - Calories Burned Algorithm...................................................................................47 Figure 29 - Diet & Workout Plan Tabs....................................................................................48 Figure 30 - Image View XML .................................................................................................48 Figure 31 - setAdapter ()..........................................................................................................49 Figure 32 - getView ()..............................................................................................................49 Figure 33 - Selecting Images from Gallery View....................................................................50 Figure 34 - Cardio & Outdoor Tab ..........................................................................................51 Figure 35 - Cardio Tab Algorithm Flow..................................................................................52 Figure 36 - Stopwatch Algorithm ............................................................................................53 Figure 37 - Linking Google Play Services to Project ..............................................................55 Figure 38 - Google Console Obtaining maps API key ............................................................56 Figure 39 - Google Console API key.......................................................................................56 Figure 40 - Android: value.......................................................................................................57 Figure 41 - Google Maps Permissions & Features ..................................................................57 Figure 42 - XML fragment addition ........................................................................................57 Figure 43- Load Google Map Code.........................................................................................58 Figure 44 - Start Service Intent................................................................................................59 Figure 45 - onCreate Myservice3 ............................................................................................60 Figure 46 - Distance between two coordinates........................................................................61 Figure 47- OnLocationChanged ()...........................................................................................62
  • 6. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 6 Figure 48- Broadcast Receiver.................................................................................................63 Figure 49 - Plotting of Markers for run path............................................................................64 Figure 50 - Performance Graphing Tab...................................................................................65 Figure 51 - Heart Rate/Time graphing.....................................................................................66 Figure 52 - Heart Rate/Time graphing.....................................................................................67 Figure 53 - getDay () of the week............................................................................................68 Figure 54 - Generate distance bar chart ...................................................................................69 Figure 55 - doPost () ................................................................................................................69 Figure 56 - JSON object checking...........................................................................................70 Figure 57 - Retrieve from JSON and Execute Prepare Statement...........................................71 Figure 58 - Database creation ..................................................................................................72 Figure 59 - Database columns creation....................................................................................73 Figure 60 - Database viewer in Heidi ......................................................................................73 Figure 61 - Eclipse’s Window Builder ....................................................................................74 Figure 62 - Gym_Buddy Desktop GUI....................................................................................75 Figure 63 - Calories Burned Graph Creation...........................................................................76 Figure 64 - Data Gathering and Array Storage........................................................................76 Figure 65 - Dataset creation.....................................................................................................77 Figure 66 - Array being passed to Dataset...............................................................................77 Figure 67- System block diagram............................................................................................78 Figure 68- Samsung Galaxy S3 Mini Specifications...............................................................80 Figure 69 - FRDM K20D50M Pinout......................................................................................81 Figure 70 Vernier Receiver pinout ..........................................................................................81
  • 7. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 7 Abstract “Coronary heart disease is the most common type of heart disease, killing nearly 380,000 people annually” – According to National Vital Statistics Report (2013). This is a worrying statistic and it shows the importance of monitoring your own health and fitness in relation to coronary heart disease. Whether you want to improve your daily workouts or train for a marathon, a heart rate monitoring system is a valuable companion. Tracking your personalized heart rate zones helps you control the intensity of your workout for long-term stamina, high- calorie burn or for other health or fitness goals. As a regular gym user with experience with using tailored diet and workout plans that would always include cardiovascular routines with specific heart rate zones in order to achieve the desired goal, I felt that the issue of inaccurate cross trainers and treadmills was a major problem. With our generation being so heavily dependent on mobile device applications I felt that a solution for the problem of usage of multiple different applications for different uses such as a pdf viewer for you workouts and a clock app for your timing or a map app for and outdoor run, could be solved by compacting all of these features to a single all in one mobile application.
  • 8. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 8 In order to demonstrate a solution for the problem an all in one fitness systems was developed that included a heart rate monitoring system with a desktop application and a database enabled mobile device application. The system consist of the following features:  Heart rate measurement with heart rate zones for exercise and resting  Calorie burn calculation  GPS tracking with live heart rate, distance & speed  Diet & workout plan storage  Single session post workout performance graphing  Database user account creation and sign in features  Multiple sessions performance graphing on a desktop application
  • 9. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 9 Acknowledgments I would like to take this opportunity to express my gratitude to my supervisor Niall O’Keeffe for his exemplary guidance, monitoring and constant encouragement throughout the course of my final year project. I would like to extend my sincere thanks to the staff members of GMIT (Galway Mayo Institute of Technology), for the valuable information provided by them in their respective fields. I am grateful for their cooperation during the period of my assignment. Lastly I would like to thank my friends and family for their constant encouragement without which this assignment would not be possible.
  • 10. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 10 Introduction 1.1 The Problem Heart disease is Ireland's number one killer with approximately 10,000 people dying each year from cardiovascular disease (CVD) - including coronary heart disease (CHD), stroke and other circulatory diseases. CVD is the most common cause of death in Ireland, accounting for 33% of all deaths. The largest number of these deaths relate to CHD - mainly heart attack - at 5,000. 13% of premature deaths (under age 65) are from CVD. Getting regular exercise for people who have a heart disease is important as it makes your heart muscle stronger and it helps you be more active without chest pains or other symptoms. Evidence from many scientific studies shows that reducing these risk factors decreases the chance of having a heart attack or experiencing another cardiac event, such as a stroke, and reduces the possibility of needing a coronary revascularization procedure (bypass surgery or coronary angioplasty). Regular exercise has a favourable effect on many of the established risk factors for cardiovascular disease. For example, exercise promotes weight reduction and can help reduce blood pressure. As with all the benefits of exercise there a risk factors involved for people suffering with heart disease. Placing too much strain on your heart during exercise will result in one of the main symptoms showing up first in CVD (Cardiovascular disease) patients which is irregular heartbeats or pulse. As person who is highly interested in health and fitness and with a family member who is affected by heart disease I was highly motivated to research monitoring of heart rate zones in more detail and to provide an all in one fitness system solution not only for a regular gym goer but also for a person affected by a cardiovascular disease so that they would be more comfortable during exercise.
  • 11. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 11 1.2 Research Detailed research was completed before the final decision to go ahead with this project was made. The main fields of research were; current heart rate monitoring technologies with mobile devices and desktop application support and health and fitness factors that could be established from heart rate monitoring. 1.3 Findings Heart rate monitoring benefits - Improved performance - training in your appropriate target heart rate will allow you to progress faster with less wasted effort. - Increased knowledge - knowledge of the hearts functions, the effects of stress and health problems on heart rate, and how heart rate varies during training will encourage you to take more responsibility for your own training. - Objective Assessment - the heart does not lie! The heart shows the response of the body at any moment in time allowing you to assess intensity and recovery. - Objective training - are you burning fat or are you burning carbohydrates? Training in appropriate heart rate zones takes the guesswork out of your cardiovascular program by customizing the proper exercise intensity for your goals. - Recent large epidemiologic studies have confirmed earlier studies that showed resting heart rate measurement to be an independent predictor of cardiovascular and all-cause mortality in men and women with and without diagnosed cardiovascular disease.
  • 12. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 12 There are many benefits of heart rate monitors. Your workouts become more time efficient and safe, intensity can be measured simply and reliably. Your goals are more easily set and reached, progress or lack of progress toward fitness is easily tracked and motivation to improve increases through greater awareness, and knowledge replaces guesswork. Apps There are numerous applications on the market that aid a person’s fitness regime with majority having a GPS tracker that will follow the user’s route when they are walking/running. The data is then uploaded to a site that can be accessed by the user at any time to view their route. Other application focused primarily on having heart rate monitoring without any other interesting features included with the data being stored only on the device itself. This restricted the user to only viewing the data for that single measurement on the phone. Other application existed but where consisted of a cluttered user interface and had to rely heavily on other applications for other health data. Heart rate monitoring technologies “For the casual user looking to get a resting heart rate, wrist-based devices are fine. No manufacturer claims that these bands work for extreme athletes, and most make it clear that this style of band is for casual use only -- never for medical use -- and that they work only when you're still. Usually, manufacturers package the heart-rate sensing technology with tried-and- true motion sensors that track steps and activity, too.
  • 13. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 13 But aside from gauging huffing and puffing, heart rate tracking during exercise is one of the best ways to evaluate overall fitness. If you're looking to hit a target heart rate while moving, you may be better off using a chest-strap device or even the ol' finger-to-the-wrist method” CNET – “Do wristband heart trackers actually work? A check-up “ From research about different heart rate monitoring technologies I stumbled upon an article provided by CNET UK which put five leading smart devices with heart rate monitors to the test, measuring their accuracy with an EKG (Electrocardiogram) and the results were that if you were looking to hit a target heart rate while moving that the best solution was using a chest- strap device as it was the most accurate when comparing to an EKG. From these findings I firmly decided to use a chest strap device as I wanted high accuracy heart rate readings.
  • 14. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 14 1.4 Project Aims and Objectives The overall aim of the project was to provide an accurate heart rate monitoring system which could be used to accurately record and store resting and exercise heart rate zones that would not only benefit CVD (Cardiovascular Disease) patients but also regular gym user’s. An additional aim was to provide the user with a mobile application that would determines heart rate zones depending on recording taken from chest-strap device which would also contain other useful features that would be beneficial for a gym user. With this in mind the following objectives were drafted:  Develop an accurate heart rate monitoring systems  Design a simple to use android app  Implement heart rate zones depending on data of user  Implement diet and workout plan storage  Include a GPS tracker with live heart rate ,calorie burn and distance data being recorded  Apply Indoor & Outdoor cardiovascular training modes  Apply Database storage of exercise data recorded with single session performance graphing  Design a desktop application for viewing and graphing of recorded data
  • 15. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 15 1.5 Project Plan The project plan was designed in September 2014. Initially the project progress was on track however, with the additional workload of other modules the progress was soon stalled. Due to this delay some elements and a few new additions, the project took longer than expected. Figure 1 below shows the original project plan designed in September 2014. Figure 1 – Project Plan
  • 16. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 16 2 Methodology Abstract In this chapter of the report the method in which features were designed developed and tested will be described, the theory behind the project and each of its individual features will be explained as well as the research and steps taken during the development phase of the feature in question, as well as the approach taken to solve any problems that were encountered. First of all the general research and methods will be explained then the actual way in which features were implemented will be explained.
  • 17. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 17 2.1 Approaching the problem The problem was approached by breaking down the overall project down into smaller individual components that were later combined to form a fully functional system. The breakdown of the project is as follows.  Hardware – Embedded System - Heart Rate Detection Using Vernier Exercise Heart Rate Monitor - Heart rate measurement & calculation on a Freescale FRDM-K2050DM microcontroller - Transmission of heart rate data using HC_06 Bluetooth module  Software - Android Application with networking for heart display of heart rate data and other fitness factor - Server Application & Database Construction - Desktop application for viewing of data stored on database & performance graphing
  • 18. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 18 As a person with Agile software methodology experience which was gained as part of a six month placement in Intel Shannon working in an team that followed this type of software development process. I learned that it was best to tackle projects was feature-by-feature instead of in big phases. With this knowledge a goal oriented modular approach was taken, small goals that were flexible were established and the above features were never developed from start to finish individually as some aspects of one feature might have been dependant on another aspect of another feature. This resulted in all of the features progressing gradually which in result allowed the developer to jump from one part of the system to another. What this resulted in was small blocks of functionality that could easily be adapted to the main project, removed or modified. The design process of each of the blocks started with a goal, research on how this goal should be achieved and then implementing the knowledge into a small project which would later be merged with the main project. This type of approach continued until the completion of the systems, this practice was adopted due to the fact that it made bug fixing easier and it also added an element of safety due to the fact that it wasn’t implementing new functionality to the main project but first being thoroughly tested before the additions was applied and this method made sure that new code wouldn’t jeopardize the functionality of the main code and even if it were to cause problems it was easy to extract and fix.
  • 19. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 19 2.2 Hardware Overview Heart Rate Detection On initial research of heart rate monitoring techniques and the equipment used the findings that I have found were pointing in the direction of using a chest-strap device as it was the most accurate method of monitoring. With these findings I spoke to my supervisor Niall O’Keeffe who provided me with an exercise heart rate monitor consisting of a wireless transmitter belt and a receiver module that originally plugged in to a Vernier interface. The transmitter belt senses the electrical signals generated by the heart much like an EKG. For each heart beat detected, a signal is transmitted to the receiver module, and a heart rate is determined. As this unit was designed to be used with one of Vernier’s interfaces it required a low power microcontroller to replace that equipment. Figure 2 – Chest Strap Device and Transmitter
  • 20. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 20 Heart Rate Calculation & Bluetooth Transmission As part of a 4th year Embedded Systems module Freescale K60 development board was used which not only familiarised me with the Freescale product’s and documentation but also with the development tool that is CodeWarrior which a complete integrated development environment (IDE) that provides a highly visual and automated framework to accelerate development of the most complex embedded applications. With this familiarity and the need of a low power microcontroller and guidance of my supervisor I turned to a Freescale product which was the FRDM-K20D50M ultra-low-cost development platform enabled by the Kinetis K20 USB MCU family built by ARM Cortex M4 processor. Features include the Freescale open standard embedded serial and debug adapter (OpenSDA), providing easy access to MCU I/O, battery-ready, low-power operation, a standard-based form factor with expansion board options and a built-in debug interface for flash programming and run-control. With the idea of Bluetooth transmission in mind this development platform offered easy access to MCU I/O via Arduino R3 compatible I/O connectors which was perfect for the HC-06 Bluetooth module planned. This module permits any microcontroller with a standard RS232 serial port to communicate with a PC or a Smartphone equipped with a Bluetooth Master module Figure 3 – FRDM-K20D50M development platform & HC_06 Bluetooth module
  • 21. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 21 2.3 Software Overview Android As a person who is highly interested in mobile device applications I knew that this was the route I wanted go down in my final year project. Mobile Device Programming module was introduces to us in the first semester of 5th year and in a short period of time I was proficient in android development using Eclipse (IDE) combined with android SDK .With this newly acquired skill set I was able to design an Android application with the theme in mind. Originally the applications main objective was display heart rate data and zones belonging to that heart rate but as time went on other ideas were created by problems recognised during daily cardiovascular and training activity. Ideas included were the addition of diet and workout plans and also contribution by my lecturers which included Michelle Lynch’s idea of adding GPS tracking of an outdoor run with live heart rate data and also the option to see the route taken. My supervisor Niall O’Keeffe provided me with valuable tips letting me know that in order for this systems to be a fully functional systems that it needed to include data base storage with an option of a back end solution to view data recorded and with this information I dedicated myself to achieve this feature also.
  • 22. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 22 Android networking As part of the mobile device programming module android networking information was provided which included the basic transfer of basic data types to a servlet that could return modified values of the data that was sent, the medium in which this data was send was via JSON objects. A basic project was then developed with Android networking for testing purposes so more could be learned on how to apply it to the main systems. Java Servlet & Database Mobile Device Programming and Server Client Programming modules provides us with necessary skills to achieve full functionality of a java servlet to database communication so this area required very little research. In order to achieve the communication between a java servlet and SQL database the use of a JDBC driver software component was needed which was responsible for enabling the Java application to interact with the database. Desktop Application With great advice from my supervisor a desktop GUI was developed as a back end solution for the system. At the time MigLayout had only recently been learned during the previous semester in the Software Engineering 1 module of the course, however its usability and advantages were immediately obvious. The GUI was designed to access player’s performance information that was stored on a database by an Android application which allowed the user to view five session performance graphs.
  • 23. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 23 Semester Two For most of semester one research was the main focus of the project. Once the appropriate background research had been completed and a great deal had been learnt in terms of the needed technologies and java programming techniques that would help to complete the project. Work first started on the embedded side of the project which included interfacing the heart rate receiver module to the Freescale freedom board.
  • 24. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 24 2.4 Hardware Implementation Figure 4 – Hardware Block Diagram. The project consists of a low power Freescale freedom board which has interfaced to it a Heart Rate Receiver Module. Heart Rata Data is gathered using the Exercise Heart Rate Monitor which is fitted firmly on a person chest which then monitors that person’s heartbeat. The transmitter detects each heartbeat through two electrodes and transmits heart rate information to the receiver with a low frequency electromagnetic field. Heart Rate Receiver is connected to the Freescale board and once the heart beat is detected it is put in a formula which calculates the heart rate and is sent via Bluetooth to the app.
  • 25. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 25 Embedded Software Embedded side of the project consisted of development using C-Programming in a CodeWarrior IDE. Once the board was setup the programming could begin. As the receiver detects a heartbeat transmitted by a chest-strap device a hardware interrupt is caused and the following snippets of code is executed: Figure 5– Interrupt Service Routine HeartRateCounter variable is incremented of every interrupt detected which is responsible for keeping the data of the number of heartbeats. PIT is then used which is a 16-bit timer that provides precise interrupts at regular intervals with minimal processor intervention. The timer counts at the peripheral clock frequency. The timers count down from an initial count value to 0 and set an interrupt flag. The timer is then reloaded with the initial count value and the countdown continues. This was used to countdown ten seconds and transmit heart rate data gathered over Bluetooth.
  • 26. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 26 Figure 6 – Programmable Interrupt Timer Once the counterSec counter reached ten seconds the data gathered was cast to an unsigned char and passed to uart_putchar for transmission over Bluetooth.
  • 27. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 27 2.5 Software Implementation The Android Application The Android application, from a project point of view, was the central element. Android provides a rich application framework that allows you to build innovative apps for mobile devices in a Java language environment. The software for the app was all developed in Java using the Android Development Tools (ADT) plugin for Eclipse IDE (Integrated Development Environment). ADT plugin extends the capabilities of Eclipse to allow the user to quickly set up new Android projects, develop Android applications, add packages based on the Android Framework API, debug your application using android SDK (Software Development Kit) tools, and also allowing you to distribute your application on the Google play store. An activity represents a single screen with a user interface. All the GUI (Graphical User Interface) design for the activity is created using the layout.xml filet which is included in the Android project. The Gym Buddy application consists of two activities with the first activity being a welcome screen. The main activity consists of Android Tab Host which provides a nice way to present multiple thing on a Single Screen. These things are presented by Tabs. Gym Buddy fitness app contains nine tabs. These tabs are for create account, sign in, details, heart rate, gym plans, diet plans, cardio, outdoor run and post workout graphing.
  • 28. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 28 Tab 1 – Create Account Tab one was designed for the user to insert all of the required information for the heart rate zones and other fitness factors to be determined. Figure 7– Create account The user was asked to enter the following details name & password which would ensure that it would be only them that could access their accounts and impact their statistics and the password was decided as feature to uphold the integrity of the user’s statistics provided to them by the application. Age, gender and height were the most important pieces of information entered by the user as these pieces would help determine heart rate zones and the maximum daily calorie allowance. Once the user entered the following information the first bit of calculation that was required was the weight. As the calorie burn formula required the use of pounds it would be necessary to allow the user to enter either kilograms or pounds as
  • 29. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 29 his choice of measurement. Depending of the choice taken a suitable conversion method would be implemented. If the user selected kilograms as the weight measurement a formula to convert to pounds was used. Multiplying the kilograms entered by 2.2046 returned the correct weight in pounds. Figure 8 – Weight calculation formula The second calculation and probably the most important component of the system was establishing the maximum heart rate of the user. Depending on the gender and age of the person using the system a calculation was required to determine maximum heart rate. The formula for male is as follows 220 – Age = Maximum Heart rate and for females is 226 – Age = Maximum Heart Rate. So once the user has entered their age and gender the following snippet of code was used.
  • 30. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 30 Figure 9– Maximum heart rate and calorie needs formulas Depending on the gender and age of user maximum heart rate would be calculated. The Katch- McArdle formula was used to determine the maintenance calories which required the use of weight entering by the use. The formula is as follows for both men and women: BMR = 370 + (21.6 x Lean Body Mass (kg)). This is a newer formula that accounts for your lean body mass, which generally gives you a more accurate estimate of your basal metabolic rate (BMR). Figure 10 – Katch-McArdle formula
  • 31. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 31 One last calculation is required before the details recorded are stored on a data base and this is the different heart rate zones. As the maximum heart rate zones was calculated this data could then be used for determination of heart rate zones. Figure 11 - Heartrate zones table Using the figure above code was written to get warm-up, fat burning, aerobic, high intensity and maximum heart rate zones. This was achieved in the following manner. Figure 12 – Heartrate zone calculations
  • 32. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 32 In order to get a zone a calculation was used by which the percentage of the maximum heart rate was calculated to get the necessary data to display different zones. As an example we take the fat burning zone, by looking at the diagram your body is in fat burning zone when you heart rate is at 60-70 % of your max heart rate so by getting 60% this would be the lower zone of fat burning and getting 70 % of the heart rate would be the higher zone of fat burn and as long as the heart rate was in the range of these values it would be considered within the fat burning zone. With all of the necessary data entered and calculated the create account button could then be activated in order for the data gathered to be stored in a data base. Figure 13- Creating an entry in the database
  • 33. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 33 The first thing this activity does is acquire twelve strings that of the inputted name and the desired password and other inputted data and it creates a new instance of my class DataBaseData class that takes in twelve string variables in this case they are the name, password, age , gender , units , weight , max heart rate, average heart rate , calories needed, calories burned , speed ,instance and create, the create string is a tag that is used to tell the server that it will be a creating an entry in the database for a new user but there will be more on that later, the DataBaseData class just places these strings into a hash map. Figure 14 – Hash map class
  • 34. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 34 A new JSON object is then created and the hash map is passed to it. A new string is then created using the static urlContentPost in the httpUtils class here is the method the below. Figure 15 - URlContentPost This method was responsible for posting the parameters passed to it to a URL passed to it in its parameters in this case the URL of my servlet running on an apache tomcat server. http://localhost:8080/NemanjaTest/Servlet The JSON object was then converted to a string and was also given the name “User Data” this gave the content post method all the variables in required, the address, the name parameter and the value parameter, the doPost method on the servlet side then waited to receive the JSON or multiple JSON objects with a certain name parameter and responded accordingly with a string which you could pass to a JSON object and use to extract data sent back by the server. This was the method was how the data was sent and received by the Android device, the IP address the data was sent to was different depending which network the pc was connected to . As my application needed to be used in an environment where WIFI wasn’t always available it needed to be able to transfer the data over the 3G network.
  • 35. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 35 Port forwarding needed to be setup on the router for demonstration purposes. I began by logging in to router and activating port forwarding on port 8080. Then getting the PC’s global IP which was then used in the Android applications on the same port. The data transfer was always threaded as not to freeze the applications UI as it took care of the task. Placing of data into hash maps and inserting them into JSON objects and sending them via the content post method was how all the data transfer in the app, whether it be sending or receiving was handled. Tab 2 & 3 – Sign In & Details Figure 16 – Sign In & Details Tab After a successful method was discovered to send data to the server and insert it into the database, all that was left to do was for the client to receive data from the servlet upon it receiving a query and searching the database for the player query information sent by the client. The sign in tab was created to give the user the facility to search for his name and information already stored under and he would get the relevant user information loaded to a
  • 36. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 36 details tab with an option to update some information. A simple UI (User Interface) was designed with two text field and two buttons, text fields were there for entering of user’s names and password and one button for activation of data transfer and sending the query to the servlet but this time data was expected in return also. The other button’s feature was to clear the text field allowing the user to clear the information entered. Figure 17 - Data transfer & sending the query to the servlet
  • 37. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 37 From the figure above it can be seen that the string that is being returned by the URL content post method is used to create a new JSON object by the name of jsonDataReturn , then the variables are being extracted from this JSON object which are the desired variables requested by the client. Prior to this name and password is retrieved from the text area and stored in a hash map that has a “Sign In” key as part of it. New JSON object is created and the hash map containing three strings which are name, password and “Sign in “ are passed in to it to be sent to the servlet. Prior to this name and password is retrieved from the text area and a new instance of DataBaseSignIn is created which takes in two strings which are name and password and a command string tag. Then a JSON is being sent to the servlet containing the hash map with the necessary data with a tag to define that it wishes to query the database. The jsonResult JSON object hold the response sent back by the servlet. Data is then retrieved by using the getString which will get the string associated with the key. Figure 18 - Data retrieval using getString
  • 38. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 38 Once the data is retrieved it is all then stored in details tab for the user to review and change if needed. As well as the user being able to review the data the information loaded is also used for calculation of necessary factors for the app to function accordingly. Age, gender, weight & max heart rate is used to determine heart rate zones & calories burned throughout exercise. Tab 4 – Heart Rate Tab four was responsible for the activation of Bluetooth and the display of heat rate and the zones assigned to that zone. Figure 19 – Heart Rate Tab The UI (User Interface) of this tab consisted of two buttons, one being responsible for the activation of Bluetooth and the other for de-activation. Two check box selection option was displayed for the user for selection of either resting or training heart rate zones.
  • 39. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 39 The tab also included a heart image which was animated to pulse on a pulse received as well as a graph which also included a circle that would bounce when a pulse was detected with a sound animation included. On activation of the Bluetooth on button two methods were called findBluetooth () and openBluetooth (). Figure 20 – Bluetooth On button As name might suggest findBluetooth () method was responsible for device discovery. BluetoothAdapter class was used which lets you perform fundamental Bluetooth tasks , such as an initiate device discovery , query list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for connection from other devices, and start a scan for Bluetooth LE device. In the figure below we can see how this was achieved.
  • 40. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 40 Figure 21 – Find Bluetooth method Firstly it was checked if a bluetooth adapter was available and once this was established I checked if bluetooth adapter is enabled and if not an intent was created for enabling of bluetooth. Once you have the local adapter , you are able to get a set of BluetoothDevice object representing all paired devices with getBondedDevices(). And if the paired device had the name of HC-06 which was the embedded bluetooth module device it was assigned to a Bluetoothdevice mmDevice variable.
  • 41. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 41 On successful pairing of the devices I then moved on to the openBluetooth() method, where a Bluetooth socket for communication for with the paired device was created and opened. To create a Bluetoothsocket for connecting to the paired device BluetoothDevice.createRfcommSocketToServiceRecord(uuid) method was used and started using BluetoothSocket.Connect to initiate connection. This also performed an SDP lookup of the given uuid to determine which channel to connect to. Once the socket was connected IO stream was opened by calling getInputStream () on the socket and then that socket was assigned to an InputStream which is used for reading byte based data, one byte at a time. BeginListeningforBTData () method was then called which was responsible for interpretation of the incoming data Figure 22 – Open Bluetooth method
  • 42. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 42 The biggest chuck of programming was done within this method as it was the spine of the whole application. The first part that was done was getting and estimated number of bytes and if the bytes received where greater than zero a byte array of the estimated size was created. Use of the read () method of an InputStream returns an integer which contains the byte value of the byte read. Once the read () method returns -1, the end of stream has been reached, meaning there is no more data to read in the InputStream. The byte array is then checked for an ASCII 10 (“End Line”) and decoded in to a string. That string is then looped through and checked for the character stored in it. This character is then cast to an integer and multiplied by six to give us beats per minute. Figure 23– beginListeningForBTData method
  • 43. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 43 Now that out beats per minute have been identified checking of heart rate zones could be done. Beats per minute was stored in a integer variable called btsPM which on every heart rate received over Bluetooth was used to check what heart rate zone it belonged to. If the resting check box was selected and beats per minute were lower than warm up zone, age and btsPM variable were passed to a method for calculation of resting heart rate zones and the method also relied on the gender of the user. Figure 24 – Resting Heart Rate Zone Algorithm selection Which was developed using the help of the following table. Figure 25 - Resting Heart Rate Chart
  • 44. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 44 Below here is a code snipped of how the algorithm was achieved. Figure 26 - Resting Heart Rate Algorithm As an example we take a male in the age bracket of 18 to 25 and the heart rate between 49 and 55 which tells the user that he has an excellent heart rate resting conditions. The zones are rated from athlete-excellent-good-above average-average-below average and poor so if the user was in the age bracket specified heart rate between 49 up to 82+ was used to determine the zone. If the training check box was selected and the heart rate recorded was greater or equal to the warm up zone the following algorithm was implemented.
  • 45. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 45 Figure 27 - Training Heart Rate Algorithm As we can see in the above figure that if the heart beat recorded was greater or equal to warm up low zone (Calculated by getting 50% of maximum heart rate) and less than warm up high zone and as long as training check box was active the user would be displayed with his heart rate zone on the UI (User Interface) and also the method pumpHeart() was called which produced the animation of the beating heart with a heartbeat noise which also used an instance of the graphView class which was responsible for drawing of a graph with a circle being animated to represent a pulse. The same principal was applied to the rest of heart rate zone measurement.
  • 46. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 46 Beats per minute recorded were stored in to an array list which was passed to a method which was responsible for the calculation of the average heart rate. Reason that this was needed was for the calorie burned formula which needed the average heart rate calculated. Within the method array list was looped through and all the data stored in the array list was summed and then divided by the size of the array to get the average. With this average recorded the formula for calories burned from the Journal of Sports Science could be used which was as follows: Men Calories Burned: = [(Age x 0.2017) - (Weight x 0.09036) + (Heart Rate x 0.6309) -55.0969] x Time / 4.184. Women Calories Burned: = [(Age x 0.074) - (Weight x 0.05741) + (Heart Rate x 0.4472) - 20.4022] x Time / 4.184.
  • 47. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 47 Algorithm developed for calculations was as outlined below. Figure 28 - Calories Burned Algorithm So depending on gender of the user a specific formula was used to calculate calories burned which would then be displayed in the indoor or outdoor cardio tabs.
  • 48. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 48 Tab 5&6 – Diet and Workout Plans Figure 29 - Diet & Workout Plan Tabs Tabs four and five were used for displaying images of diet and workout plans that were stored on the phone. This was achieved using android Galley and Image View. Android xml needed to be modified in order at include gallery view and image view. Figure below explains how this was achieved. Figure 2.27 Gallery View XML Figure 30 - Image View XML
  • 49. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 49 Once the xml was setup we then needed to set Adapter to the gallery. Figure 31 - setAdapter () Set adapter provides the data and the views to represent the data in this widget. WorkoutImageAdapter class contained all of the images that held workout plans. getView () method within the class was responsible for dealing with the images. Figure 32 - getView ()
  • 50. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 50 From this a gallery view with workout images could then be viewed within workout plan’s tab. To enable the user to click on the gallery image and display it in a larger image view plain the use of setOnItemClick listener was used with onItemclick responsible for setting the imageView with image clicked on in the gallery view. Figure 33 - Selecting Images from Gallery View The technique used for workout plan images was also mimicked for diet plan information also.
  • 51. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 51 Tab 7 & 8– Cardio & Outdoor Tab Cardio tab was designed to allow the user to select between indoor and outdoor cardio and depending on that selection calories burned and heart rate data would either be displayed in the indoor cardio tab or on an outdoor tab containing a google map fragment. The layout out of the tab included two check boxes. One was used for indoor selection and the other for outdoor with two areas below to display heart rate and calorie burned information. Stopwatch interface was also included as part of the GUI. Figure 34 - Cardio & Outdoor Tab
  • 52. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 52 If the indoor option is selected and the stopwatch started the user is able to see his heart rate with the zones and also the calorie being burnt within the cardio tab. Figure 35 - Cardio Tab Algorithm Flow
  • 53. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 53 In order to enable a stopwatch feature Android SystemClock was used. To update the value of the timer the use a handler was needed. The Handler takes a runnable object and it schedules its execution; it places the runnable process as a job in an execution queue to be run after a specified amount of time. The runnable was run on the thread to which this handler is attached. Figure 36 - Stopwatch Algorithm
  • 54. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 54 timerinMilisec was updated using an Android System clock method which returns millisecond since boot, not counting time spent in deep sleep. Which is then taken away from startTime variable which is assigned in the same method except in the onCreate part of the activity. From this method all of the necessary components were gathered for the stopwatch to be displayed. Outdoor selection was used to show the user a google map fragment which display’s users heart rate, calories burned and distance of run which uses an Android Service for GPS (as it is CPU intensive and it needs to run in the background away from the main UI). Before any of Android service programming was done the setup before the use of Google maps needed to be done. This included downloading Google play services within the Android SDK Manager followed by importing the downloaded library into the eclipse workspace. Getting the Google map key was the next step as for use of Google maps you need to create a valid Google Maps API key. The key itself is free and you can use it with any other application that call the Maps API and it also supports unlimited number of users. You get this key via the Google APIs Console. You have to provide your application signature key and the application package name. This is based on the key with which you sign your Android application during deployment.
  • 55. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 55 During development with Eclipse, Eclipse automatically creates and uses a debug key. Creating a SHA-1 for you signature key was the next path that needed to be taken. To generate SHA-1 fingerprint using java keytool open your terminal and execute the following command to generate SHA-1 fingerprint. keytool -list -v -keystore "%USERPROFILE%.androiddebug.keystore" -alias androiddebugkey -storepass android -keypass android Once the command is executed in the output you will be able to see SHA1 finger print. The next step was to open Google API Console and select Services on left side of the panel and turn on Google Maps Android API v2. Figure 37 - Linking Google Play Services to Project Next order of business was to select API access on left side and on the right side click on Create new Android key.
  • 56. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 56 Figure 38 - Google Console Obtaining maps API key Once you have clicked on Create new Android key a popup window is activated asking for the SHA1 and package name. This is where the obtained SHA1 and your android project package name separated by a semicolon were entered. And also take note of the API key which will be required later in the project. Figure 39 - Google Console API key
  • 57. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 57 Once the previous steps were completed and all of the necessary information was gathered we could then move on to modifying the AndroidManifest.xml. Replacing the android: value with your map key was then done. Figure 40 - Android: value Google maps also needed the following permissions and features. Figure 41 - Google Maps Permissions & Features Once all of the initial setup was completed focus could be turned to displaying a Google map fragment within the tab itself. Once the fragment was added to the tab in the following way: Figure 42 - XML fragment addition
  • 58. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 58 It was quiet easy to display the map itself in the fragment with the use of the following code. Figure 43- Load Google Map Code With Google maps being now present within the tab the use of android services was required. A service is an application component that runs in the background, not interacting with the user for an indefinite period of time. Services, like other application objects (activities, broadcast listeners…), run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work and this is exactly what was done. Each service class also must have a corresponding declaration in its package's AndroidManifest.xml. Android Service class responsible for GPS locations was activated using an intent which was started on initiation of start stopwatch button only if outdoor mode of cardio was selected.
  • 59. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 59 Figure 44 - Start Service Intent Once the service was kicked off Myservice3 class broadcasted GPS locations. onCreate () for the class was responsible for getting the GPS status and requesting GPS updates in the time provided and on specified distance moved.
  • 60. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 60 Figure 45 - onCreate Myservice3 As the minimum distance for location update was set to very low OnLocationChanged() was called often which provided the user with new latitude and longitude and each time these were placed in to a hash map which was used for the calculation of distance between locations. Outlined below is the code responsible for this.
  • 61. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 61 Figure 46 - Distance between two coordinates The difference between previous and current latitude and longitude was calculated and this data was then used for the haversine formula to compute the distance from the two locations. This formula assumes that the Earth is a plain sphere. Once the distance was returned by the method the latitude, longitude and distance were sent to a broadcast receiver which was present in the main activity.
  • 62. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 62 Figure 47- OnLocationChanged ()
  • 63. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 63 Once the data was received by the broadcast receiver which included latitude, longitude and distance markers of the initial start of run and path of movement could be displayed as well as the distance being travelled by the user could also be displayed on the Google Map Fragment. Figure 48- Broadcast Receiver
  • 64. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 64 Markers were dropped on every 20 meters to portray the path of the user’s movement. Below is the described algorithm. Figure 49 - Plotting of Markers for run path On initial start of movement first markers is dropped and then on every 20th meter. On end of outdoor cardio the user would stop the stopwatch and in results the data recorded (Average Heart Rate, Distance, Calories Burned and Speed) for the duration of the workout would be sent to the database in the same method as previously described and performance graphs would be shown in the next tab.
  • 65. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 65 Tab 9 – Performance Graphing Figure 50 - Performance Graphing Tab Tab seven was where all of the gathered information throughout the duration of the single session were graphed. To achieve this a graphing library called MPAndroidChart created by Philip Jahoda was used. The data that was graphed was heart rate average and heart rate over timer as well as calories burned graphed on a pie chart versus daily calorie needs. Distance was also graphed on a bar chart specifying the distance that was covered on a particular day. Plotting the heart rate average and heart rate over time the following code snippet was used.
  • 66. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 66 Figure 51 - Heart Rate/Time graphing In the figure above we can see a method which is responsible for creation of a line chart and which is part of MPAndroidChart library, array lists containing minutes and heart rate were used in order to graph the required data.
  • 67. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 67 Pie chart graphing required the use of calorie needs and calories burned calculated for plotting. With this data supplied a clear graphs of calories burned vs calories allowed was achieved. Figure 52 - Heart Rate/Time graphing Distance calculated throughout the outdoor run was graphed on a bar chart which specified the distance that was covered on a particular day of the week. In order to get the day of the week Android Calendar was used and the following algorithm was developed.
  • 68. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 68 Figure 53 - getDay () of the week Day of the week was got using the calendar. Get (Calendar.DAY_OF_WEEK) and depending on a day an array list would be populated with a string corresponding to a name of that day. Days were then used to display to the user what day of the week he had covered which distance.
  • 69. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 69 Figure 54 - Generate distance bar chart Servlet Operations The servlet’s role in the project was to receive and send data back to android device and store and request data from the database. All data was sent and received from the servlet’s do post method, this method waits on a post from the client in this case Android device. Figure 55 - doPost ()
  • 70. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 70 The string “inputString” is the JSON object in string format, the “UserData” was the name value that was passed to the content post method that is how the servlet was able to distinguish individual JSON objects being sent from the client. The servlet in this case always received one JSON object with the same name value but a unique string in each hash map was used to differentiate between a query command for the database and an insert command. Figure 56 - JSON object checking In the above figure a JSON is being created using the string received in Figure 2.43 and the string “Command” is being defined as whatever string is in that JSON’s hash map with the name value of “Command”, the name value “Command” was default for all JSON object being sent but what this string was equals to was unique depending on the data inside the JSON object. As we can see from the figure above the string is then being checked if it is equal to “Create”, if this is true the code will go into that block and execute appropriate code. This is how the servlet distinguished between different contexts and commands that the client needed such as queries and insertions in to the database.
  • 71. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 71 In the instance for the create account activity the string with the name “Command” was equal to “Create” which led the servlet to enter the block of code that was used to create a new entry in the data base for the new user. Where the data passed was retrieved and a prepare statement was used to insert that data in to the data base. Figure 57 - Retrieve from JSON and Execute Prepare Statement
  • 72. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 72 Database Construction Once the client-server communication was achieved, it was time to implement a database. The software program HeidiSQL was used to set up the database. XAMPP was used in conjunction with this to run the database. Constructing a database with Heidi was very simple and the first by the name of “GymBuddyDB” was created. Figure 58 - Database creation The Gym buddy database was created on the local host and could be connected to via port 3306. Once the data base was created within that session it was then populated with the required fields. Below you are able to see database filled with some statistic columns.
  • 73. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 73 Figure 59 - Database columns creation Figure 60 - Database viewer in Heidi
  • 74. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 74 Desktop GUI The final feature that was implemented in the project was a desktop GUI, its functionality was to include.  Searching the database for a user and displaying their fitness statistics  Graphs the users fitness performance The layout of the GUI was designed in Eclipse’s Window Builder GUI designer. This extensions allowed the user to design the GUI with a graphical representation of the layout desired. By selecting text fields, buttons and positions of the window code would then be generated for the creation and position of these components. Figure 61 - Eclipse’s Window Builder
  • 75. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 75 Figure 62 - Gym_Buddy Desktop GUI The user simply enters his name and password that he created within the android application and presses the sign in button. This action takes the requested name and password and queries the database for the user. The operations for searching for a player in the database in this instance is the same as it was in the Android application but no transmission to the server was needed as it read the database directly from the local host. One thing the GUI project needed was the addition of the JDBC driver like what was done with the Java servlet. On successful loading of data from data base recorded data would be displayed and four performance graphs. Throughout research and advice from a lecturer it was decided that JFreeChart graphing library would be used for performance graphing. From below figure we can see how the creation of one of the graphs was established.
  • 76. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 76 Figure 63 - Calories Burned Graph Creation As with android graphs arrays would be expected to be passed to the graph functions. Data loaded from the database would be retrieved and parsed to required data type that would then be added to an array. Figure 64 - Data Gathering and Array Storage
  • 77. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 77 The gathered data would then be added to a data set that was created. Figure 65 - Dataset creation Figure 66 - Array being passed to Dataset As we can see in the above figure the array created from the data gathered from the database was then added to a dataset which would then be used to portray a graphical image of the performance graphs.
  • 78. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 78 3 Conclusion Overall the project was a success. All objectives were met and the Gym Buddy System turned out to be a fully functioning fitness system that successfully monitored user’s heart rate date as per the project description. The following diagram shows all of the components that the project has incorporated. Figure 67- System block diagram
  • 79. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 79 3.2Achievements A complete solution for the problem proposed was achieved. The systems is a fully functioning product that can support regular gym user or a patient that has cardiovascular disease and guide them both their hearth condition monitoring or fitness goals. All aspects of the project objectives were completed and implemented. The final features included are:  Accurate Heart Rate Measurement using chest-strap device  Simple to use and unique android app  Heart Rate Zone Measurement  Diet & Workout Plan Storage  GPS tracker with live heart rate data, calorie burn and distance being recorded and displayed on a Google Map  Indoor & Outdoor cardiovascular training modes  Database storage of exercise data recorded with single session performance graphing  Desktop application for viewing and graphing of multiple sessions data 3.3Future Work During development of the system, Android application itself was solely tested on the Samsung Galaxy S3 mini phone. Tests will have to be conducted to ensure the app is compatible with different android OS platforms and screen sizes. As the android application was tested with connection for use on a single heart rate measurement device additional test will be required to ensure same outcome of data recording.
  • 80. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 80 4 Appendices Figure 68- Samsung Galaxy S3 Mini Specifications
  • 81. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 81 Figure 69 - FRDM K20D50M Pinout Figure 70 Vernier Receiver pinout
  • 82. Nemanja Marjanovic B.Eng. (Hons) Computer & Electronic Engineering April 2015 82 5 References 1 FRDM-K20D50M Setup Guide and Documentation http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=FRDM-K20D50M 2 Exercise Heart Rate Monitor Information & Data Sheet http://www.vernier.com/products/sensors/heart-rate-sensors/ehr-bta/ http://www.vernier.com/files/manuals/hgh-bta.pdf 3 Android Google Map View Tutorial & Information http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/ https://developers.google.com/maps/documentation/android/ 4 Heart Rate Zone, Calorie Needs Information http://www.freedieting.com/calorie_needs.html http://fitnowtraining.com/2012/01/formula-for-calories-burned/ http://build-muscle-101.com/heart-rate-to-burn-fat/ 5 Gallery View http://developer.android.com/reference/android/widget/Gallery.html http://developer.android.com/reference/android/widget/Adapter.htmlgo 6 Android Tab View Information http://developer.android.com/training/implementing-navigation/lateral.html 7 Java IO http://tutorials.jenkov.com/java-io/inputstream.html 8 Android Bluetooth http://developer.android.com/guide/topics/connectivity/bluetooth.html