Sei sulla pagina 1di 65

VIETNAM NATIONAL UNIVERSITY, HANOI

UNIVERSITY OF ENGINEERING AND TECHNOLOGY

Nguyen Van Tinh

DETECTING HUMAN FALLS WITH A 3-DOF


ACCELEROMETER
Major: Electronics and Communication

HA NOI - 2014

VIETNAM NATIONAL UNIVERSITY, HANOI


UNIVERSITY OF ENGINEERING AND TECHNOLOGY

Nguyen Van Tinh

DETECTING HUMAN FALLS WITH A 3-DOF


ACCELEROMETER

Major: Electronic and Communication

Supervisor: Assoc. Prof. Dr Tran Duc Tan

HA NOI - 2014

AUTHORSHIP
I hereby declare that the work contained in this thesis is of my own and has not been
previously submitted for a degree or diploma at this or any other higher education
institution. To the best of my knowledge and belief, the thesis contains no materials
previously published or written by another person except where due reference or
acknowledgement is made.

Signature:

SUPERVISORS APPROVAL
I hereby approve that the thesis in its current form is ready for committee examination
as a requirement for the Bachelor of Engineering and Technology degree at the
University of Engineering and Technology.

Signature:

ii

ACKNOWLEDGEMENT

First of all, I would like to express special thanks to Assoc. Prof. Tran Duc-Tan
who always guides me, points out the mistakes, and gives me the instructions and
comments during the time to realize this work. Without his supervising, I would
have many difficulties to finish this thesis.
Secondly, I want to give my sincerely thanks to the faculty members and staffs of
the Faculty of Electronics and Telecommunication, VNU-UET for their
enthusiasm to guide me to for the background of knowledge
I also greatly appreciate all members of the MEMS Lab who always facilitate me
to do this thesis, answer my questions in a familiar way and share their experience
for me as well as make me feel comfortable and better in studying
Finally, I want to give the best thank to my parents, my relatives and my friends
who always encourage, take care me during the studying and researching period.

Sincerely
Nguyen Van Tinh

iii

ABSTRACT

A simple fall can have devastating consequences for the elderly. If it happens, they
can become disoriented, immobilized, or knocked unconscious and unable to call
for help. This thesis aims to create a portable device to monitor the falls in older
adults by using a micro controller PIC18f4520, a 3-DOF acceleration sensor
ADXL345, a GSM/GPRS modem SIM900 and an embedded fall detection
algorithm. The human activities can be sensed by the 3-DOF accelerometer. The
acceleration signals are brought to the micro controller to monitor and alert the
fall. If the people fall, an alert message would be sent to their relative through the
GSM/GPRS modem. The experiment device has been tested carefully and it can
be applied to real application after the carefully evaluation and analyses.

Keywords: Fall, accelerometers, monitoring.

iv

Table of Contents

ACKNOWLEDGEMENT ........................................................................................... iii


ABSTRACT ..................................................................................................................iv
Table of Contents...........................................................................................................v
List of Figures ............................................................................................................. vii
List of Tables ................................................................................................................ix
ABBREVATIONS .........................................................................................................x
INTRODUCTION .........................................................................................................1
1.1 Motivation ............................................................................................................1
1.2 Relate Works .......................................................................................................2
1.3 Contribution and thesis overview ........................................................................4
MATERIAL AND THE METHOD ..............................................................................5
2.1 Hardware ..............................................................................................................7
2.1.1 MCU pic18f4520 ............................................................................................. 7
2.1.2 ADXL345 accelerometers sensor .....................................................................9
2.1.3 SIM900 module ............................................................................................. 11
2.2 Integrated System ............................................................................................... 13
2.2.1 Power module ................................................................................................ 14
2.2.2 MCU module ................................................................................................. 14
2.2.3 SIM900 module ............................................................................................. 14
2.2.4 Sensor ADXL345 .......................................................................................... 15
2.3 Software .............................................................................................................. 15
2.3.1 I2C interface .................................................................................................. 15
v

2.3.2 UART communication ................................................................................... 19


2.3.3 Timer ............................................................................................................. 20
2.4 Algorithms .......................................................................................................... 23
2.4.1 System architecture ........................................................................................ 23
2.4.2 Signal process ................................................................................................ 24
2.4.3 Posture recognition module ............................................................................ 26
2.4.4 Fall detection ................................................................................................. 27
2.4.5 Final decision................................................................................................. 28
2.4.6 Embedded program ........................................................................................ 37
RESULTS AND DISCUSSIONS ................................................................................ 40
Conclusions .................................................................................................................. 44
References .................................................................................................................... 45
Appendix A .................................................................................................................. 46

vi

List of Figures

Figure 1-1: Fall in elderly at home ...................................................................................2


Figure 2-1: Position of accelerometer in waist body .........................................................6
Figure 2-2: Module System..............................................................................................7
Figure 2-3: Pic 18f4520 microcontroller [13] ...................................................................7
Figure 2-4: Structure of pic18f4520 [13] . ........................................................................8
Figure 2-5: Sensor accelermeteter ADXL345...................................................................9
Figure 2-6: Block diagram of sensor ADXL345 [12] ..................................................... 10
Figure 2-7: Axes of Acceleration Sensitivity [12] . ........................................................ 10
Figure 2-8: Output response and orientation to gravity [12] . ......................................... 11
Figure 2-9: SIM900 module ........................................................................................... 11
Figure 2-10: Module proposed system ........................................................................... 13
Figure 2-11: System hardware of automatic falls detect ................................................. 13
Figure 2-12: I2C protocol between sensor ADXL345 and MCU [12] . ........................... 15
Figure 2-13: UART communication between MCU and SIM900 moudule .................... 19
Figure 2-14: Basic UART packet form: 1 start bit, 8 bits data, 1 parity and 1 stop bit [10]
...................................................................................................................................... 20
Figure 2-15: Interfacing microcontroller to PC via USB to UART Converter [10] ......... 20
Figure 2-16: System architecture [7] .............................................................................. 23
Figure 2-17: Walking before low-pass filter and average ............................................... 25
Figure 2-18: Walking after low-pass filter and average .................................................. 25

vii

Figure 2-19: Posture recognition module [7] . ............................................................... 26


Figure 2-20: Fall detection module [7] . ........................................................................ 27
Figure 2-21: Acceleration pattern during a fall [7] ........................................................ 28
Figure 2-22: Final decision of fall ................................................................................. 29
Figure 2-23: Ay component of Acceleration vector ........................................................ 31
Figure 2-24: Zero crossing rate ...................................................................................... 31
Figure 2-25: Standing .................................................................................................... 32
Figure 2-26: Walking ..................................................................................................... 33
Figure 2-27: Standing- Lying ......................................................................................... 33
Figure 2-28: Fall experiment 1 ....................................................................................... 34
Figure 2-29: Fall experiment 1 after time 7s................................................................... 35
Figure 2-30: Zoom out fall experiment 1........................................................................ 35
Figure 2-31: Fall experiment 2 ....................................................................................... 36
Figure 2-32: Fall experiment 2 after time 7s................................................................... 36
Figure 2-33: Zoom out fall experiment 2........................................................................ 37
Figure 2-34: Fall detect flowchar program ..................................................................... 38
Figure 3-1: Schematic of fall detection system ............................................................... 40
Figure 3-2: Automatic fall detect system ........................................................................ 41
Figure 3-3: The backface of SIM900 module ................................................................. 41
Figure 3-4: The frontface of SIM900 module ................................................................. 42
Figure 3-5: Integrated fall detection system ................................................................... 42
Figure 3-6: Automatic falls detect system in human ....................................................... 43

viii

List of Tables

Table 1: Final decision of fall ........................................................................................ 29


Table 2: Logic table ....................................................................................................... 30
Table 3: Values for difference states .............................................................................. 32

ix

ABBREVATIONS
DOF

Degree Of Freedom

ZCR

Zero Cross Rate

MCU

Microcontroller Unit

SMS

Short Message Service

GPRS

General Packet Radio Service

LCD

Liquid Crystal Display

I2C

Inter Integrated Circuit

UART

Universal Asynchronous Receiver/Transmitter

SPI

Serial Peripheral Interface

CCS

Cascading Style Sheet

Chapter 1

INTRODUCTION

1.1 Motivation
Every year in the world, approximately 28-35% of people aged of 65 and over
experience falls. The frequencies of falls are different between aged and appear to
vary in among countries as well. For example, every year by the research of in
South- East Asia Region found that in China 6-13%, another found that in Japan
20% of elderly fell. Meanwhile in Europe region 30% of people over 65 and 50%
of those over 80 years fell each year, the same research found that in Region of
American the proportion of older adults who fell each year ranging from 21.6% in
Barbados to 34% in Chile [1] [2] .
Experiencing a fall unobserved can be dangerous, highly probability of get serious
injury consequence or due to death if treatment is not providence in time. By the
research, the falls mortality rates account for 40% all of injury and the cost of fall
injury in older person reached for hundreds of millions of dollars [1] [3] .

Figure 1-1-1: Fall in elderly at home


Many elderly living alone either department, nursing home or a smaller house
after their children grown up and left home or go out to work, in case of older
people who taking a long - term to treatment in hospital without nurse around.
Usually, an elderly person unable to get up by himself or herself after falls.
Therefore we have built an automatic fall detect system device to send help to
other people like relative or nurse to help them in time [2] .

1.2 Relate Works


In modern society, health care for elderly has been concerned by many
organization and development countries, so there are many products have been
built in market to serve medical and health care services for elderly too.
There are many method used distinguish technical equipment to design a system
to detect falls system such as analysis human body posture recognition and
detection falls

use image processing, location sensors or accelerometers.

However, each of these methods has certain problems [4] .


2

Firstly, in the image processing approach, the disadvantage is how to installation


the camera in the room must work well, another insulation is limited functioning
in the outdoor environment and limited of resolution in camera, target occlusion.
One more the biggest issue is concern to user privacy. It is obvious that people
will not comfortable when camera recording them with activities in living at
home.
Secondly, in the location sensors approach, the problem is that there are so much
varies location sensors precision (not constant rate of distance error) in the market
with different kind of prices. For reasonable results, high precision is required in
our application; high precision means high in prices. The price is high many times
than accelerometer and similar with image processing location sensors is limited
in outdoor environment.
In the common way of formulating posture recognition and fall detection many
researcher use accelerometer with lower cost and it far more commercially
available in the market but still keep high result precision to detect fall in elderly.
With posture recognition module and fall detection module by applying threshold
to acceleration derived from 3-axis accelerometer sensor worn on the waist (
particular ADXL345, a 3-axis accelerometer from Analog Devices) they detected
a potential fall and the activity/posture after the fall, resulting in 100% accurate
posture recognition and detect falls with of 85% of accuracy [4] .

1.3 Contribution and thesis overview


The purpose of this thesis design completely automatic falls detects system for
elderly. Our system must operation in two functions: The first is automatic detect
truly fall in elderly when they live home alone or in the nurse house. Etc. The
second function is auto send SMS to relative contact to need help in time like their
child or the nurse...etc. to avoid the bad case happening. Our main of contribution
is analysis, simulation and improving an algorithm to posture recognition and
detect falls in elderly with build a database source in falls of Vietnamese people
and completely success design the falls detect system by applying this algorithm
working well in the real life.
The rest of this thesis is organized as follows:
Chapter 2 provides theoretical and algorithm background. At first is overview
about hardware components and these features, description our integrated system
how configuration from other components. Then we will going to detail the
software, about interface, protocols between MCU and other devices has used,
going deeply about our system architecture, signal processing, algorithm of
posture recognition and fall detection module and final decision to send SMS to
relative contracts of automatic falls detect system in elderly.
In chapter 3, we will show about products of our work and guide how to use our
system too. Also, show some the results from experiments of our algorithms were
simulated in MATLAB with explaining and evaluating respectively. The
conclusions and directions for future work are addressed in the final section.

Chapter 2

MATERIAL AND THE METHOD

In this section, we will describe brief about our method and schedule of function
working in our system.
The sensor used in this project was one 3-axis accelerometer, particular was
ADXL345 accelerometers manufacturing by Analog Devices Company. Our
accelerometer was positioned in the waist body so that y-axis must parallel with
Earths gravity. A 3-axis ADXL345 sensor is return in a real-valued estimate of
the acceleration along the x, y and z-axes from which velocity and orientation
angle can be estimated. Reading data from sensor with sample rate was 10Hz and
processing within buffer 10 data. By applying the threshold, posture recognition
module will show us whenever we standing, walking, lying or in null state. The
function of fall detection module is detecting the fall events base on threshold. . If
the system detects the falling event, by combination with posture period time
after event of fall, it automatically sends an SMS message through GSM/GPRS
modem SIM900 to the responsive contact.[7] .

Figure 2-1: Position of accelerometer in waist body

Here is our proposed system of automatic falls detect system in elderly, in which
accelerometer ADXL345 returns the value of acceleration in 3-axis. MCU is
center of processing and control within system, LCD 16x2 is display the values of
acceleration 3 axis x, y, z or signal control and function of SIM900 module is send
SMS message to relative contacts.

Figure 2-2: Module System

2.1 Hardware
2.1.1 MCU PIC18f4520

Figure 2-3: Pic 18f4520 microcontroller [13]


Pic 18f4520 is 8-bit microcontroller was developed by Microchip with some
features bellow
C Compiler Optimized Architecture:
- Optional extended instruction set designed to optimize re-entrant code
100,000 Erase/Write Cycle Enhanced Flash
7

Program Memory Typical


1,000,000 Erase/Write Cycle Data EEPROM
Memory Typical
Flash/Data EEPROM Retention: 100 Years Typical
Self-Programmable under Software Control
Priority Levels for Interrupts
8 x 8 Single-Cycle Hardware Multiplier
Extended Watchdog Timer (WDT):
- Programmable period from 4 ms to 131s
Single-Supply 5V In-Circuit Serial
Programming (ICSP) via Two Pins
In-Circuit Debug (ICD) via Two Pins
Wide Operating Voltage Range: 2.0V to 5.5V
Programmable Brown-out Reset (BOR) with
Software Enable Option

Bellowing is structure and schematic of Pic 18f4520

Figure 2-4: Structure of pic18f4520 [13] .


8

2.1.2 ADXL345 accelerometers sensor

Figure 2-5: Sensor accelermeteter ADXL345


The ADXL345 is a small, thin, low power, 3-axis accelerometer with highresolution (13-bit) measurement at up to 16 g. Digital output data is formatted as
16-bit twos complement and is accessible through either a SPI (3- or 4-wire) or
I2C digital interface
Highlight features:
- Ultralow power: as low as 40 A in measurement mode and 0.1 A in
standby mode at VS= 2.5 V (typical)
- Power consumption scales automatically with bandwidth
- User-selectable resolution. Fixed 10-bit resolution. Full resolution, where
resolution increases with grange, up to 13-bit resolution at 16 g
(maintaining 4 mg/LSB scale factor in all granges)
- Tap/double tap detection
- Activity/inactivity monitoring
- Free-fall detection
- Supply voltage range: 2.0 V to 3.6 V
- SPI (3- and 4-wire) and I2C digital interfaces
- Measurement ranges selectable via serial command
- Wide temperature range (40C to +85C)

Function block diagram of sensor ADXL345

Figure 2-6: Block diagram of sensor ADXL345 [12]


Gravitational acceleration at a point is constant. Here is output of accelerometers
in some position.

Figure 2-7: Axes of Acceleration Sensitivity [12] .


10

Figure 2-8: Output response and orientation to gravity [12] .


Application:
- Detect sock, falls, movement
- Measure the angle

2.1.3 SIM900 module

Figure 2-9: SIM900 module


11

The SIM900 GSM/GPRS Shield provides you a way to use the GSM cell phone
network to receive data from a remote location. The shield allows you to achieve
this via any of the three methods:
-

Short Message Service

Audio

GPRS Service

The GPRS Shield is compatible with all boards which have the same form factor
(and pin out) as a standard Adriano Board. The GPRS Shield is configured and
controlled via its UART using simple AT commands. Based on the SIM900
module from SIMCOM, the GPRS Shield is like a cell phone. Besides the
communications features, the GPRS Shield has 12 GPIOs, 2 PWMs and an ADC.
Highlight feature:
- Quad-Band 850 / 900/ 1800 / 1900 MHz - would work on GSM networks
in all countries across the world.
-

Control via AT commands - Standard Commands: GSM 07.07 & 07.05 |


Enhanced Commands: SIMCOM AT Commands.
Short Message Service - so that you can send small amounts of data over
the network (ASCII or raw hexadecimal).
SIM Card holder and GSM Antenna - present onboard.
Low power consumption - 1.5mA(sleep mode)
Industrial Temperature Range - -40C to +85 C

12

2.2 Integrated System

Figure 2-10: Module proposed system


Here is schematic of our proposed system has been designed in Altium software:

Figure 2-11: System hardware of automatic falls detect


13

2.2.1 Power module


In automatic fall detect system. There are two level power sources, one for MCU
and sensor accelerometer ADXL345 and other for module SIM900. With module
SIM900, it only works when the current is larger than 2A. Consequently, we have
been using an adapter 12V, 3A with LM2576 to get +5V, 2A. Power for MCU and
sensor is +5V voltage, so one branch from the adapter with LM7805 voltage
regulator we will receive it.
2.2.2 MCU module
The Microcontroller 18f4520 has been being used and clock source frequency
(Crystal) is 20 MHz, which fast enough to execute fall, detect program.
2.2.3 SIM900 module
In SIM900 module, these pins here has been using:
Power on or down: PWRKEY should be pulled down at least 1 second and then
released power on/down the module
Status:

SIM interface:

STATUS

Power on the status

NETLIGHT

Network status

SIM_VDD

Voltage supply for SIM card +3V

SIM_DATA

SIM_DAT input/output

SIM_CLK

SIM clock

SIM_RST

SIM reset

Serial port: RXD and TXD for UART communication between MCU and
SIM900 module

14

2.2.4 Sensor ADXL345


By using interface I2C between MCU and sensor. There are 4 pins has used: Vcc,
ground, SCL and SDA, Vcc for +5 voltages, SCL is the clock line, SDA is the data
line.
2.3 Software
2.3.1 I2C interface

Figure 2-12: I2C protocol between sensor ADXL345 and MCU [12] .
The physical I2C bus
This is just two wires, called SCL and SDA. SCL is the clock line. It is used to
synchronize all data transfers over the I2C bus. SDA is the data line. The SCL &
SDA lines are connected to all devices on the I2C bus. There needs to be a third
wire, which is just the ground or 0 volts. There may also be a 5volt wire is power
is being distributed to the devices. Both SCL and SDA lines are "open drain"
drivers. What this means is that the chip can drive its output low, but it cannot
drive it high. For the line to be able to go high, you must provide pull-up resistors
to the 5v supply. There should be a resistor from the SCL line to the 5v line and
another from the SDA line to the 5v line. You only need one set of pull-up
resistors for the whole I2C bus, not for each device, as illustrated below [11] :

15

Masters and Slaves


The devices on the I2C bus are either masters or slaves. The master is always the
device that drives the SCL clock line. The slaves are the devices that respond to
the master. A slave cannot initiate a transfer over the I2C bus, only a master can
do that. There can be, and usually are, multiple slaves on the I2C bus, however
there is normally only one master. It is possible to have multiple masters, but it is
unusual and not covered here. On our application, the master will be pic 18f4520
micro controller and the slaves will be three-axis accelerometer ADXL345 sensor.
Slaves will never initiate a transfer. Both master and slave can transfer data over
the I2C bus, but that transfer is always controlled by the master [11] .
The I2C Physical Protocol
When the master pic 18f4520 micro controller wishes to talk to a slave (our
ADXL345 sensor for example), it begins by issuing a start sequence on the I2C
bus [1]. A start sequence is one of two special sequences defined for the I2C bus,
the other being the stop sequence. The start sequence and stop sequence are
special in that these are the only places where the SDA (data line) is allowed to
change while the SCL (clock line) is high. When data is being transferred, SDA
must remain stable and not change whilst SCL is high. The start and stop
sequences mark the beginning and end of a transaction with the slave device [11] .

16

Data is transferred in sequences of 8 bits. The bits are placed on the SDA line
starting with the MSB (Most Significant Bit). The SCL line is then pulsed high,
then low. Remember that the chip cannot really drive the line high, it simply "lets
go" of it and the resistor actually pulls it high. For every 8 bits transferred, the
device receiving the data sends back an acknowledge bit, so there are actually 9
SCL clock pulses to transfer each 8 bit byte of data. If the receiving device sends
back a low ACK bit, then it has received the data and is ready to accept another
byte. If it sends back a high then it is indicating it cannot accept any further data
and the master should terminate the transfer by sending a stop sequence [11] .

Clock
The standard clock (SCL) speed for I2C up to 100KHz. Philips do define faster
speeds: Fast mode, which is up to 400KHz and High Speed mode which is up to
3.4MHz [11] .
I2C Device Addressing
All I2C addresses are either 7 bits or 10 bits. All of our modules and the common
chips you will use will have 7-bit addresses. This means that you can have up to
128 devices on the I2C bus, since a 7-bit number can be from 0 to 127. When
sending out the 7-bit address, we still always send 8 bits. The extra bit is used to
inform the slave if the master is writing to it or reading from it. If the bit is zero
the master is writing to the slave. If the bit is 1 the master is reading from the
slave. The 7-bit address is placed in the upper 7 bits of the byte and the
17

Read/Write (R/W) bit is in the LSB (Least Significant Bit). The address of slave
ADXL345 is 0x53 [11] .

The I2C Software Protocol


The first thing that will happen is that the master will send out a start sequence.
This will alert all the slave devices on the bus that a transaction is starting and they
should listen in incase it is for them. Next, the master will send out the device
address. The slave that matches this address will continue with the transaction, any
others will ignore the rest of this transaction and wait for the next. Having
addressed the slave device the master must now send out the internal location or
register number inside the slave that it wishes to write to or read from [11] .
Writing to the Slave
-

Send a start sequence


Send the I2C address of the slave with the R/W bit low (even address)
Send the internal register number you want to write to
Send the data byte
[Optionally, send any further data bytes]
Send the stop sequence.

Reading from the Slave


Before reading data from the slave device, you must tell it which of its internal
addresses you want to read. So a read of the slave actually starts off by writing to
it. This is the same as when you want to write to it: You send the start sequence,
18

the I2C address of the slave with the R/W bit low (even address) and the internal
register number you want to write to. Now you send another start sequence
(sometimes called a restart) and the I2C address again - this time with the read bit
set. You then read as many data bytes as you wish and terminate the transaction
with a stop sequence [11] .
-

Send a start sequence


Send 0x53 (I2C address of the ADXL345)
Send address (Internal address of the bearing register)
Send a start sequence again (repeated start)
Send 0xC1 (I2C address of the ADXL345 with the R/W bit high (odd
address)
- Read data byte from ADXL345
- Send the stop sequence.
2.3.2 UART communication
The Universal Asynchronous Receiver/Transmitter (UART) controller is the key
component of the serial communications subsystem of a computer. UART is also a
common integrated feature in most microcontrollers. 3 pins we must care are Tx
(transmitter), Rx (Receiver) and Ground [12] .

Figure 2-13: UART communication between MCU and SIM900 moudule


The Asynchronous Receiving and Transmitting Protocol
The asynchronous communication it mean that both transmitter and receiving
works in different clocks but must not exceed 10%. Start and stop bits are also sent
with each data byte to identify the data.
19

In this case, the sender and receiver must agree on timing parameters (Baud Rate)
prior transmission and special bits are added to each word to synchronize the
sending and receiving units [10] .

Figure 2-14: Basic UART packet form: 1 start bit, 8 bits data, 1 parity and 1
stop bit [10]
Every operation of the UART hardware is controlled by a clock signal, which runs
at much faster rate than the baud rate. Transmitting and receiving UARTs must be
set at the same baud rate, character length, parity, and stop bits for proper
operation. The typical format for serial ports used with PC connected to modems
is 1 Start bit, 8 data bits, no Parity and 1 Stop bit.
UART is the simplest form of communication between microcontroller and PC.
However, due to the mushrooming growth of technology, serial port is slowly
being replaced by other means of communication port such as USB to RS-232
[10] .

Figure 2-15: Interfacing microcontroller to PC via USB to UART Converter


[10]

2.3.3 Timer
Timer as the name suggests pertain to time-related operations. They are mostly
used for exact delay generation. Timers are also used in various other operations
like PWM signal generation, auto-triggering of several other peripherals. In our
project, we used timer0 for calculating data sample rate and timer1 for calculating
exactly time to detect falls.

20

Each of the four timers of Pic f84520 has certain special features some of which
are explained below. The detailed list of these features can be obtained from
PIC18f4520 datasheet.

Timer0
-

Timer0 can work as Timer/Counter in both 8-bit and 16-bit modes


Dedicated 8-bit, software programmable prescaler
Selectable clock source (internal or external)
Interrupt on overflow

Timer1
-

Timer1 can work as 16-bit timer or counter


Readable and writable 8-bit registers (TMR1H and TMR1L)
Selectable clock source (internal or external)
Alternate clock source can be provided at Timer1 oscillator pins (T1OSO
& T1OSI)
- Interrupt on overflow
- Timer1 can be multiplexed with other peripherals like ADC etc. and
generates special event triggering for CCP (Capture, Compare and PWM)
events.
Timer2
-

8-bit Timer and Period registers (TMR2 and PR2, respectively)


Software programmable prescaler (1:1, 1:4 and 1:16)
Software programmable postscaler (1:1 - 1:16)
Interrupt on TMR2 to PR2 match
Optional use as the shift clock for the MSSP (Master Synchronous Serial
Port) module

Timer3
-

Timer3 can work as 16-bit timer or counter


Readable and writable 8-bit registers (TMR3H and TMR3L)
Selectable clock source (internal or external)
Alternate clock source can be provided at Timer1 oscillator pins (T1OSO
& T1OSI)
21

Interrupt on overflow
Timer3 can be multiplexed with other peripherals like ADC etc. and
generates special event triggering for CCP (Capture, Compare and PWM)
events.

Here is some formula how to calculate timer in MCU

Ftimer FOSC / (4*Pr escaler )

Ttimer 1/ Ftimer
Where FOSC is Clock source frequency (Crystal). Prescaler is integer number takes
the basic timer clock frequency (power of 2 from 0 -

2nbit )

This means that when Timer runs, it will take Ttimer sec to increment its value at
every count.

22

2.4 Algorithms
2.4.1 System architecture
The posture recognition and fall detection process describe in this project is
divided to several phases such as show in Figure 17.
The first is in the real world in which sensor accelerometers ADXL345 is
positioned in waist body region. The next phase is sensory part, after sampled rate
with 10Hz; the data received from the accelerometer was in the form of a threevalued vector of floating point numbers that represented the individual
accelerations of sensor ADXL345 in the x, y, z-axes subtracted by the gravity
vector G. The acceleration values was recorded in meters per second squared (

m
2
s

).Thus, lay flat on a level surface, the expected reading of the accelerometer would
be approximately [0.0, 9.81]. In this phase we has signal process step before data
get into attribute extraction module to formulated mean, orientation, standard
deviation. The last final phase is data mining body posture recognition and fall
detection. Each of these modules gives an output: the real time posture of body
and fall or not fall events [4] [7] [9] .

Figure 2-16: System architecture [7]


23

2.4.2 Signal process


- Converting
The process of obtaining and converting the accelerometer reading depends on the
accelerometer you are using, in our case, the ADXl345 in its basic configuration,
provides 10-bit resolution for 2g , but has several other ranges (
2 g , 4 g , 8 g , 16 g ) and the resolutions (from 10bit to 13bit depending on the
range). The formula used to calculate the acceleration from the accelerometer
reading is:

Data _ outg ( Data _ outresolution * Scaleresolution ) /1000


From ADXL345 datasheet 10-bit, 2g we has scale is 3.9 respectively.
- Filter
After that, we used the Low - Pass filter to removing short-term fluctuation. This
type of filter attenuates the higher frequencies of the signal, thus providing a
smoother reading. The Low-Pass filter is easily implemented by using the
following equation.

yt .xt (1 ). yt 1
Where yt is our filtered signal, yt 1 is the previous filtered signal, xt the
accelerometer reading and the smoothing factor.
- Average
Next process step, we accumulated the output data, and then took average over
buffer 10 for making data more accuracy.
- Offset
Finally, we took offset of output average data. Consequently gravitational
acceleration response in some position satisfied with real life.

Data _ out g Data _ out g Voffset

24

The comparison of walking state is show before and after low-pass filter and
average.
18
An
16
Null
14

Lying

L2 gia toc

12

10

Standing

Walking

10

20

30
Thoi gian - s

40

50

60

Figure 2-17: Walking before low-pass filter and average

18
An
16
Null
14

Lying

L2 gia toc

12

10

Standing

Walking

10

20

30
Thoi gian - s

40

50

Figure 2-18: Walking after low-pass filter and average


25

60

2.4.3 Posture recognition module


Here is algorithm for detect posture recognition [7] .

Figure 2-19: Posture recognition module [7] .


In which th1, th2 are the thresholds, to detected th1, th2 we has did many
experiments with data got from our sensor ADXL345 to obtained these values
such that posture simulation in MATLAB satisfying with posture in the
experiment real life. After completely processing in this module, we will get four
states of posture: lying, standing, walking, and null.

26

2.4.4 Fall detection


Here is algorithm for fall detection [7] . The same with posture recognition, th4 is
the threshold, to detected

th4 we also has did many experiments with falls

respectively, with requirement result simulation in MATLAB has the same with
the experiments.

Figure 2-20: Fall detection module [7] .


The fall detection module searches for particular pattern in the signal. Figure 20
represents a pattern An (compute from ax, ay, az) norm during fall event.

27

Figure 2-21: Acceleration pattern during a fall [7] .


If the difference between consecutive minima and maxima is greater than the Th4,
The output decided it as a fall.

2.4.5 Final decision


The final decision on event of a fall is based on both output of posture recognition,
fall detects, and requirement with the time after fall. When a fall is detected,
decision from posture recognition module in this time and after period (here we
choose period of time 7 second) tells us whether it is a fall alarm. Why we
consider posture recognition after time 7 second because some people can stand up
by themselves after fall so we must check it to confirm truly fall or not. Table 1
summarizes the final decision [7].

28

Flowchart of algorithm:

Figure 2-22: Final decision of fall

Fall detection

Posture recognition

Posture after 7s of

Final

Fall

decision

Fall

Standing

Dont care

False

Fall

Walking

Dont care

False

Fall

Lying

Dont care

False

Standing or Walking

False

Lying or Null

True

Standing or Walking

False

Lying or Null

True

Fall

Fall

Lying

Null

Table 1: Final decision of fall

29

Here is locgic table was standardized.


State

Posture
reocognition

Fall detection

Posture after
7s of fall

Final decision

A*B*C

Standing

Walking

Lying

Null

Table 2: Logic table


x: dont care

Looking at the table, if fall detection event occur, if state of posture recognition in
this time is still walking, standing the fall decision final will be discarded. In the
same with another case if posture in the time of fall is lying or null, but after 7
second, the posture is standing or walking, final decision is false too.
Analysis of the algorithms
The data from accelerometer ADXL345 is stored in buffer of suitable length,
mention again, in our case it is fixed as 10 samples, as the sampling rate is fixed as
10 Hz, then we will take average over the buffer length, the purpose of this to get
data that are more accurate. Lowering or high the window size, will affect the
decision of posture recognition. The reason behind that the, the zero crossing rate
requires a constant oscillation for particular the amount of time to figure out the
between states of walking and momentary jitter (no state) [7].

30

Figure 2-23: Ay component of Acceleration vector


The transitions and slight variations are regarded as null state. To characterize a
state between null and walking, lying and standing to thresholds are used on the
zero crossing rate.

Figure 2-24: Zero crossing rate


The trend has greater than Th1 to be confirming as walking. Any else the
variations are discarded. Th2 marks the lower threshold based on which slight
variations are removed in the start of the algorithm. The necessary of lower Th2
threshold is the transition state lower than Th2 will be confirm null state [7].
31

Table 2 gives what the values of Posture recognition module means.


State
Walking
Standing
Lying
Null

Value
2
4
10
15

Table 3: Values for difference states


By doing many experiments, analysis and simulation in MATLAB, finally we
have choose the suitable value of these thresholds and window size to work in our
hardware.
Window Size = 10
Th1= 0.7
Th2 = 4.0
Th4: 1.3 (m/s^2)
Here is some imagine of experiment of our works was simulated in MATLAB

Figure 2-25: Standing


32

Figure 2-26: Walking

Figure 2-27: Standing- Lying


33

State transition of people in experiments:


Standing ->Walking-> Standing->Lying->Standing->Walking->Fall->Standing

Figure 2-28: Fall experiment 1


From the above figure, we can see that in the 13 and 120 second there is event of
falls. In the 13 second, posture recognition module detect null state (respective
with 15 value) and fall detection module show us one event of shock (over the
threshold mark by red color ) and in 120 second the state is lying and one event of
shock, so it must has two alarm for falls. However, it not true because our
experiment has only one falls in 120 second, while in 13 second we were walking.
Therefore, by checking the state after 7 second of falls we can discard it. The final
decision was showing in Figure 2-26 and zoom - out in Figure 2-27.

34

Figure 2-29: Fall experiment 1 after time 7s

Figure 2-30: Zoom out fall experiment 1

35

By do one more experiment in Figure 2-28, we got the correct detect of fall in
final decision in nearly 60 second.

Figure 2-31: Fall experiment 2

Figure 2-32: Fall experiment 2 after time 7s


36

Figure 2-33: Zoom out fall experiment 2

2.4.6 Embedded program


In this section, we will describe how to implement our program in hardware of
automatic fall detection system.
Here is flowchart of fall detection program.

37

Figure 2-34: Fall detect flowchar program


Firstly, we want to explain why choose the sample rate data is 10Hz, frequency
10Hz it mean 1 second we will take 10 data, by the way i can calculate amount of
time to take 1 data is approximately 100ms. While our code running time of fall
detection program around 53.3ms by using timer. Therefore, data will be not
missing and our program will execute stability as well.
So the important note to let our program working well.

Fdatasamplerate

1
Tcoderunning time
38

Where

Fdatasamplerate is

data sampling rate.

Tcode running time

is code running

time of fall detection program .


Fall detection program executed gradually in bellow:
In the first is initialize step. Sensor ADXL345, LCD 16x2, interrupt like Timer0,
Timer1, UART would be setup. Timer0 was set to determine the data sampling
rate frequency, timer1 was set to count the time 7s after fall had detected. Interrupt
UART was set in highest priority to temporary stopping main program and went to
interrupt service to send SMS message when truly fall occurred.
In the rest part is where posture recognition and fall detection module. Posture
recognition will tell us the posture of elderly in this time: Standing, walking, lying
or null state and fall detection will point out fall event occurred, If fall detection
module has an event of fall. Final decision is sending SMS message to relative
contact if after period of 7 second the posture of people is lying or null.

39

Chapter 3

RESULTS AND DISCUSSIONS

Imagine of system

Figure 3-1: Schematic of fall detection system

40

Figure 3-2: Automatic fall detect system

Figure 3-3: The backface of SIM900 module

41

Figure 3-4: The frontface of SIM900 module


Integrated system in waist body region:

Figure 3-5: Integrated fall detection system


42

Figure 3-6: Automatic falls detect system in human


Result and discussion
After done with this thesis, we have gotten many nice things:
-

Completely one version of automatic falls detect system: Hardware,


software with low cost (about 40$) and consuming fewer resources but we
were able to achieve detection of 85% accuracy in detecting of falls.
Simple fall detect algorithms, improved base one already algorithms
Designed with response of hardware capabilities: Memories, performance.
We have been building a database of falling in Vietnamese people.
Our system can be expanded with others heath care systems such as
pressure monitoring, oxygen monitor.

43

Conclusions
The fall monitoring system is still a new application in Vietnam and it has good
potential to develop and commercialize. During the period I follow this research
direction, I have study some posture recognition and fall detection algorithms.
After that, I have proposed an improvement in algorithms in order to enhance the
device's performance. Firstly, the algorithms have been simulated in MATLAB
environment. After that, it can be re-programmed in C language which is suitable
with the micro controller. I have also learned how to design and develop a real
device and how to program it. For the hardware part, I has learned how to work
with the accelerometer ADXL345, process the data and filter noise from it; I also
study about: 1) I2C to communicate between sensor and the microcontroller, 2)
UART to communicate between the microcontroller with the GSM/GPRS modem
SIM900 in order to send message to relative, 3) timers in the micro controller. I
also have built a database of postures and falls. The experiment device has been
tested carefully. In lab experiment, the device can offer to an accuracy of 85%. It
can be applied to real application after further evaluation and analyses.

44

References

[1] Marilyn Langfeld, Adina Murch,Ann Feild. WHo Global report on falls
Prevention in older Age. France: World Health Organization, 2007.
[2] Fact sheet: Prevention of Falls among Elderly. Athens-GREECE: Center for
Research and Prevention of Injuries-CEREPRI Department of Hygiene &
Epidemiology, 2012.
[3] Report of Cost of Falls Injury in Older Persons in United States. Atlanta:
Center for Disease Control and Prevention National Center for for Injury
Prevention and Control (NCIPC), http://www.cdc.gov, 2013.
[4] Hristijan Gjoreski, Mitja Lutrek, Matja Gams. "Accelerometer Placement for
Posture Recognition and Fall Detection." Intelligent Environments (IE),
2011 7th International Conference on. Nottingham: IEEE, 25-28 July 2011.
[5] Petar Mostarac, Roman Malari, Marko Jurevi, Hrvoje Hegedu, Aim LayEkuakille, Patrizia Vergallo. "System for monitoring and fall detection of
patients using mobile 3-axis accelerometers sensors." Medical
Measurements and Applications Proceedings (MeMeA). Bari: IEEE, 30-31
May 2011.
[6] NingJia. "Detecting Human Falls with a 3-Axis Digital Accelerometer." July
2009. http://www.analog.com/.
[7] BharadwajS. Fall Detection with Posture recognition on Android Smart
phone. December 2012. https://github.com.
[8] Jonathan Tomkun, Binh Nguyen. "Design of a F all Detection and Prevention
System for the Elderly." Electrical and Biomedical Engineering Design
Project, Ontario, Canada, 2010.
[9] Sauvik Das, LaToya Green, Beatrice Perez, Michael Murphy. "Detecting User
Activities using the Accelerometer on Android Smartphones." 30 July ,
2010. https://www.truststc.org.
[10] WWKong. UART Universal Asynchronous Receiver and Transmitter.
December 2010. http://tutorial.cytron.com.
[11] Gerry. Using the I2C Bus. n.d. http://www.robot-electronics.co.uk/.
[12] Analog Devices. "3-Axis, 2 g/4 g/8 g/16 g Digital Accelerometer." n.d.
http://www.analog.com/.
[13] Microchip Technology Incorporated. "PIC18F2420/2520/4420/4520 Data
Sheet." 2004. http://www.microchip.com/.

45

Appendix A
/* Name : Nguyen van Tinh K55D
Title: Fall_detection of elderly people
- Reading and data process from adxl345
- use timer0 to determine time sampling data
- use timer1 to determine time is real fall occur(>=7s)
- use period interupt uart to send SMS
- Apply algorithm fall include:
- Posture recognition
- falldetection
- Final decision
- send SMS through GSM Sim900
*/
#include <18f4520.h>
// MCU
#device HIGH_INTS = TRUE
// To use priority interrupt of Timer1
#include <MATH.H>
//============================== Initialize system step ============================//
#use delay (clock=20000000)
// Clock Crystal 20 Mhz
#use rs232 (baud=9600, xmit=PIN_C6, rcv=PIN_C7) // UART communication
#use i2c (Master,sda=PIN_C0, scl=PIN_C1)
// I2C interface
#fuses HS, NOPROTECT, BROWNOUT, PUT, NOLVP // Setup the complier
#include <lcd_lib_4bit.c>
// LCD 16x2 library
#define DEVICE1 (0x53)
// Address of ADXL345 sensor
#include <stdio.h>
#include <stdlib.h>
//========================== Define ADXL345 register address =======================//
#define BW_RATE
44
#define POWER_CTL
45
#define DATA_FORMAT
49
#define DATAX0
50
#define DATAX1
51
#define DATAY0
52
#define DATAY1
53
#define DATAZ0
54
#define DATAZ1
55
#define FIFO_CTL
56
//======================== Define variable and Threshold value =======================//
const int FiFo = 10 ;
// window size
const float th = 10 ;
// to remove dc Th
const float th1 = 0.7;
// threshold to check walking or null
const int th2 = 4.0 ;
// threshold to check lying or standing
const float sigma = 0.15 ;
// remove jiter
const float value = 1.3;
// threshold compare to detect fall Th4
int id, power;
signed int16 aXout[FiFo] ;
// FiFo buffer array
signed int16 aYout[FiFo] ;
signed int16 aZout[FiFo] ;
signed int16 Acce_OutputX = 0 ;
// Output 3-axis ADXL345 variable
signed int16 Acce_OutputY = 0 ;
signed int16 Acce_OutputZ = 0 ;

46

float aXoutAverage = 0 ;
float aYoutAverage = 0 ;
float aZoutAverage = 0 ;
float gx = 0 ;
float gy = 0 ;
float gz = 0 ;
float g = 0 ;

// Averages variable

// An norm aceleration

/* Timer0 variable to sample data */


int flag0 = 0,dem0 =0;
int flag1 = 0,dem1 = 0 ;

// Timer0 variable-> Data sample rate


// Timer1 variable-> Counter time after fall

// Aceleration sensor variable in m/s^2

/* variable to data processing */


float a_vec[FiFo];
// store a_vec
float sig[FiFo];
// array store norm acceleration
int decision_signal[FiFo] = {0,0,0,0,0,0,0,0,0,0};
int zrc[FiFo] = {0,0,0,0,0,0,0,0,0,0};
// array for algorithm process
int fall_decisionsignal[FiFo] = {0,0,0,0,0,0,0,0,0,0};
void write(int device, byte address, byte val);
byte read(int device, byte address) ;
void timer0_ini(void);
void interrupt_timer0_isr(void);
void timer1_ini(void);
void interrupt_timer1_isr(void);

// function for write in I2C interface


// function for read in I2C interface
// function for initialize Timer0
// function interrupt service Timer0
// function for initialize Timer1
// function interrupt service Timer1

// ---------------------------------------------variable and function for sim 900-------------- -----------------------//


char c=0x00,c1=0x00,c2=0x00,c3=0x00,c4=0x00,c5 =0x00,c6=0x00; // variable to check interrupt UART
int8 new_sms = 0;
void ngat();
// function interrupt UART
void reset();
// reset SIM900
void at_command();
// function check AT-COMMAND
void send_sms();
// function send SMS
//---------------------------------=----------------- initialize ADXL345-------------------------------------------------//
void ini_adxl345(void)
{
write(DEVICE1,FIFO_CTL,0x9f);
write(DEVICE1,DATA_FORMAT,0x00);
// 0x00001001 +-2g 10 bit
write(DEVICE1,BW_RATE,0x0d);
// baud rate 400hz I2C interface
delay_us(10);
write(DEVICE1,POWER_CTL,0x2D);
delay_us(10);
write(DEVICE1,POWER_CTL,0x08);
}
//============================== Main Program =================================//
void main()
{
int i,w,count = 0,vitringa;
// variable to algorithm process
float diff[FiFo],minmax_attr ;
int tmin , tmax;
int flag = 0;
set_tris_d(0x00);
// intialize MCU pin
set_tris_a(0xff);
SET_TRIS_B(0x00);

47

enable_interrupts(GLOBAL);
enable_interrupts(INT_RDA);
timer0_ini();
ini_adxl345();
reset();
at_command();
reset();
for (i=0 ;i <= FiFo-1; i++ )
{
aXout[i] = 0 ;
aYout[i] = 0 ;
aZout[i] = 0 ;
}
while(true)
{

// enable interrupt in GLOBAL


// enable interrupt UART
// initialize Timer0
// initialize ADXL345
// initialize SIM900

// initial FiFO Buffers

// loop

if(flag0 == 1)
// if interrupt Timer0 occur
{
flag0 = 0;
output_low(PIN_B1);
id= read(0x53,0x00);
power=read(0x53,0x2D);
//------------------------------------------ receive value from ADXL345---------------------------------------- //
Acce_OutputX = (read(DEVICE1,DATAX1)*256) | (read(DEVICE1,DATAX0));
Acce_OutputY = (read(DEVICE1,DATAY1)*256) | (read(DEVICE1,DATAY0));
Acce_OutputZ = (read(DEVICE1,DATAZ1)*256) | (read(DEVICE1,DATAZ0));
//-------------------------------- Queue of data before signal process------------------------------------------- //
for(i= 0 ; i <= FiFo-2;i++ )
{
aXout[i] = aXout[i+1];
aYout[i] = aYout[i+1];
aZout[i] = aZout[i+1];
}
aXout[FiFo-1] = Acce_OutputX ;
aYout[FiFo-1] = Acce_OutputY ;
aZout[FiFo-1] = Acce_OutputZ ;
//------------------------------------------------ Average the data -------------------------------------------------//
for(i=0 ; i <= FiFo-1 ; i++ )
{
aXoutAverage = aXoutAverage + (float)aXout[i];
aYoutAverage = aYoutAverage + (float)aYout[i];
aZoutAverage = aZoutAverage + (float)aZout[i];
}
aXoutAverage = aXoutAverage / ( float )FiFo ;
aYoutAverage = aYoutAverage / ( float )FiFo ;
aZoutAverage = aZoutAverage / ( float )FiFo ;
//---------------------------------------------------- Convert to m/s^2 and Offset ------------------------------- //
gx = aXoutAverage*3.9/1000;
// +-2g SCALE = 3.9 mg/LSB (g unit)
gy = aYoutAverage*3.9/1000;
gz = aZoutAverage*3.9/1000;
gx = gx*9.81 - 0.5 ;// V0ff set V = V(d0) - [V(+)-V(-)/2]
gy = gy*9.81 - 0.5 ;
gz = gz*9.81 - 0.5 ;

48

g = sqrt(gx*gx + gy*gy + gz*gz);


// calculate the norm value
//------------------------------------------- Queue of data afer signal process---------------------------------- //
for(i= 0 ; i <= FiFo-2 ; i++ )
{
a_vec[i]= a_vec[i+1];
sig[i] = sig[i+1];
}
a_vec[FiFo-1]= g;
// assignment to processing
sig[FiFo-1] = gy;
//========================= Posture recognition module ======================== //
for(i = 0; i <=FiFo-1; i++)
{
a_vec[i] = a_vec[i] - th;
}
for(w = 0; w <= FiFo-1; w++)
{
for(i= w + 1; i<= FiFo-1; i++)
{
if(a_vec[i] < sigma && a_vec[i-1] > sigma)
count = count + 1;
}
zrc[w] = count;
count = 0;
}
for(i = 0; i <=FiFo-1; i++)
{
if(zrc[i] == 0)
{
if(abs(sig[i]) < Th2)
decision_signal[i] = 10; // lying
else
decision_signal[i] = 5; // standing
}
else
{
if(zrc[i] > th1)
{
decision_signal[i] = 2; // walking
}
else
decision_signal[i] = 15; // none
}
}
//=========================== Fall detection module ===========================//
for(i = 0; i < FiFo; i++)
{
a_vec[i] = a_vec[i] + th;
}
tmin = 1;
tmax = 1;
diff[0] = 0;
for(i = 0; i <= FiFo -1 ; i++)

49

{
diff[i+1]= a_vec[i+1] - a_vec[i];
}
i = 2;
while((i<FiFo-1)&&(flag != 2))
{
if(diff[i] < 0 && diff[i+1] > 0 && flag ==1)
{
tmin = i ;
flag = flag + 1;
}
else if (diff[i] > 0 && diff[i+1] < 0&& flag ==0)
{
tmax = i;
flag = flag +1;
}
i++;
}
minmax_attr = a_vec[tmax]-a_vec[tmin];
if(minmax_attr < value || tmax < tmin)
{
tmin = 0;
tmax = 0;
}
if(tmin != tmax)
{
for(i = tmin ;i < tmax;i++)
{
fall_decisionsignal[i] = 1 ;
}
}
tmin = 1;
tmax = 1;
flag = 0;
//============================ Final Fall decision =============================//
for(i = 0;i <= FiFo-1;i++)
{
if((decision_signal[i] == 10 && fall_decisionsignal[i] == 1) || (decision_signal[i] == 15 &&
fall_decisionsignal[i] == 1))
{
vitringa = i ;
timer1_ini();
enable_interrupts(INT_TIMER1);
break;
}
}
//======================== Check posture after 7s to decide send SMS ================//
if(flag1 == 1) // // lying > 7s -> Send SMS
{
dem1 = 0;
flag1 =0;
DISABLE_INTERRUPTS(INT_TIMER1);
if( decision_signal[vitringa] == 10 ||decision_signal[vitringa] == 15 )

50

{
dem1 = 0;
output_high(PIN_B1);
delay_ms(1000);
send_sms();
output_low(PIN_B1);
DISABLE_INTERRUPTS(INT_TIMER1);
}
}
//====================== Detele variable, array for next process ==================== //
aXoutAverage = 0 ;
aYoutAverage = 0 ;
aZoutAverage = 0 ;
for(i = 0 ; i <= FiFo-1 ;i++)
{
decision_signal[i] = 0;
zrc[i] = 0;
fall_decisionsignal[i] = 0;
}
}
}
}
//=================================End of main ================================//
//=============================== Function write in I2C ===========================//
void write(int device, byte address, byte val)
{
i2c_start();
i2c_write(device<<1);
i2c_write(address);
i2c_write(val);
i2c_stop();
}
//=========================== Function read in I2C ===============================//
byte read(int device, byte address)
{
int value;
i2c_start();
i2c_write(device<<1);
i2c_write(address);
i2c_start();
i2c_write(device<<1|0x01);
value=i2c_read(0);
i2c_stop();
return value;
}
// ================================= Timer0 initialize ============================//
void timer0_ini(void)
{
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256|RTCC_8_BIT); // T_tm0=T_osc*4*256
set_timer0(0); // counter from 0
enable_interrupts(INT_TIMER0);

51

}
// ================================= Timer1 initialize ============================//
void timer1_ini(void)
{
setup_timer_1 ( T1_INTERNAL | T1_DIV_BY_8 );
set_timer1(0);
dem1 =0;
}
// ================================ Timer0 interrupt service ========================//
#INT_TIMER0
void interrupt_timer0_isr(void)
{
clear_interrupt(int_timer0);
set_timer0(0); // counter from 0
dem0++;
if(dem0 == 10 ) // f = 8hz
{
flag0 = 1;
dem0 = 0;
}
}
// ================================= Timer1 interrupt service =====================//
#INT_TIMER1
void interrupt_timer1_isr(void)
{
clear_interrupt(int_timer1);
set_timer1(0);
dem1++;
if(dem1 ==80)
{
flag1 = 1;
dem1 =0 ;
}
}
// ========================== Function check interrupt in UART ======================//
#INT_RDA FAST // period interrupt
void ngat()
{
c=getc();
if(c=='\r') c1=c;
if(c=='\n') c2=c;
if(c=='O') c3=c;
if(c=='K') c4=c;
if(c=='\r') c5=c;
if(c =='\n')c6=c;
if(c1=='\r' && c2=='\n' && c3=='O' && c4=='K'&& c5 =='\r'&& c6=='\n') new_sms=1;
}
// =========================== Function to reset SIM900 ===========================//
void reset(void)
{
int i ;
new_sms =0;

52

c1 = 0x00;
c2 = 0x00;
c3 = 0x00;
c4 = 0x00;
c5 = 0x00;
c6 = 0x00;
}
// ========================= Function check AT- Command =========================//
void at_command(void)
{
int8 j = 0;
j=0;
while(j++)
{
printf("AT\n\r");
// wait for interrupt
if(new_sms ==1)
{
new_sms = 0;
printf("AT-OK");
delay_ms(100);
break;
}
}
}
// ============================ Function to send SMS ============================//
void send_sms(void)
{
int i ;
printf("AT+CMGS=\"01667646812\"\r\n");
// Contact relative'number to send SMS
i = 0;
delay_ms(2000);
printf(" PHAT HIEN NGA !");
// contain of SMS
putc(26);
// ending message 26
printf("\"\r\n");
delay_ms(1000);
printf("Gui tin nhan...");
delay_ms(100);
printf("Da gui tin..");
delay_ms(100);
}

Link video demo of fall detect system:


https://www.youtube.com/watch?v=X3lng3HEqm8

53

Potrebbero piacerti anche