Sie sind auf Seite 1von 83

WIRELESS ECG

Volume II

By Haroon Mustafa Khan Submitted to The School of Information Technology & Electrical Engineering, University of Queensland For the degree of Bachelor of Engineering In the Division of Computer Systems Engineering

Letter to the Head

Haroon Mustafa Khan

Letter to the Head


6 Demigre St, Eight Mile Plains, Brisbane, Qld 4113, Australia Ph: (07) 3841 4021 Email: s358223@student.uq.edu.au 18 October 2002 To the Head School of Information Technology and Electrical Engineering The University of Queensland St Lucia, 4072 Australia

Dear Professor Simon Kaplan, In accordance with the requirements of the degree of Bachelor of Engineering in the division of Computer Systems Engineering, I present the following thesis entitled Wireless ECG. This work was completed with partnership of Mr. William Brims and Mr. Bhavik Kant under the guidance and supervision of Dr Adam Postula. I declare that the work contained in this document is my own, except as acknowledged in the text, footnotes or references, and has not been previously submitted for a degree at the University of Queensland or at any other institution. Yours sincerely,

Haroon Mustafa Khan

Abstract

Haroon Mustafa Khan

Abstract
The overall objective of this project is to design and implement a prototype ECG system which replaces wired connections between sensor points and a central node with wireless links. Successful implementation of the final system would be of benefit to all involved in the use of electrocardiography as access to, and movement of, the patient would not be impeded by the physical constraints imposed by the cables. Most aspects of the design would also be portable to other sensor applications, making the work relevant to a vast range of systems where movement of sensors is desirable and constrained by hard-wired links. The design and implementation of the wireless link and ECG sensor electronics to produce an ECG signal form the basis of the Wireless ECG Monitors. The Wireless Sensor Protocol (WSP) was hence produced to handle the wireless link. Analogue electronics are used to obtain the signal and to filter noise, while PC based software is used to display the results. The WSP for the ECG system consists of two Slave nodes and one Master node. The Slave node prototype consists of an ECG sensor (with associated electronics), PIC microcontroller and Nordic's nRF401 UHF transceiver, as 'patches' ordinarily placed on the patient. Alteras Nios Softcore processor (16 bit design) with Nordic's nRF401 UHF transceiver forms the Master (base) node where data is collected and an ECG signal is calculated for displaying to the medical staff.

ii

Acknowledgement

Haroon Mustafa Khan

Acknowledgement
In order for me to complete this project to its best, I am grateful to several family and friends. Firstly, I would like to mention my supervisor, Dr. Adam Postula who provided the inspiration and motivation required to make the project a success. Furthermore, a great deal of assistance was provided by Matthew DSouza who always offered support and ideas, often at difficult times. Thanks Matt for keeping the project rolling. Also thanks to Simon Leung for managing the world class facilities offered to us at iLabs. An immense amount of appreciation goes to my partners in crime for the ECG Team, William Brims and Bhavik Kant. Without your brains and help, nothing would be possible. Also recognition to the rest of the iLab team including Alan Hardcastle, Dimitri Andronikos, Zon Shih and other close friends, with whom there were several memorable hard working days and nights together. I hope we can stay close friends forever. Also recognition goes to Sanjay B, who let us borrow his camera for pictures of our final product on such a short notice. Finally, I would like to extend my greatest and utmost gratitude to my family, in particular my parents who have stuck with me, even after my late nights in labs and often times where I spent less time with family and more in front of a computer. This thesis is a reward of your patience.

iii

Table of Contents

Haroon Mustafa Khan

Table of Contents
LETTER TO THE HEAD ...........................................................................................................................I ABSTRACT................................................................................................................................................ II ACKNOWLEDGEMENT .........................................................................................................................III TABLE OF CONTENTS .......................................................................................................................... IV LIST OF FIGURES.................................................................................................................................. VI CHAPTER 1 INTRODUCTION .............................................................................................................. 1 1.1 1.2 1.3 THESIS INTRODUCTION .............................................................................................................. 1 THESIS OBJECTIVE..................................................................................................................... 2 THESIS STRUCTURE ................................................................................................................... 3

CHAPTER 2 ECG ..................................................................................................................................... 4 2.1 2.2 ECG THEORY ............................................................................................................................ 4 NEED FOR WIRELESS ECG ........................................................................................................ 5

CHAPTER 3 SIMILAR PROJECTS....................................................................................................... 6 3.1 3.2 3.3 3.4 BLUENURSE .............................................................................................................................. 6 BLUEMEDICA ............................................................................................................................ 6 MICROMEDICAL ........................................................................................................................ 7 SMART DUST ............................................................................................................................. 8

CHAPTER 4 WIRELESS ECG DESIGN ............................................................................................. 10 4.1 ECG SYSTEM DESIGN ............................................................................................................. 10 4.2 ECG NODE HARDWARE .......................................................................................................... 10 4.2.1 ECG Master ....................................................................................................................... 11 4.2.2 ECG Slave.......................................................................................................................... 11 4.3 ECG NODE SOFTWARE ............................................................................................................ 12 4.3.1 ECG Master ....................................................................................................................... 12 4.3.2 ECG Slave.......................................................................................................................... 13 CHAPTER 5 WIRELESS PROTOCOLS ............................................................................................. 14 5.1 BLUETOOTH............................................................................................................................. 15 5.1.1 Bluetooth Theory................................................................................................................ 15 5.1.2 Bluetooth Stack .................................................................................................................. 16 5.2 ZIGBEE .................................................................................................................................... 18 5.2.1 ZigBee Theory.................................................................................................................... 18 5.2.2 Data Rate ........................................................................................................................... 19 5.2.3 Power Consumption........................................................................................................... 19 5.2.4 Cost and Availability.......................................................................................................... 19 5.3 PROTOCOL SELECTION ............................................................................................................ 20 CHAPTER 6 WIRELESS SENSOR PROTOCOL .............................................................................. 22 6.1 6.2 WSP STACK ............................................................................................................................ 22 WSP LAYER DESCRIPTION ...................................................................................................... 23

iv

Table of Contents

Haroon Mustafa Khan

6.2.1 6.2.2

Application Layer............................................................................................................... 23 Medium Access Control Layer ........................................................................................... 23


Time Division Duplex Scheme............................................................................................ 24 Packet Format ...................................................................................................................... 27

6.2.2.1 6.2.2.2

6.2.3 Physical Layer ................................................................................................................... 29 6.3 SYSTEM HIERARCHY ............................................................................................................... 30 CHAPTER 7 BASEBAND PROCESSOR ............................................................................................. 32 7.1 PIC 16F876 ............................................................................................................................. 32 7.2.1 I/O Pins .............................................................................................................................. 33 7.2.2 Timer.................................................................................................................................. 34 7.2 NIOS SOFTCORE PROCESSOR ................................................................................................... 35 7.2.1 Embedded System Hardware Design ................................................................................. 36 7.2.2 Software ............................................................................................................................. 38 CHAPTER 8 OPERATING SYSTEM .................................................................................................. 40 8.1 8.2 BERKLEY TINYOS ................................................................................................................... 40 WSPOS................................................................................................................................... 41

CHAPTER 9 PRODUCT EVALUATION ............................................................................................ 43 9.1 9.2 9.3 9.4 DESIGN .................................................................................................................................... 43 POWER..................................................................................................................................... 45 COST ....................................................................................................................................... 46 SIZE ......................................................................................................................................... 46

CHAPTER 10 FUTURE DEVELOPMENTS ....................................................................................... 48 10.1 10.2 TIMING ISSUES......................................................................................................................... 48 WSP ........................................................................................................................................ 49

CHAPTER 11 CONCLUSION............................................................................................................... 51 REFERENCE........................................................................................................................................... 52 APPENDIX A SLAVE CODE ................................................................................................................ 55 APPENDIX B MASTER CODE............................................................................................................. 66

List of Figures

Haroon Mustafa Khan

List of Figures

FIGURE 2.1 - IDEAL ECG WAVE ................................................................................................................... 4 FIGURE 3.1 - PORTABLE TABLETPC DESIGN ................................................................................................ 7 FIGURE 3.2 - MICROMEDICALS ECG MODULE ............................................................................................ 8 FIGURE 3.3 - SMART DUST NON-FUNCTIONAL MOTE ................................................................................... 9 FIGURE 4.1 - NETWORK TOPOLOGY ............................................................................................................ 10 FIGURE 4.2 - MASTER NODE ARCHITECTURE ............................................................................................. 11 FIGURE 4.3 - SLAVE NODE ARCHITECTURE ................................................................................................ 12 FIGURE 4.4 - MASTER NODE SOFTWARE .................................................................................................... 13 FIGURE 4.5 - TWO VITAL TASKS IN SLAVES OS ......................................................................................... 13 FIGURE 5.1 - BLUETOOTH SCATTERNET ..................................................................................................... 16 FIGURE 5.2 - BLUETOOTH SPECIFICATION PROTOCOL STACK ..................................................................... 17 FIGURE 5.3 - ZIGBEE PROTOCOL STACK .................................................................................................... 18 FIGURE 6.1 - WIRELESS SENSOR PROTOCOL STACK ................................................................................... 22 FIGURE 6.2 - TIME DIVISION DUPLEX SCHEME ........................................................................................... 25 FIGURE 6.3 - RECEIVING NODE TO IGNORE PACKET .................................................................................... 27 FIGURE 6.4 - ENTIRE SYSTEM HIERARCHY .................................................................................................. 30 FIGURE 7.2 - ALTERA EXCALIBUR DEVELOPMENT BOARD ......................................................................... 35 FIGURE 7.3 - EMBEDDED HARDWARE DESIGN ............................................................................................ 37 FIGURE 7.4 - SNIPPET CODE FOR SETTING LED OUTPUT TO LOW ................................................................ 38 FIGURE 7.5 SNIPPET CODE FOR CREATING TIMER INTERRUPT ................................................................... 39 FIGURE 8.1 - CREATE_THREAD AND THREAD_TO_DO ROUTINE FOR OPERATING SYSTEM ............................ 42 FIGURE 9.1 FINAL RESULT ....................................................................................................................... 44 FIGURE 9.2 MASTER NODE ...................................................................................................................... 45 FIGURE 9.3 SLAVE NODE .......................................................................................................................... 47

vi

List of Tables

Haroon Mustafa Khan

List of Tables

TABLE 5.1 - WIRELESS TECHNOLOGY COMPARISON TABLE ........................................................................ 14 TABLE 6.1 - SWITCHING TIMES FOR THE NRF401 TRANSCEIVER ................................................................. 23 TABLE 6.2 - NRF401 CHARACTERISTICS ..................................................................................................... 30 TABLE 7.1 - PICF876 MICROCONTROLLER CORE FEATURES ..................................................................... 33 TABLE 7.2 PICF876 PIN ALLOCATION ..................................................................................................... 34 TABLE 7.3 - TIMING FUNCTIONS OF PICF876 (MAC, PHY)....................................................................... 34 TABLE 7.4 - WIRELESS ECG 32 BIT NIOS DESIGN ...................................................................................... 38 TABLE 9.1 TDD RESULTS ........................................................................................................................ 45 TABLE 9.2 POWER CONSUMPTION RESULTS FOR SLAVE NODE .................................................................. 46 TABLE 9.3 BUDGET FOR SLAVE NODE...................................................................................................... 46

vii

Introduction

Haroon Mustafa Khan

Chapter 1 Introduction

1.1 Thesis Introduction


Ever since the existence of mankind, the goal of humans has forever been to make life simpler. The wheel was invented by the Sumerians to help with transportation. The computer was created to improve and quicken several tedious tasks. In the last decade though, the greatest scope and emphasis is being seen in the wireless technology sector. The aim of this technology is to reduce the number of cables and wires which may be tedious and often even hazardous. Scientists and Engineers have been exerting, both a lot of time and money on these technologies, and hence we have the beginning of what many are calling the Wireless Age. In todays day and age, it is common to see the likes of mobile phones, laptops, computers, personal digital assistants (PDAs) and of late, MP3 players. Such devise seem useful, but the concept of these devices being able to interact with each other is what has caught the eye of designers. The thought of being able to meet an acquaintance and immediately having exchanged personal details wirelessly, seems far-fetched yet very realistic. One such place where wireless technology could be implemented is inside a hospital, where there are several electrical devices using long wires and cables. An Electrocardiogram (ECG) Monitor which ideally has 12 cables connected to a patient could potentially be implemented as a wireless system. An ECG reading is proven worldwide to be the most accurate data used to determine a patients heart condition. Hence, this project is based on the ultimate vision to eliminate all cable used in an ECG System and make the system wireless with each node communicating wirelessly to the computer for the doctor to see.

Introduction

Haroon Mustafa Khan

1.2 Thesis Objective


The overall objective of this project was to design and implement a prototype ECG system which replaced wired connections between sensor points and a central node with wireless links. The proposed wireless ECG sensor was a joint effort with two final year Engineering colleagues, William Brims and Bhavik Kant. Each group member was assigned a particular task in regards to a network layer of the wireless protocol, which they all performed to a high standard. This documentation gives the reader a brief overview of the sections relating to the other two members, with the main focus on the work and research carried out by the author. For a greater understanding of this project, the following Wireless ECG thesis documentations are recommended: Wireless ECG Volume I by William Brims Wireless ECG Volume III by Bhavik Kant

This project can be broken up into four main stages. Firstly, a detailed study into the ECG System was performed, which included the node architecture and the ECG sensor itself. Secondly, focussed was directed towards developing an efficient, reliable and robust wireless network protocol after researching different wireless technologies available. The next step involved a decision on which baseband processors to incorporate and to instigate the software using an operating system. The final step involved the implementation of the wireless design, with the result, a PC displaying an ECG signal of a nearby patient.

Introduction

Haroon Mustafa Khan

1.3 Thesis Structure


This documentation introduces the ideal solution for the ECG predicament, creating a wireless ECG design to enable easy and effective communication between a PC and a patient wired up to accumulate ECG data. Chapter 2 provides the reader with a brief overview of an ECG System, including the reasons for creating a wireless design in such a system. Chapter 3 delves into some of the exciting technologies in research and on the market. Including a range of technologies based on Wireless Biomedical Sensors. Chapter 4 introduces the basic integration of the ECG design in relation to the software and hardware aspect of the design. Chapter 5 presents a range of protocols for our design, with particular interest in two ideal wireless communication protocols, namely Bluetooth and ZigBee. Chapter 6 draws from the information presented in the previous chapter to implement into the design of the Wireless ECG. Chapter 7 discusses the processors which have been incorporated into the design to operate the entire system. Chapter 8 commences with an overview of the TinyOS system designed by Berkley University, before dwelling on the Wireless ECG operating system based on TinyOS. Chapter 9 evaluates the entire working product, by comparing results with the project objective. Chapter 10 suggests improvements on the current working version of the product. These enhancements are intended to improve the operation and design of the Wireless ECG system as a whole. Chapter 11 concludes with a brief overview of the entire design.

ECG

Haroon Mustafa Khan

Chapter 2 ECG

2.1

ECG Theory

Electrocardiogram (ECG/EKG) is a representation of electrical activity of the heart muscle as recorded from the body surface, which is used in the analysis of heart disease. It was developed by William Einthoven in 1903 using a crude galvanometer. This electrical activity is related to the impulse that travels through the heart which determines its rate and rhythm. For a full ECG examination of a patient, he/she must be wired up with 12 electrodes. The ECG signal obtained represents the polarization and the depolarization of the cells during a heartbeat. Figure 2.1 shows an example of an ideal ECG signal

Figure 2.1 - Ideal ECG Wave This documents scope pertains mainly to the network of the Wireless ECG design and not an explanation of our sensor design and software for sampling, analog to digital conversion and signal compression. For an overview on the

ECG

Haroon Mustafa Khan

hardware and software of the ECG sensor design, it is advisable to refer to my colleague, William Brims thesis entitled Wireless ECG Volume I.

2.2

Need for Wireless ECG

An ECG signal is useful for a doctor to evaluate a patients heart condition relating to: Whether a heart attack has occurred What parts of the heart is damaged Irregular heart beats Whether the heart is not receiving enough blood or oxygen

As has been demonstrated, an ECG signal is extremely valuable, making it a conventional mechanism used in hospitals by both doctors and nurses. The aim of this thesis is to develop a wireless system to provide a more user-friendly device. By eliminating the long cables between nodes, the patient is comfortably able to move around without the hassle of wires, while also being able to place the electrodes on themselves without being impeded by leads. Similarly it provides the doctor or nurse with a trouble-free approach to the patients ECG signal. In addition, software could allow ECG signals to be saved and sent possibly by email to other parts of the world. In fact, for patients in rural and regional areas an ECG report could be sent via email to a doctor for examination.

Similar Projects

Haroon Mustafa Khan

Chapter 3 Similar Projects

3.1

BlueNurse

As has been explained previously, the need for such a device is immense, hence there are projects similar to this that are being conducted throughout the world. This idea of a Wireless ECG was first introduced to the University of Queensland Computer Systems and Electrical Engineering department last year as the thesis project BlueNurse, completed by three colleagues, Daniel Marr, David Lin, Naveenan Vasudevan. The BlueNurse design involved a pointto-point communication system with three nodes connected to a single Bluetooth module and another Bluetooth module used to receive ECG data for the PC. This project was successfully able to communicate wirelessly with the two modules, however it lacked in that it did not display an ECG signal on the PC. [16, 22]

3.2

BlueMedica

Another project with similar goals is the BlueMedica project, which was also being fabricated at the same time as BlueNurse. This was a joint effort between five Engineering Students at the Slovak University of Technology in Bratislava. The BlueMedica design again applies the Bluetooth wireless technology for communication between a patient and his doctor/nurse. A mobile device called a TabletPC was designed to enable examination of vital data by a doctor or a nurse. As part of the project, a device for patients was created. This device is a wristlet which measures the temperature and pulse of the patient, and passes it to the TabletPC for evaluation. Furthermore, an information system was created to store the various data received at the TabletPC. Additional functionalities

Similar Projects

Haroon Mustafa Khan

such as ECG, blood pressure, insulin dosing appliance, pulse oximetry are also capable on this communication module. Figure 3.1 shows a design of the portable TabletPC.

Figure 3.1 - Portable TabletPC Design

[14]

3.3

MicroMedical

One such company which may provide us with some competition in the market is MicroMedical Industries. MicroMedical is a subdivision of Ventracor which is an Australian medical company that designs technology for the medical profession. It has recently been working towards creating a handheld Personal Digital Assistant (PDA) which will display the ECG data of a patient through wireless technology. This PDA data can then be downloaded onto a laptop, desktop PC or Pocket PC and possibly sent to other parts of the world for analysis. Their product has received strong interest from countries such as Italy, Spain, Ireland, the United States and China. It is small and lightweight and no batteries are necessary, making it a valuable portable mechanism.

Similar Projects

Haroon Mustafa Khan

Although this technology symbolizes a great step in this growing field, there are still some aspects in which it lacks. The major difference though between our proposed device and that of MicroMedical is that our wireless ECG design consists of each of the nodes communicating using wireless technology with the PC. Whereas, MicroMedicals design consists of all 12 nodes connected to a single baseband processor and a single transceiver to send and receive from the PC. Our design eliminates the wires between the nodes, such that each node consists of its own transceiver and microcontroller as a result making the design of both hardware and software more complex, nevertheless more userfriendly. Figure 3.2 shows MicroMedicals ECG interface

Figure 3.2 - MicroMedicals ECG module [25]

3.4

Smart Dust
[11, 13]

The Smart Dust scheme

was largely designed by Seth Hollar under the

supervision of Professor Kris Pister at the University of Berkley, California. The goal of the Smart Dust project was to explore the limits on size and power consumption in autonomous sensor nodes. Its design was intended to envision most general application. The device which was proposed, incorporated communication, processing, sensor, and batteries into a minute package about a cubic inch size. Figure 3.3 shows a picture of a non-functional mode which has two silicon chips sitting on a type-5 hearing aid battery. Also it contains a

Similar Projects

Haroon Mustafa Khan

MEMS corner cube optical transmitter array and a CMOS ASIC chip with an optical receiver, charge pump and simple digital controller.

Figure 3.3 - Smart Dust Non-Functional Mote [6] Smart Dust provides a platform for future prototype with the emphasis on reducing size and power. Furthermore, this module offers a new solution to the wireless technology, optical. Radio Frequency (RF) presents a problem as dust motes offer a very limited space for antennas, thereby demanding extremely short wavelength hence high frequency transmission. In addition, RF circuitry is fairly complex making it difficult to reduce power consumption. On the other hand, the optical transmission require a significantly reduces power intake. However a line-of-sight path is required, making it unsuitable for the Wireless ECG application. Nevertheless, the main interest in the Smart Dust project is for the reason that it provides a basic structural platform of a wireless sensor design, which can be incorporated into the Wireless ECG design. An operating system, by the name of TinyOS was designed to create an ideal sensor networking structure to the system architecture, using a minimum amount of program space on an Atmel Chip. This concept is dwelled on further in Chapter 8.

Wireless ECG Design

Haroon Mustafa Khan

Chapter 4 Wireless ECG Design

4.1

ECG System Design

A design system consisting of a single Master and two Slave network design was incorporated into this project. The master node comprises of the interface to the PC which is responsible for communicating directly with each particular slave as shown in figure 4.1. The two slave nodes which are placed on the patients body to collect ECG data will in turn send data packets through the RF transceivers to the master which will display the ECG information through a graphic user interface (GUI).

Master (PC)

Slave A (Electrode)

Slave B (Electrode)

Figure 4.1 - Network Topology [8]

4.2

ECG Node Hardware

10

Wireless ECG Design

Haroon Mustafa Khan

4.2.1

ECG Master

The master ECG node is responsible for receiving the two measured values and combining the information to produce an ECG signal of the patient. Its basic structure includes a PC connected to the radio transceiver. The Nios Softcore Processor is used as the interface between the PC and the transceiver. This embedded processor design is explained in detail in section 7.2. For both master and slave design the Single Chip RF Transceiver, nRF401 which operates at 433MHz is used. Frequency Shift Keying (FSK) modulation and demodulation capabilities are handled with this chip. For additional detail on the transceivers it is worthwhile to refer to Volume III in this thesis documentation. Figure 4.2 shows the block diagram of our Master Node.

RF Transceiver

Nios Softcore Processor

PC

Figure 4.2 - Master Node Architecture [8]

4.2.2

ECG Slave

The ECG slave nodes are placed on the heart of the patient to measure biopotentials which are then transmitted wirelessly to the Master ECG node. The slave node consists of an electrode connected to an amplifier allowing an adequate signal to be transferred. This signal needs to be recognisable by the Baseband Processor and therefore next it is then passed through an Analog to Digital Converter to convert it into a digitised signal. Our design uses a PIC 16F876 which is described further in Section 7.1. Finally the microcontroller

11

Wireless ECG Design

Haroon Mustafa Khan

sends the packet via the RF transceiver to the master node using the necessary packet format. A block diagram of the slave node is shown in Figure 4.3.

Electrode

Amplifier

ADC

PIC
16F876

RF

Figure 4.3 - Slave Node Architecture [8]

4.3

ECG Node Software

4.3.1

ECG Master

As explained earlier the master node is designed on a Nios Softcore Processor, and hence this controls the RF transceiver. The code for this processor is written in C and it is responsible for sampling the incoming data and creating the outgoing packets. Furthermore the software is designed such that the master has control over the slave node in terms of transmission slot time. This is executed using the Time Division Duplex (TDD) Scheme. A simple operating system (OS) to handle the different tasks called WSPOS (based on TinyOS design) was also considered. Both these concepts are explained in detail later. The ECG Graphical User Interface Program which is created in Visual C++ is used to display the patients ECG to the user. This software will calculate the received measurements from each slave node and perform signal processing and conditioning on the received measurements from the slave nodes. A block diagram of the master nodes software can be seen in figure 4.4.

12

Wireless ECG Design

Haroon Mustafa Khan

Nios Softcore Processor

Reconstruction of Sampled Signal

Signal Processing and Conditioning

Display ECG Signal Graphical User Interface Sensor Network Control Interface

Figure 4.4 - Master Node Software [8]

4.3.2

ECG Slave

The software for the Slave ECG nodes baseband processor (PIC 16F876) was created in C format, also incorporating an operating system. Periodically, the slave node will sample the patients body voltage source every 3 milliseconds. This information is then logged into the Flash Memory in the microcontroller. During the slaves transmission slot, which is determined by the packet received from the master, it will extract the stored data and transmit it wirelessly to the master. Figure 4.5 shows a simple flowchart of these two tasks.

Task called every 3 ms

Sampling ECG

Task called at transmission slot

Transmit Packet

Sample ECG data

Extract data from Flash

Store in Flash

Send Packet

End

End

Figure 4.5 - Two vital tasks in Slaves OS

13

Wireless Protocol

Haroon Mustafa Khan

Chapter 5 Wireless Protocols


Communication protocols provide an integral backbone of any wireless systems. Sensors and instruments have long been using wireless technology, but extensive research into this field has only recently boomed due to advances in technology such as 802.11, Hiperlan, Bluetooth and ZigBee. Table 5.1 shows a comparison table of some of the different Wireless technologies available.
IEEE 802.11a Frequency band Frequencies 5 GHz 5.475.725 GHz Max Capacity Typical Power QoS Interference 20 Mbps 25mW Low Satellite IEEE 802.11b 2.4 GHz 2.42.483 GHz 11 Mbps 30mW Low Microwave, cordless phones, Bluetooth Typical Radius Costs 20100 m Medium 30200 m High 20100 m Low 20100 m Low 5 GHz 5.155.30 GHz 20 Mbps 0.11 W Medium Satellite 5 GHz 5.155.30 GHz 54 Mbps 25mW High Satellite Hiperlan1 Hiperlan2 Bluetooth Class 1 2.4 GHz 2.42.483 GHz 732.2 Mps 1mW Medium Microwave, cordless phones, IEEE 802.11b 10 m Medium

Table 5.1 - Wireless technology comparison table [15] However in the Wireless ECG design the need is for a short range and low power wireless network, and therefore most of the above technologies can be ignored. When deciding upon the wireless protocol, focus is put towards two protocol standards which not only provide a more than convenient replacement for cables, but with their capacity for autonomous interaction and rich functionality, will become increasingly popular in the search for hassle free wireless communication. These are: Bluetooth

14

Wireless Protocol

Haroon Mustafa Khan

ZigBee

5.1

Bluetooth

5.1.1

Bluetooth Theory
has its origins in the late 1990s, when

The Bluetooth wireless system

[21]

Ericsson Mobile Communications launched an initiative to study wireless alternatives to the cables which linked the mobile phones with accessories such as headsets. It was names after Harald Bluetooth (Harald Gormsson) a 10th century Danish King who united Denmark and Norway. This was appropriate as it symbolised the uniting of isolated devices and systems. The scope for Bluetooth is such, that currently over 2000 companies are participating in the special interest group (SIG) formed in 1998 by Ericsson, Nokia, IBM, Intel and Toshiba, while many more are developing Bluetooth products. Several Bluetooth consumer products are becoming available now, and soon it will be evident whether this technology is accepted by the general public and is able to provide an improved standard of life. Bluetooth is a pure ad hoc networking protocol used especially for short-range, low power wireless communication radio link between two devices operating in the unlicensed 2.4 GHz industrial scientific and medical (ISM) band. Bluetooths design incorporates a piconet network in which two or more Bluetooth devices form a communication channel to exchange data. The first device to initiates the channel is the master while the other devices on the piconet are the slave. In addition, the Bluetooth technology is capable of engaging in several piconets present in the same vicinity in a Time Division Multiplexing fashion. This phenomena, known as scatternet (shown in Figure 5.1) gives Bluetooth a more versatile look. If used in the wireless ECG system, this would provide as easy

15

Wireless Protocol

Haroon Mustafa Khan

method of transferring ECG data between doctors and possibly to a central computer to collect data of all patients.

Piconet 1

Piconet 2

Master Slave Bluetooth Link Figure 5.1 - Bluetooth Scatternet [26] Hybrid direct-sequence spread spectrum and frequency hopping spread spectrum technology is used as the transmission scheme. The Bluetooth module transmits at 1mW (0 dBm) at a useful data speed of 721 kbps per piconet. It can accommodate up to eight devices per piconet, in which the expected coverage range is around 10 m.

5.1.2

Bluetooth Stack

To facilitate the data transmission in Bluetooth, they have designed a series of protocols within the system that processes data for suitable transmission and receipt. Its structure consists of a microprocessor to handle all baseband specification, and several software layers.
[12]

Each layer in the stack is

responsible for structuring the data to allow accurate communication over the Bluetooth Link. Figure 5.2 provides a representation of the Bluetooth Stack.

16

Wireless Protocol

Haroon Mustafa Khan

UPPER LAYER RFCOMM L2CAP HCI Driver


PCM UART or USB

SDP

Audio

HCI Link Manager Baseband Radio LOWER LAYER

Figure 5.2 - Bluetooth specification protocol stack [22] Radio Layer is the lowest defined layer of the protocol and it defines the requirements of the Bluetooth transceiver. Baseband Layer is concerned with the link control at the bit and packet level as well as the coding and encryption for the packet assembly and frequency hopping operations. Link Manager Layer configures the link, in that it is responsible for encryption, authentication, state of stations in the piconet, power modes, traffic scheduling and packet format. Host controller interface (HCI) accommodates the transferring of data between the upper and lower layer (baseband controller) via a physical bus, allowing the user access Bluetooth baseband capabilities. Audio communication is relatively simple as it involves opening an audio link in a pulse code modulated (PCM) format. Logical link control and adaptation protocol (L2CAP) allows for protocol multiplexing and segmentation of outgoing packets.

17

Wireless Protocol

Haroon Mustafa Khan

Service Discovery Protocol (SDP) provides the means for application to discover which services are available and the characteristics of those services. RFCOMM Layer emulates the RS-232 control and data signalling over the Bluetooth baseband

5.2

ZigBee

5.2.1

ZigBee Theory

One of the emerging standards in the move toward a wireless world is an approach called ZigBee.
[27]

Pioneered by Phillips, it has since formed into an

alliance of companies working together to create a wireless communication protocol. The ZigBee stack unlike Bluetooth is relatively straightforward, as can be seen in Figure 5.3.

Figure 5.3 - Zigbee Protocol Stack [24]

18

Wireless Protocol

Haroon Mustafa Khan

The main purpose of this standard is to provide its customers with three main features: Low data rate Low power consumption Low cost

5.2.2

Data Rate

Like Bluetooth, the ZigBee technology operates in the 2.4 GHz ISM band. The maximum data rate achievable on this technology is 250 kbps. On top of that, it caters for a range of between 10 meters to 75 meters depending on the power consumption required for a given application.

5.2.3

Power Consumption

The design for ZigBee took into consideration the high power consumption of Bluetooth. For most application, the Zigbee module is capable of a battery life of 6 months to 2 years with AA batteries. This is achieved by using sleep mode functions to allow communication only when the application deems necessary. The Zigbee chip here draws a few milliamps in sleep mode against 100 microamps or more for a comparable Bluetooth state. Furthermore this prevents the device from interference problems as it often wont be operating when other modules are using the 2.4 GHz band.

5.2.4

Cost and Availability

Cost was another deciding factor in ZigBees design. Bluetooth which is currently between $7 and $10 today, may go as low as $4, however the ZigBee solution will come in at less than $2.

19

Wireless Protocol

Haroon Mustafa Khan

Currently, the major disadvantage with ZigBee is that it is still in development stage. Standardised work on the Zigbee protocol is nearly finished, with the final specs expected to be ratified by the end of the year. Companies such as Phillips Semiconductors and Motorola are putting the final touches to a networking spec that could leapfrog all other competitors in the wireless technology market.

5.3

Protocol Selection

While both technologies have their advantages and disadvantages, they are in fact different solution optimised for different applications. Bluetooth provides an ideal ad hoc network between capable device for transferring audio, screen graphics, picture and file. On the other hand, the Zigbee device is ideally for a static network, which comprises of a multiple devices communicating with smaller packets. [23] The intended design requires a wireless sensor which will provide us with: low power wireless power supply efficient, reliable and lean communication protocols easily accessible physical measurements interaction between instruments and controllers costs and availability

By analysis of the above criteria, one can determine which particular technology would be best suited for the Wireless ECG application. The most well-suited technology for this design would be ZigBee, mainly due to its power features and relatively simple stack. Bluetooth in contrast, has certain unnecessary and rather complex features in its protocol. However as ZigBee technology is not available to the market, the best solution was to design a specific protocol

20

Wireless Protocol

Haroon Mustafa Khan

design suited for this particular application. This protocol is discussed further in the next chapter. The reason as to why this documentation has detailed other wireless protocols is to provide the reader with the adequate background on the existing technology and why they are unsuitable for our application. Furthermore the concepts involved in these standards, in particular Bluetooth make up a vital part of our wireless systems protocol

21

Wireless Sensor Protocol

Haroon Mustafa Khan

Chapter 6 Wireless Sensor Protocol

6.1

WSP Stack

The communication protocol which was incorporated into this project is called the wireless sensor protocol (WSP). The main purpose of this protocol is to provide an easy to use and reliable way of transferring data between the nodes. Designing a protocol is error-prone and time consuming but more importantly the design decisions made in this phase greatly affect the quality of the entire system implementation. Hence, it is important to design a simple protocol which is suitable for the application. The execution of each block is considered instantaneous and any synchronisation between stack layers has to be performed by means of protocols. [20] The WSP stack which is employ is based on the protocol for universal radio links (PURL) as well as the Bluetooth wireless protocol. The WSP stack is shown in Figure 6.1.

Application Medium Access Control Physical Figure 6.1 - Wireless Sensor Protocol Stack [8] Each of the layers are essential in the design of the project. Hence, the workload between the three final year thesis students involved with this project, was split between the three protocol layers.

22

Wireless Sensor Protocol

Haroon Mustafa Khan

6.2

WSP Layer Description

6.2.1

Application Layer

The Application (APP) layer which forms the upper layer of the stack is similar to a PURL Application Layer. It is responsible for providing the command interface services to link the protocol stack with the user software. Therefore in the master node, it establishes the data communication of the entire system, by using a GUI and passing a query through to the next layer. Furthermore, the PHY layer extracts accurate data from the ECG as has been explained in more detail in Volume I.

6.2.2

Medium Access Control Layer

The authors main responsibility for the Wireless ECG project was the Medium Access Control Layer (MAC). The medium access layer forms an integral part of wireless communications for controlling multiple accesses to the medium simultaneously and optimally. This particular layer involves controlling the entire piconet link through setting an establishment between the links via the master mode. The MAC layer moreover recognises certain functions regarding the transmission of data. Hence, it also is in charge of changing the modes for the transceivers. Table 6.1 shows the time required to change between the two states, and these times are taken into account to ensure no packets are missed.

Change of Mode TX RX RX TX

Max Delay 3 ms 1 ms

Table 6.1 - Switching times for the nRF401 transceiver

23

Wireless Sensor Protocol

Haroon Mustafa Khan

To obtain an accurate ECG signal it is vital that each slave node is sampling electric activity of the patient at a concurrent time. Since our wireless ECG design has multiple nodes, the MAC layer is responsible for not only ensuring the synchronisation of transmission but also the synchronisation of ECG data collected. Furthermore, the MAC layer also holds fundamental information such as addresses of other nodes in the piconet and the types of packet sent are also determined by the MAC layer In addition, as it is the central layer, it provides the link between the APP and the PHY Layer. The MAC layer is implemented in the PIC microcontroller for the slave node design and on the Nios Softcore for the master node design. One useful feature of the MAC layer used to enhance its performance is the Time Division Duplex (TDD) Scheme. Since the MAC layer has control over the transmission time of each node, it also is responsible for resynchronisation of the wireless network. This is executed by checking a certain counter which holds the number of cycles required before resynchronisation.

6.2.2.1

Time Division Duplex Scheme

As explained earlier, TDD makes up a vital part of the MAC layer design. The scheme incorporated here is based on the Bluetooth piconet specifications. The Master controls the transferring of data in the entire system. Using TDD, the master has control over which slave sends and at which particular slot time. Figure 6.2 shows an implementation of our design. It shows how each of the three nodes in the piconet communicates independently without interference, preventing the probability of collisions and enhancing simplicity of the design. However, the most complex aspect of this type of system is the global clock which was quite difficult to implement, due to certain timing issues involved in the entire design.

24

Wireless Sensor Protocol

Haroon Mustafa Khan

Master Packet Slave Packet

TX to RX RX to TX

Connection and Synchronise

Periodic Data Transfer

Resynchronisation\Disconnection (after 6 cycles)

Master

Slave A

Slave B

Figure 6.2 - Time Division Duplex Scheme [8] The TDD scheme in the Wireless ECG design functions as follow:

1. The TDD scheme is initialised by a connection and synchronisation period, in which the master sends a message assigning each slave in the piconet (two in this design) with a particular time slot during which it is allowed to communicate with the master.

2. Master node changes into receive mode once the entire packet has been sent.

3. Once the synchronisation is accomplished, the slave is then permitted to transmit data at its given time slot. Each slave will initialise its clock so there is a global clock in the piconet.

25

Wireless Sensor Protocol

Haroon Mustafa Khan

4. Each slave will transmit packets during its time period by firstly changing into transmit mode and then wirelessly sending ECG information before shifting back into receive mode once again.

5. This cycle will be repeated a certain number of times before the master will either resynchronise or disconnect. This is performed to ensure that the global clock is constantly updated reducing the chances of timing problems. Through experimentation of this piconet architecture it was realised that relatively precise results were achieved if the network was resynchronised once every six cycles. However, with the inclusion of more nodes, this will almost certainly result in reducing the number of cycles before synchronisation is needed, in turn requiring more resynchronisation at regular intervals. The size of these time slots is dependant on the symbol rate of the radio transceiver as well as the time required for the transceiver to switch between receiving and transmission modes. The symbol rate for the chosen RF transceiver is 20 kbps, meaning that each transmission symbol bit period is 50 s. By observation of the TDD Scheme it is evident that after each transceiver sends its packet, it immediately changes modes to receiving. This is to disable the nRF401 completely preventing it from transmitting a logic low output as each transceiver will receive the signal closest to it. This then creates the issue of slave nodes receiving packets from other slave nodes as shown in Figure 6.3 Hence the MAC layer will check the packet address to ensure it only listens to the master and rejects from other slaves.

26

Wireless Sensor Protocol

Haroon Mustafa Khan

Slot 1 Sender Master


TX

Slot 2 Slave A
TX

Slot 3 Slave B
TX

Receiver

Slave A Slave B

Master Slave B

Master Slave A

Figure 6.3 - Receiving Node to ignore packet (marked by red cross)

6.2.2.2

Packet Format

The format of our packets for the MAC layer for both slave and master nodes are as follows: [8] Master Connect/Disconnect/Resynchronise: (APP MAC) 4 bits Unique Identifier (MAC PHY) 4 bits Unique Identifier 8 bits SlotA/SlotB 2 bit Connect/Disconnect/Resynchronise 1 bit Connect/Disconnect

27

Wireless Sensor Protocol

Haroon Mustafa Khan

Master Receive Packet: (PHY MAC) 4 bits Slave Address 24 bits Data

(MAC APP) 24 bits Data

Slave Receive Packet: (PHY MAC) 4 bits Unique Identifier (MAC APP) 4 bits Unique Identifier 2 bit Connect/Disconnect 8 bits SlotA/SlotB 2 bit Connect/Disconnect/Resynchronise

Slave Send Packet: (APP MAC) 24 bits Data

28

Wireless Sensor Protocol (MAC PHY) 24 bits Data 4 bit

Haroon Mustafa Khan

Unique Identifier

As is evident from above, each packet type in the MAC layer contains vital information required for the succession of a TDD scheme. The Unique Identifier is a 4-bit word which is kept constant throughout a transmission cycle. This allows accurate communication protocols for the piconet as it ensures the slave node checks whether it is running by schedule. At the completion of a cycle, the Unique Identifier is incremented in the master node for the next batch of data.

6.2.3

Physical Layer

The Physical Layer (PHY) basically deals with the radio link between the master and the slave node. It involves receiving and transmitting of data as well as the encoding and decoding of data. It is also responsible for maintaining the radio link and providing an interface with the radio module. As it is the layer responsible for receiving packets, it uses data whitening and CRC check methods to ensure the best quality communication. Data whitening is a procedure white scrambles the packet, in order to randomise the data from highly redundant patterns and to minimise DC bias packets. While a CRC scheme provides a checking mechanism for error detection. For this project we are not required to operate in the 2.4 GHz ISM and hence we are using 433MHz as the nRF401 transceiver performs at this rate. Table 6.2 shows some characteristics of the nRF401 chip which have been discussed.

Parameters Frequency

nRF401 433MHz

29

Wireless Sensor Protocol

Haroon Mustafa Khan

Modulation Symbol Rate Symbol Transmit Period

FSK 20 kbps 50s

Table 6.2 - nRF401 characteristics For a greater understanding of this WSP layer one must refer to Volume III in this thesis.

6.3

System Hierarchy

Now that the reader has been given an in-depth overview of each layer in the protocol and the packet format used, the entire system at a whole needs to be looked at more closely. Figure 6.4 provides a good representation of the architecture.

ECG

Master
Application

Slave
Application

Medium Access Control

Medium Access Control

Physical

Physical

Air link Figure 6.4 - Entire system hierarchy The initial start-up of the system is performed in the APP layer of the master node. The GUI which is created in Visual C++ will prompt the user on initialising

30

Wireless Sensor Protocol

Haroon Mustafa Khan

the wireless connection. This will in turn pass information via a UART to the Nios Softcore Processor which contains both the MAC layer and the PHY layer. The MAC layer will establish the link and setup the transmission using the TDD scheme. A packet containing information on the Piconet Management is passed onto the PHY Layer. Here decoding of the message and the creating of transmission packets is executed, before finally sending the data through the transceiver. The slave nodes transceiver receives the packet and passes it onto the baseband processor (PIC 16F876). Decoding of the message is done in the PHY layer and then the information is passed onto the MAC layer. The MAC layer first checks to see if it is a valid packet from the master, if so, then it resets the clock and realises the transmission slot time. A query is then passed onto the APP layer, which begins sampling ECG data and storing it into Flash in the microprocessor. While data is being sampled, the MAC layer is aware of time before next transmission is required. Just prior to transmission time, the MAC layer changes the mode of the transceiver to transmit mode. The MAC layer then extracts a sample of ECG data and passes it onto the PHY layer. This information is once again formatted and created into a packet to be sent back across to the master node. Finally, the information is received and yet again passed through the particular layers until it reaches the PHY layer. Once the PHY layer has received substantial information from the nodes in the piconet, it then is able to create the ECG signal on the PC.

31

Baseband Processor

Haroon Mustafa Khan

Chapter 7 Baseband Processor


The decision on which types of processors to incorporate into a design project is a very important step. With so many processors to choose from this task becomes even more complicated. However it was decided early that the PIC family range for typical 8 bit processors would be suitable for the designated use. This is mainly due to the availability of the chip as well as the large range of software development tools available. Furthermore, the Nios softcore processor was employed, to portray the digital aspects of the design.

7.1

PIC 16F876

This 28-pin microcontroller is a powerful yet easy to program CMOS Flashbased 8-bit microcontroller.
[17]

Its instructions require an acceptably low 200

nanoseconds, making it ideal for the Wireless ECG design. However the paramount aspect of this chip which is useful for our design is its 10 bit ADC, as this reduces the need for an additional chip to perform this function of digitising ECG data. Therefore this chip was used as the baseband processor to handle our transmission link (PHY, MAC), and an additional PIC876 was used to extract ECG data (APP layer). Figure 7.1 shows a basic pin diagram of the processor, while the peripheral features of this chip are displayed in Table 7.1.

32

Baseband Processor

Haroon Mustafa Khan

Figure 7.1 - Pin Diagram of the PICF876 [18] This section will detail the main features used in the PICF876 microcontroller, namely the I/O Pins and the Timer. The entire code for the PIC (slave.c) is available in Appendix A.

Key Features Operating Frequency Flash Program Memory (14 bit words) Data Memory (bytes) EEPROM Data Memory Interrupts I/O Ports Timers

Value DC 20 MHz 8K 368 256 13 22 3

Table 7.1 - PICF876 Microcontroller Core Features [18]

7.2.1

I/O Pins

Four I/O pins were needed for a full implementation of our Wireless ECG design, including a transmitting and receiving pin, a transceiver mode select pin and an input pin to retrieve ECG data from the amplifier. Initially, a further output I/O pin was used for debugging, which was later connected to a LED to provide an interface to the system. Table 7.2 shows our pin allocation in regards to the I/O pins.

33

Baseband Processor

Haroon Mustafa Khan

Name TX RX TXEN Debug / LED

Direction Output Input Output Output

Pin RB7 RB0 RB6 RB5

Table 7.2 PICF876 Pin allocation Receiving of data was implemented using the interrupt driven pin RB0. When a logic high is received by the transceiver, it will request the receive interrupt routine. This routine will then check the remainder of the packet to ensure it is of correct packet format.

7.2.2

Timer

The PIC F876 has three timers available, which includes two 8-bit counters (timer0, timer2) and one 16 bit counter (timer1). Two of these are incorporated into our slave node design for the MAC and PHY layer. The rate at which these timers perform at, is dependant on the value of the input clock. To meet the requirement of low power usage, a 3.6864 MHz crystal was used. Table 7.3 shows the functions of each of the two timers used. The clock value for the timers was initialised by setting the prescaler and the clock register.

Timer timer0 timer1

Function Time required before next packet sent Receiving of transceiver data Table 7.3 - Timing Functions of PICF876 (MAC, PHY)

34

Baseband Processor

Haroon Mustafa Khan

7.2

Nios Softcore Processor

The Nios technology which acts as the Wireless ECG master node is a softcore processor, meaning that Hardware Description Language (HDL) is employed to instigate the hardware of the design. The Altera Excalibur board (shown in Figure 7.2) contains the Nios Softcore Processor which is an advances and integrated solution for creating embedded processor applications. HDL code can easily be compiled and programmed into the Field Programmable Analog Array (FPGA), which contains a large logic gate capacity and the ability to reconfigure.

Figure 7.2 - Altera Excalibur Development Board [2] FPGA devices allow rapid design prototyping. They offer more dense logic and less tedious wiring work than discrete chip designs. Moreover it provides faster turnaround than sea-of-gates, standard cell, or full-custom design fabrication. Such a processor is more flexible than a hardcore processor, due to its superior performance and its relative simplicity in design. [5]

35

Baseband Processor The Altera Excalibur development board contains: APEX EP20K200E programmable device 8 Mbit (512K 16) of internal Flash RAM Two 1 Mbit (64K 16) of internal SRAM RS232 communication port JTAG port, Parallel Port, Multiple Expansion Port Two LEDs Two 7 Segment displays More switches and components

Haroon Mustafa Khan

[3]

The NIOS development board is a fairly complicated device in that both hardware and software are core pieces to the board. Fortunately the documentation provided by Altera, allow easy implementation of the Wireless ECG Design. All documents found are listed in the Bibliography section of this document [1-3].

7.2.1

Embedded System Hardware Design

The Embedded system hardware was designed to demonstrate the interface between the software and hardware. The main development program for this board is Quartus II which is used to integrate Verilog/VHDL files, schematics and numerous others. Also contained within the program is the powerful MegaWizard program which is used to create Nios processor variations, as well as smaller logic components falling under the categories of arithmetic, gates and storage. Leonardo Spectrum is also used to read a design from Verilog, VHDL, EDIF source files and perform RTL (Register-Transfer-Level) synthesis, constraint-based optimisation and timing analysis. [5] The 32 bit Nios processor design for the Wireless ECG Project is shown in Figure 7.3. A 32 bit processor was preferred ahead of a smaller 16 bit processor due to certain shortcomings which were evident in the 16 bit design, in

36

Baseband Processor

Haroon Mustafa Khan

particular with downloading master software onto Flash to initialise code to run every time power is switched on.

Figure 7.3 - Embedded Hardware Design A description of the Wireless ECG Nios System created is shown in Table 7.4 below. The system clock frequency is 33.333 MHz provided by an onboard oscillator. Another clock is used to utilise the phase locked loop circuitry on the board so the user can create their own clock.

Module Name CPU UART ROM Flash SRAM LCD Display timer0, timer1, timer2

Description Standard 32 bit Nios 2.1 CPU Debug UART used for downloading and execution of code 32 bit Boot Monitor ROM Nios 32 default Flash Memory Nios 32 default SRAM 11 bit output for display on external LCD screen Standard interval timers, writable/readable period, Start/Stop control bits

37

Baseband Processor

Haroon Mustafa Khan

nRF_RX, nRF_TX, nRF_TXEN, nRF_CS, LED_test1 LED_test2, LED_test3

Input I/O Receive pin, Rising edge triggered, Generates IRQ 6 standard output pins used for transmission, transceiver mode, chip select and debugging/LED.

Table 7.4 - Wireless ECG 32 bit Nios Design The onboard SRAM and Flash memory are used to store data and program memory respectively. Once the core is booted up, the firmware stored in flash will be transferred to the SRAM and will automatically execute saving execution time of the code. This is because it is easier to access SRAM than it is Flash. [7]

7.2.2

Software

The software program written for the Nios Implementation is located in Appendix B for reference. Named master.c, it contains the implementation for both the PHY and MAC layer of the Master node The code is structured fairly similar to that of the slave node as it controls the same WSP layers. However the major difference is the procedure in which I/O pins and timers are utilised. Furthermore the method of creating interrupts is also dissimilar. To initialise a I/O pin, a declaration of a np_pio structure is required. Then the pio needs to be assigned to the particular I/O pin, as shown below for the LED output pin (Figure 7.4)

np_pio ledout1 = na_LED_test_1; ledout1->np_piodata = 0;

/* declaration of ledout1 */ /* sets the output to low */

Figure 7.4 - Snippet code for setting LED output to low To create any sort of interrupt, such as for a timer, the interrupt service routine (ISR) needs to be installed into the interrupt vector table using the

38

Baseband Processor

Haroon Mustafa Khan

nr_installuserisr() function. This requires the irq no. (defined in header file) and the function to be run when the interrupt is triggered. After this is complete, the timer control bits need to be set to allow for interrupts and continuous countdown. Each of these variable can easily be implemented using predefined masks available. An example of the implementation for creating a timer interrupt is shown in Figure 7.5.

np_timer *clk1 = na_timer1;

/* declaration of clk1*/

nr_installuserisr(na_timer1_irq, clk1_ISR,(int)clk1); /* setup interrupt */ clk2->np_timerperiodl = 0x33330; clk2->np_timerperiodh = 0; /* 1 ms */

clk2->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; /* Start interrupt */

Figure 7.5 Snippet code for creating timer interrupt The Nios technology was straightforward and easy to use. Furthermore, the results which were obtained from the Softcore processor were quite significant. Several aspects of the design were more accurate and less tedious. As an example, the interrupt routines were not complicated and the timers were more precise compared to that of the PIC. However the most useful aspect of the Nios Softcore which makes it ideal for complex system debugging is the UART. By using printf statements in the code, the Nios softcore is a god-send for hardware programmers.

39

Operating System

Haroon Mustafa Khan

Chapter 8 Operating System


The core challenge we face is to meet the requirements of the network sensor protocol explained in the previous section in a structured design. This involves using the baseband processor to implement all layers in the stack using a tiny micro-threading operating system. An operating system is an essential part of any design. This section will briefly describe the Berkley TinyOS system which was used in the Smart Dust sensor explained in section 3.4. The Wireless ECG design uses the basic hypothesis of the TinyOS idea to generate a simple yet more relevant operating system.

8.1

Berkley TinyOS

The TinyOS [10] design provides an ideal solution to be integrated in a networked system. Since it was created in 1999, it has attracted immense attention for its simplicity and effectiveness. The initial Berkley design involved the creating of a very basic operating system called a TinyOS, on an ATMEL chip. The design was created for the Smart Dust project which was a prototype for a minute optical communicating sensor. This operating system fits into a very small and reasonable 178 bytes of memory. Although the sensor involved in this design was used to measure temperature and light it provides an ideal method of creating an operating system which could be incorporate in most conventional sensor design. The TinyOS uses an extremely efficient multithreading engine, where it maintains a two-level scheduling structure, so some of the processing associated with hardware events can be executed immediately. Furthermore, it uses an event model that allows for high concurrency to be handled in a very small amount of space.

40

Operating System

Haroon Mustafa Khan

However the greatest advantage of this design is that the CPU resources are used efficiently, due to the fact that the TinyOS uses an event-based operating system. No blocking or polling is permitted, thus allowing a collection of tasks associated with an event to be handled rapidly. These great advances in this field lay a foundation for further architectural advances.

8.2

WSPOS

To manage an effective operating system design, it is vital to create an effective platform for the entire system. The Wireless Sensor Protocol Operating System (WSPOS) uses the concepts described above by creating a thread and using a kernel First In First Out (FIFO) method to handle the threads in the queue. A thread is formed by creating a struct, which contains an id and an array of data_length. The id is used to determine the thread command which is being referred to, while the data_length array is the information passed, relating to that particular thread. For example, to create a thread for sending a packet, you would first set the id number to that of the send_message thread. Then the packet data to be sent would be put in the struct data_length array. It is important to note here than not every thread needs to have data, but an identifier is always required. To make computation basic and easy to follow, a create_thread routine is shaped. When this method is called with a thread, it puts that thread in the kernel queue. Similarly, a thread_to_do routine is used to remove a thread from the kernel and perform the particular task. Flowcharts of these two commands are shown in Figure 8.1.

41

Operating System

Haroon Mustafa Khan

Create thread

Thread to do

Place thread id onto Queue

Extract first thread id to be done off Queue

Place data onto Queue

Extract data From first thread

No

Entire data placed


Yes

Entire data placed

Increment Index to Thread

Increment Current Thread

End

End

Figure 8.1 - create_thread and thread_to_do Routine for Operating System The kernel is basically the main program (consisting of a continuous while loop), responsible for controlling the threads on the queue. As it uses a FIFO scheme, it continuously monitors the index_to_thread and current_thread variables. If these are not equal, then there must be a thread on the queue which needs to be executed. This operating system allows for a simple multi-threading system similar to the one described by TinyOS. The WSPOS uses a minimum amount of program space and is fairly straight-forward and painless to program.

42

Project Evaluation

Haroon Mustafa Khan

Chapter 9 Product Evaluation


This section will detail the performance of the entire designed system with special emphasis on the division executed by the author of the thesis. The results are compared with the objectives clearly set out in Section 1.2. Analysis of the performance and functionality of both hardware and software design are discussed, with an evaluation of the entire system as a whole.

9.1

Design

The design system at the time of submission of this document, consists of a wireless communication system which transfers ECG data from two nodes placed on a patient body to a PC for evaluation. However there are certain shortcomings of the design, some of which are hoped, can be resolved before the demonstration of the product. The intended design was to create every node as a separate node with no wire connection. However as has been described thoroughly in Volume I, this aspect of the design could not be met fully due to its complexity and the noise power evident. Instead the final product consists of two nodes using a third node as a common measuring point. The voltage difference between the node and the common point is then transmitted through the transceiver. However the design of the ECG sensor circuit was successful as can be seen in Figure 9.1 which shows an ECG signal on the PC. Filtering and Compression techniques were used to remove unwanted noise. Also, even though this design uses three nodes connected with wires, two transceivers are still used. Therefore the networking aspect of the design with the WSP stack has been successful.

43

Project Evaluation

Haroon Mustafa Khan

Figure 9.1 Final Result The WSP stack implementation on both the PICF876 and Nios Softcore Processor is functioning properly with the packet format described in section 6.2.2. Furthermore the system has been created using the Operating System (WSPOS) described in chapter 8. This not only provided the platform by which our threads can execute, but it also is very useful in performing the requirements of the WSP. In addition, a similar system was also created without the Operating System (using a state machine type structure). The performance of both systems was equivalent and suitable for the Wireless ECG design; however the WSPOS design was preferred over the standard design as it gave the software more structure. Figure 9.2 shows the Master node including the transceiver and Nios Development board.

44

Project Evaluation

Haroon Mustafa Khan

Figure 9.2 Master Node One of the most complex features of the Wireless ECG design is its TDD scheme. Although this aspect of the design is also functioning, the author is currently working towards improving the throughput. Table 9.1 provides some detail on the current TDD scheme. Cycles before Resynchronisation Data rate Max packet size Time slots Table 9.1 TDD results 6 2 kHz 48 bits 50 ms

9.2

Power

Power consumption forms an important characteristic of the design. Table 9.2 shows a breakdown of power usage throughout the entire slave system.

45

Project Evaluation

Haroon Mustafa Khan

PICF876 for MAC and PHY Layer PICF876 for APP Layer ECG circuitry Total

29 mA 30 mA 12 mA 71 mA

Table 9.2 Power consumption results for slave node

9.3

Cost

Table 9.3 provides a cost breakdown of the Wireless ECG System slave node. Notably, the master node has been not been mentioned in the budget as it consists of a PICF876 and a Nios board which is a development board. It would be ideal to construct a FPGA particularly for this project, to provide an ideal interface to the master node. ECG circuitry PICF876 2 PCB RF Transceiver Miscellaneous Total Table 9.3 Budget for Slave node $40 $40 $10 $11 $10 $111

9.4

Size

The size of the Wireless ECG slave node is acceptable as it can easily be placed on a patient without too much discomfort. Figure 9.3 shows the completed slave node.

46

Project Evaluation

Haroon Mustafa Khan

Figure 9.3 Slave node

47

Future Developments

Haroon Mustafa Khan

Chapter 10 Future Developments


After considering the final Wireless ECG product described in chapter 9, it is evident that future development is still required to achieve our ultimate goal of a complete and efficient wireless sensor system for monitoring ECG of patients. These improvements would demand additional resources and time to implement. This section offers some advice on possible additional features and/or enhancement of the product.

10.1 Timing Issues


Timing issues were one of the more complex aspects of the design as well as being one of the difficult ones to debug. The throughput of the Wireless ECG system is a poor one and is currently still in improvement stage. The main reasons for the slow data rate include: Microcontroller not able to accurately handle faster rate RF transceiver limitations on noise Long delays in TDD scheme

The 8 bit PICF876 used in the design employs a 3.6864MHz crystal. This slower rate crystal was used, over say a 40 MHz crystal mainly due to power constraints required for the system. Other processors may provide the solution for more accurate and faster data communication and hence additional work is recommended in this area. In addition prototyping of the Nordic RF transceiver showed that it too could only handle slower data rates, and if increased, information was lost. Therefore supplementary work is required on the transceiver where in future one may

48

Future Developments

Haroon Mustafa Khan

need to consider looking at different transceivers or changing component values for better tuning. To prevent clashing of different nodes on the TDD scheme, it was decided that a delay was required after each packet was sent, to ensure all corresponding nodes have received the data and have changed into their respective transmission modes. This caused a significant reduction in the throughput of the wireless design. While the Wireless ECG project team is still currently working on enhancements to this aspect of the design, there may be other alternatives which could be dwelled on in future, such as an acknowledgement scheme.

10.2 WSP
As explained, currently the system has no sort of acknowledgement scheme. When a master sets up communication with a piconet, it basically assumes that each slave node has received its packet. This initial phase is an important part of the TDD scheme as it determines the slot times for each slave. Hence if such a packet is missed by the slave node, the six packets sent between synchronisation will be lost almost certainly, and as the master needs data from both nodes to plot ECG data, a significant portion of the ECG reading could be blank. By incorporating an acknowledgement scheme such as a handshake, it would ensure that the communication link has been setup correctly and improve the overall design. Also, if another Wireless ECG system was introduced to an area near or surrounding the piconet, the communication scheme would almost certainly go haywire. When taking the design into consideration, this prototype version was never intended to form a scatternet system as that shown in figure 5.1. If however such a system was implemented, it would provide an ideal network in a hospital where patients could move between wards and still have their ECG

49

Future Developments

Haroon Mustafa Khan

monitored. To put into operation such a concept, some alterations would be required to the WSP Stack Layers, in particular the MAC layer.

50

Conclusion

Haroon Mustafa Khan

Chapter 11 Conclusion
With technology advances being seen all around us in our every day life, it is extremely important to use such technology for the benefit of the community at large. Monitoring of a patients heart condition is presently being achieved by a system using several cables wired to specific points on the patients body to produce an ECG signal. This thesis provides the documentation of the design and implementation which was necessary to create the Wireless ECG Design. This provides an alternative to the current system, as it reduces cables making manoeuvring unproblematic for patients. It demonstrates a set of protocols WSP, which can easily be incorporated in most other wireless sensor protocol. Furthermore the operating system designed, provides an ideal queuing system for a baseband processor. The current state of the project should not be looked at, as a final product, but merely as a promising platform by which to maintain enhancements within the design. With a continuation of the current design, the proposed end product is very realistic and attainable.

51

Reference

Haroon Mustafa Khan

Reference
[1] Altera Corporation, Nios Embedded Processor: Programmers

Reference Manual, Altera Corporation, San Jose C.A., 2001 [2] Altera Corporation, Nios Tutorial, Altera Corporation, San Jose C.A., 2001 [3] Altera Corporation, Nios Embedded Processor: Peripherals Reference Manual, Altera Corporation, San Jose C.A., 2001 [4] Bravo-Escos, M., Networking gets personal, IEE Review , Volume: 48 Issue: 1 , Jan. 2002, Page(s): 32 -36 [5] Collier, R.J., Using the Excalibur Development Board, Polytechnic State University Thesis, 2002 [6] Deeply Networked Systems Mote Documentation and Development Information, http://www.cs.berkeley.edu/~awoo/smartdust/ [Last accessed: 24/4/02] [7] DSouza M., Embedded Bluetooth Stack Implementation With Nios Softcore Processor, University of Queensland Thesis, 2001 [8] DSouza M., Wireless Biomedical Sensor Project Outline, School of Information Technology and Electrical Engineering, 2002 [9] Hatashida, J., Evaluation of a Network Co-processing Architecture, California Polytechnic State University Thesis, 2002 California

52

Reference

Haroon Mustafa Khan

[10] Hill J., Szewczyk R., Woo A., Hollar S., Culler D., Pister K., System Architecture Directions for Networked Sensors, University of California, 2000 [11] Hsu V., Kahn J.M., Pister K.S.J., Wireless Communications for Smart Dust, Electronics Research Laboratory Technical Memorandum Number M98/2, February, 1998. [12] Jordan, R.; Abdallah, C.T., Wireless communications and networking: an overview, IEEE Antennas and Propagation Magazine , Volume: 44 Issue: 1 , Feb. 2002 , Page(s): 185 -193 [13] Kahn J.M., Katz R.H., Pister K.S.J., Mobile Networking for Smart Dust, ACM/IEEE Intl. Conf. on Mobile Computing and Networking (MobiCom 99), Seattle, WA, August 17-19, 1999. [14] Kostelnik R., Lacko P., Perdoch M., Torork T., Ziegler J., BlueMedica: Wireless Medical Data Access Appliance, Slovak University of Technology, 2001 [15] Madden, S. Szewczyk, R. Franklin, M.J. Culler, D., Supporting aggregate queries over ad-hoc wireless sensor networks, California Univ., Berkeley, CA, USA. Mobile Computing Systems and Applications. IEEE Workshop, Page(s): 49 58, June 2002 [16] Marr D., ECG Application Featuring Data Transmission by Bluetooth, University of Queensland Thesis, 2001 [17] Microchip Graphic Explorer - Parent Tab PIC16F876 Device, http://www.microchip.com/1010/pline/picmicro/category/embctrl/14kbyt es/devices/16f876/index.htm [Last accessed: 20/8/2002]

53

Reference

Haroon Mustafa Khan

[18] Microchip, PIC16F87X Data Sheet, Microchip Technology Inc. 2001 [19] Pister K.S.J., Kahn J.M., Boser B.E., Smart Dust: Wireless Networks of Millimeter-Scale Sensor Nodes, Highlight Article, 1999 Electronics Research Laboratory Research Summary. [20] Sgroi, M. da Silva, J.L., Jr. De Bernardinis, F. Burghardt, F. Sangiovanni-Vincentelli, A. Rabaey, J., Designing wireless protocols: methodology and applications, California University, Acoustics, 2000 IEEE International Conference, Volume 6, Page(s): 3726 - 3729 [21] The Official Bluetooth Wireless Info Site, http://www.bluetooth.com/ [Last accessed: 13/5/2002] [22] Vasudevan N., The BlueNurse Wireless Link, University of Queensland Thesis, 2001 [23] Venkat Bahl, ZigBee and Bluetooth Competitive or Complementary? Zigbee Alliance, 2002 [24] Venkat Bahl, ZigBee Overview, Zigbee Alliance, 2002 [25] Ventracor: The heart accessed: 18/9/02] [26] Wei-Shin Wang, Bluetooth: a new era of connectivity, IEEE Microwave Magazine , Volume: 3 Issue: 3 , Sept. 2002, Page(s): 38 -42 [27] ZigBee Alliance, http://www.zigbee.org/ [Last accessed: 13/5/2002] company, http://www.ventracor.com/ [Last

54

Appendix A

Haroon Mustafa Khan

Appendix A Slave Code


/* * * TITLE: slave.c * * TOPIC: Wireless ECG * * METHOD: This program contains the code for the slave node. * * WRITTEN BY: Haroon Khan & Bhavik Kant * * DATE: 21/9/02 */

#include <pic.h> #define XTAL_FREQ 4MHZ __CONFIG(0x3d71); #define BITNUM(adr, bit) static static static static #define #define #define #define #define #define #define #define #define #define #define bit bit bit bit ((unsigned)(&adr)*8+(bit))

nRF_DOUT @ BITNUM(PORTB, 7); nRF_RXEN @ BITNUM(PORTB, 6); nRF_CS @ BITNUM(PORTB, 5); nRF_DIN @ BITNUM(PORTB, 0); '1' 1 0x0A 0x05 + SLAVE_NUM 0xAA 0x4A /* can't be larger than 0b01111111 */ 0xB3 3 /* no. of bytes */ 2 /* no. of bytes */ 8 8 0 /* Determines if we are the MASTER or SLAVE device */

S_NUM SLAVE_NUM MASTER_ADDR MYADDRESS PREAMBLE DW_INITIALISATION_BYTE CRC_INITIALISATION_BYTE DATA_PAYLOAD_LENGTH SYNCHRO_LENGTH DATA_LENGTH THREAD_LENGTH

#define MASTER

/* * variables for receiving data */ unsigned char rx_byte; unsigned char rx_no_of_shifts; unsigned char lookup_value [] = {0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1}; unsigned char no_of_samples; unsigned char current_bit; unsigned char samples; unsigned char rx_index_to_message = 0; unsigned char no_of_packets_to_receive; /* number of bytes to receive excluding preamble */ unsigned char preamble_received = 0; /* * variables for transmitting data */ unsigned char transmission_packet_length; unsigned char tx_no_of_shifts; unsigned char tx_index_to_message = 0; unsigned char tx_no_of_trasmissions = 0; /* * variables to keep track of states */ bank1 unsigned char delay; bank1 unsigned char state; bank1 unsigned char stage = 0;

bank2 unsigned char transmission_packet [DATA_LENGTH]; bank2 unsigned char packet_received [DATA_LENGTH]; bank2 unsigned char slot_type; bank2 unsigned char data_length []

= {SYNCHRO_LENGTH, DATA_PAYLOAD_LENGTH}; /* where on array we are */ /* which one we are processing */

bank2 volatile unsigned char index_to_thread = 0; bank2 volatile unsigned char current_thread = 0; bank3 volatile static struct threads {

55

Appendix A

Haroon Mustafa Khan

unsigned char id; unsigned char data[DATA_LENGTH]; };

typedef struct threads threads; typedef void OS_Command; typedef void OS_Event; bank3 volatile static threads thread [THREAD_LENGTH];

/* * Prototypes of functions used. */ /* * initialising interrupts */ OS_Command init_external(void); OS_Command init_timer0(void); OS_Command init_timer1(unsigned int tmr1, unsigned char prescaler); OS_Command init_timer1_m(unsigned int tmr1, unsigned char prescaler); OS_Command init_uart(unsigned char baud_rate); /* * for thread maintainence */ OS_Command create_thread (threads latest_thread); threads thread_to_do (void); /* * routines for transmitting */ OS_Command CRC_generate(void); OS_Command create_packet_structure(void); OS_Command data_whiten(void); OS_Command send_message(void); /* * routines for receiving */ OS_Command intialise_receive(void); OS_Command data_whiten(void); OS_Command create_packet_structure(void); OS_Command CRC_generate(void); OS_Command format_packet_to_receive(void); OS_Command error_occured(void); /* * ISR */ OS_Event nRF_Transmit_data(void); OS_Event nRF_Receive_data(void);

/* * implemented as an OS */ void main (void) { unsigned char currentID; current_thread = index_to_thread;

TRISB = 0x01; PORTB = 0; nRF_DOUT = 0; nRF_RXEN = 1; nRF_CS = 1; state = 0; delay = 0; init_uart(11); init_external();

/* all outputs except RB0 */

/* Dout */ /* /txen */ /* /cs */

//* 19.2k baud */

/* * initialise for slave node to receive */ thread[index_to_thread].id = 41; index_to_thread++; index_to_thread = index_to_thread % THREAD_LENGTH;

while (1) { /* * thread on queue which needs to be taken care of */ if (current_thread != index_to_thread) { currentID = thread[current_thread].id; switch (currentID) {

56

Appendix A

Haroon Mustafa Khan

/* * Transmit Routines */ case 21: CRC_generate(); break; case 22: create_packet_structure(); break; case 23: data_whiten(); break; case 24: send_message(); break; /* * Receive Routines */ case 41: intialise_receive(); break; case 42: data_whiten(); break; case 43: create_packet_structure(); break; case 44: CRC_generate(); break; case 45: format_packet_to_receive(); break; case 46: routine to handle bad packets */ error_occured(); break; } } } }

/* gives control to physical layer */

/*

void interrupt isr(void) { if (state == 0) { /* * If external interrupt occurs, resynch. */ if (INTF == 1) { INTF = 0; /* clear flag */ no_of_samples = 1; T0IF = 0; TMR0 = 202; /* 198; */ init_timer0(); /* resynchronize timer */ if (INTEDG == 1) { samples = 0x01; INTEDG = 0; } else { samples = 0; INTEDG = 1; } RB2 = RB2^1; } /* * If timer interrupt occurs, read port b. */ else if (T0IF == 1) { T0IF = 0; TMR0 = 202; nRF_Receive_data(); RB2 = RB2^1; } } /* test */

/* test */

else if (state == 1) { /* * transmit data */ if (T0IF == 1) {

/* (T0IE == 1) */

57

Appendix A

Haroon Mustafa Khan

T0IF = 0; TMR0 = 40; if (tx_index_to_message == transmission_packet_length) { nRF_DOUT = 0; delay++; if (delay == 2) { RB4 = RB4^1; T0IE = 0; delay = 0; tx_no_of_trasmissions++; INTE = 0; T0IE = 0; nRF_RXEN = 1; state = 2; if (tx_no_of_trasmissions == 6) { stage = 2;

/* * time before changing to rx mode */ if (SLAVE_NUM == 1) { init_timer1(0x9400, 4); RB3 = RB3^1; /* * time before changing to rx mode - 60ms */ } else if (SLAVE_NUM == 2) { init_timer1(0x2800, 1); /* * time before changing to rx mode - 90ms */ } else if (SLAVE_NUM == 3) { init_timer1(0xFE00, 1); } } else { stage = 0; } } } else { nRF_Transmit_data(); } } }

else if (TMR1IF == 1) { TMR1IF = 0; switch (stage) { case 0: /* in rx mode.... change to tx */ nRF_RXEN = 0; stage = 5; INTE = 0; T0IE = 0; init_timer1(0xFC67, 1); break; case 5: nRF_DOUT = 1; init_timer1(0xFE34, 1); stage = 6; break; case 6: nRF_DOUT = 0; init_timer1(0xFC67, 1); stage = 1; break; case 1: slot_type = 1; thread[index_to_thread].id = 21; /* * sample data */ thread[index_to_thread].data[0] = thread[index_to_thread].data[1] = thread[index_to_thread].data[2] = thread[index_to_thread].data[3] = index_to_thread++; index_to_thread = index_to_thread break; case 2: /* in tx mode.... change to rx */ RB3 = RB3^1;

/* disable synch receive */ /* RX to TX - 1ms */

/* RX to TX - 0.5ms */

/* RX to TX - 1ms */

/* send data */

1; /* S_NUM;/* 'o'; /* '3'; /*

packet type - ECG data */ 1st data packets */ 2nd data packets */ 3rd data packets */

% THREAD_LENGTH;

58

Appendix A

Haroon Mustafa Khan

nRF_RXEN = 1; stage = 3; init_timer1(0xF532, 1); */ break; case 3: TMR1IE INTE = T0IF = INTF = = 0; 1; 0; 0;

/* TX to RX - 3ms

/* * receive resycnh data */ slot_type = 0; no_of_packets_to_receive = data_length[slot_type] + 2; state = 0; no_of_samples = 0; samples = 0; rx_byte = 0; preamble_received = 0; rx_index_to_message = 0; rx_no_of_shifts = 0; init_external(); break; } }

OS_Command init_external(void) { INTEDG = 1; /* rising edge */ INTF = 0; INTE = 1; }

OS_Command init_timer0(void) { T0SE = 0; T0CS = 0; PSA = 0; PS2 = 0; /* prescalar 1:2 000 */ PS1 = 0; PS0 = 0; T0IE = 1; }

OS_Command init_timer1(unsigned int tmr1, unsigned char prescaler) { T1CON = 1; switch (prescaler) { case 8: T1CKPS1 = 1; T1CKPS0 = 1; break; case 4: T1CKPS1 = 1; T1CKPS0 = 0; break; case 2: T1CKPS1 = 0; T1CKPS0 = 1; break; case 1: T1CKPS1 = 0; T1CKPS0 = 0; break; } TMR1H = tmr1 >> 8; TMR1L = tmr1; TMR1IF = 0; TMR1IE = 1; } /* TMR1ON is 1 */

/* prescalar 1:8 */

/* prescalar 1:4 */

/* prescalar 1:2 */

/* prescalar 1:1 */

/* high byte */ /* low byte */

OS_Command init_timer1_m(unsigned int tmr1, unsigned char prescaler) { T1CON = 1; switch (prescaler) { case 8: T1CKPS1 = 1; T1CKPS0 = 1; break; case 4: T1CKPS1 = 1; /* TMR1ON is 1 */

/* prescalar 1:8 */

/* prescalar 1:4 */

59

Appendix A

Haroon Mustafa Khan

T1CKPS0 = 0; break; case 2: T1CKPS1 = 0; T1CKPS0 = 1; break; case 1: T1CKPS1 = 0; T1CKPS0 = 0; break; } TMR1H = tmr1 >> 8; TMR1L = tmr1; TMR1IF = 0; TMR1IE = 1; } /* high byte */ /* low byte */ /* prescalar 1:1 */ /* prescalar 1:2 */

OS_Command init_uart(unsigned char baud_rate) { SPBRG = baud_rate; SYNC = 0; BRGH = 1; SPEN = 1; CREN = 1; TXIE = 0; RCIE = 0; TXEN = 1; RCIF = 0; TRISC = 0xFF; GIE = 1; PEIE = 1; }

/* * method creates a thread - FIFO */ OS_Command create_thread (threads latest_thread) { unsigned char i; /* * put thread into queue */ thread[index_to_thread].id = latest_thread.id; for (i=0; i<DATA_LENGTH; i++) { thread[index_to_thread].data[i] = latest_thread.data[i]; } index_to_thread++; index_to_thread = index_to_thread % THREAD_LENGTH; }

/* * extracts first thread to be done - FIFO */ threads thread_to_do (void) { unsigned char i; threads readthread;

readthread.id = thread[current_thread].id; /* take thread of queue */ for (i=0; i<DATA_LENGTH; i++) { readthread.data[i] = thread[current_thread].data[i]; } current_thread++; current_thread = current_thread % THREAD_LENGTH; return readthread; } /* * ID = 21 (TX) and ID = 44 (RX) * 8 bit crc check - g(x) = x^8 + x^2 + x^1 + 1 * TX data - pkt type, data * RX data - header&address, data, CRC code */ OS_Command CRC_generate(void) { unsigned char i, j, bit0, bit5, bit6, bit7, CRC_LSFR, scrambled_bit, mess, message_length;

threads thread_to_process = thread_to_do();

/* take thread of queue */

message_length = data_length[slot_type]; */

/* determine message_length = number of bytes to process

/* * NB - MAC will also send packet type in data field */

60

Appendix A

Haroon Mustafa Khan

CRC_LSFR = CRC_INITIALISATION_BYTE; for (i=message_length; i>0; i--) { mess = thread_to_process.data[i]; for (j=0; j<8; j++) { bit0 = CRC_LSFR & 0x01; scrambled_bit = (bit0 ^ mess) & 0x01; mess = mess >> 1; bit6 = (CRC_LSFR & 0x40) >> 6; bit7 = (CRC_LSFR & 0x80) >> 7; CRC_LSFR = CRC_LSFR >> 1; bit5 = (scrambled_bit ^ bit6) << 5; bit6 = (scrambled_bit ^ bit7) << 6; bit7 = scrambled_bit << 7;

/* initialise LSFR - NB-using 8 bit LSFR */ /* skip data[0] */

/* scroll through entire byte */

CRC_LSFR = CRC_LSFR & 0x1F; CRC_LSFR = CRC_LSFR | bit5 | bit6 | bit7; } } if (thread_to_process.id == 21) { /* we are transmitting this packet */ /* * CRC code generated is in CRC_LSFR */ thread_to_process.data[message_length+1] = CRC_LSFR; /* * TX data - pkt type, data, CRC code */ thread_to_process.id = 22; /* create packet structure */ } else if (thread_to_process.id == 44) { if (CRC_LSFR == thread_to_process.data[message_length+1]) { /* * RX data - header&address, data, CRC code */ thread_to_process.id = 45; /* format packet to receive */ } else { /* invalid packet */ thread_to_process.id = 46; /* incorrect packet */ } } /* * create the thread */ create_thread(thread_to_process); }

/* * ID = 22 * TX data * RX data */ OS_Command {

(TX), ID = 43 (RX) - pkt type, data, CRC code - header&address, data, CRC code create_packet_structure(void) unsigned char address, header, M_S, pkt_type;

threads thread_to_process = thread_to_do();

/* take thread of queue */

if (thread_to_process.id == 22) { /* we are transmitting this packet */ /* * format the packet that needs to be DW - everything except preamble */ M_S = MASTER << 7; pkt_type = thread_to_process.data[0] << 5; address = MYADDRESS & 0x0F; header = (M_S | pkt_type) & 0xF0; /* M_S, pak_type */ /* * format packet to be sent */ thread_to_process.data [0] = header | address; /* * TX data - header&address, data, CRC code */ thread_to_process.id = 23; /* data whiten the packet to send */ } else if (thread_to_process.id == 43) { header = thread_to_process.data[0] & 0xF0; M_S = header >> 7; pkt_type = (header >> 5) & 0x03; address = thread_to_process.data[0] & 0x0F; if ( (M_S == 1) && (MASTER == 0) ) { if (pkt_type == 0) { /* /* we are receiving this packet */

/* ie. got from master and we are slave */

61

Appendix A

Haroon Mustafa Khan

* RX data - header&address, data, CRC code */ thread_to_process.id = 44; /* CRC check */ } } else if ( (M_S == 1) && (MASTER == 1) ) { /* ie. got from master and we are master */ thread_to_process.id = 46; // incorrect packet } else if ( (M_S == 0) && (MASTER == 1) ) { /* ie. got from slave and we are master */ /* * RX data - header&address, data, CRC code */ if (pkt_type == 1) { /* check if ECG data */ thread_to_process.id = 44; /* CRC check */ } } else { /* got from slave and we are slave */ thread_to_process.id = 46; /* incorrect packet */ } } /* * create the thread */ create_thread(thread_to_process); }

/* * ID = 23 (TX), ID = 42 (RX) * LSB first * TX data - header&address, data, CRC code * RX data - (header&address, data, CRC code) - all of which is been data whitened */ OS_Command data_whiten(void) { unsigned char DW_LSFR; unsigned char i, j, bit0, bit0a, bit3, bit2, bit6, scrambled_bit, scrambled_byte, message_byte, messa; unsigned char dw_length;

threads thread_to_process = thread_to_do();

/* take thread of queue */

/* * determing dw_length = no. of bytes which need to be whitened/de-whitened */ dw_length = data_length[slot_type] + 2; DW_LSFR = DW_INITIALISATION_BYTE; for (i=dw_length; i>0; i--) { message_byte = thread_to_process.data[i-1]; scrambled_byte = 0; for (j=0; j<8; j++) { /* scroll through entire byte */ /* initialise LSFR - NB-dealing with 7 bit LSFR */

bit0 = DW_LSFR & 0x01; bit0a = bit0 << 7; messa = message_byte << 7; scrambled_bit = (bit0a ^ messa) & 0x80; scrambled_byte = scrambled_byte >> 1; scrambled_byte = scrambled_byte | scrambled_bit; message_byte = message_byte >> 1; bit3 = (DW_LSFR & 0x08) >> 3; bit6 = bit0 << 6; bit2 = (bit0 ^ bit3) << 2; DW_LSFR = DW_LSFR >> 1; DW_LSFR = DW_LSFR & 0xBB; DW_LSFR = DW_LSFR | bit6 | bit2; } thread_to_process.data[i-1] = scrambled_byte; } /* * TX data - header&address, data, CRC code - all of which has been data whitened * RX data - header&address, data, CRC code */ if (thread_to_process.id == 23) { thread_to_process.id = 24; /* format packet to send */ } else if (thread_to_process.id == 42) { thread_to_process.id = 43; /* create packet structure */ } /* * create the thread */ create_thread(thread_to_process); } /* * ID = 24

62

Appendix A

Haroon Mustafa Khan

* TX data - (header&address, data, CRC code) - all of which has been data whitened */ OS_Command send_message(void) { unsigned char i, datalength; threads thread_to_process = thread_to_do(); datalength = data_length[slot_type] + 2; /* take thread of queue */ /* determine datalength = number of bytes to process */ /*

for (i=datalength; i>0; i--) { format packet to be sent */ thread_to_process.data[i] = thread_to_process.data[i-1]; } thread_to_process.data [0] = PREAMBLE; /* * TX data - preamble, (header&address, data, CRC code) whitened */ transmission_packet_length = data_length[slot_type] + 3; for (i=0; i<transmission_packet_length; i++) { transmission_packet[i] = thread_to_process.data[i]; } state = 1; T0IF = 0; TMR0 = 0; init_timer0(); tx_index_to_message = 0; tx_no_of_shifts = 7; init_timer1_m(0x5E00, 4); }

/* initate timer */

/* time before next transmission - 30*2*3ms = 180ms */

/* * ID = 41 */ OS_Command intialise_receive(void) { threads thread_to_process = thread_to_do(); slot_type = 0; no_of_packets_to_receive = data_length[slot_type] + 2;/* excluding preamble */ state = 0; no_of_samples = 0; samples = 0; rx_byte = 0; preamble_received = 0; /* initialise to receive preamble first */ rx_index_to_message = 0; rx_no_of_shifts = 0; init_external(); } /* take thread of queue */

/* * ID = 45 * RX data - header&address, data, CRC code */ OS_Command format_packet_to_receive (void) { unsigned char i, datalength, pkt_type, TXaddress; threads thread_to_process = thread_to_do(); datalength = data_length[slot_type]; pkt_type = (thread_to_process.data[0] >> 5) & 0x03; TXaddress = thread_to_process.data[0] & 0x0F; for (i=datalength; i>0; i--) { thread_to_process.data[i+1] = thread_to_process.data[i]; } thread_to_process.data[0] = pkt_type; thread_to_process.data[1] = TXaddress; /* * testing */ while (TRMT == 0); TXREG = '*'; i = 2; while (i < 4) { if (TRMT == 1) { TXREG = thread_to_process.data[i]; i++; } } /* take thread of queue */

63

Appendix A

Haroon Mustafa Khan

while (TRMT == 0); TXREG = '*'; /* * RX data - packet type, senders address, data */ if ((pkt_type == 0) && (TXaddress == MASTER_ADDR)) { /* * initiate time to send data! */ state = 2; stage = 0; tx_no_of_trasmissions = 0; if (SLAVE_NUM == 1) { init_timer1_m(0x9400, 1); /* initial delay - 30ms */ } else if (SLAVE_NUM == 2) { init_timer1_m(0xAA00, 4); /* initial delay - 30ms + 60ms = 90ms */ } else if (SLAVE_NUM == 3) { init_timer1_m(0x7900, 4); /* initial delay - 30ms + 60ms + 60 = 150ms } } }

*/

/* * ID = 46 * when errors occur in the packet receieved - CRC fails or from wrong person! */ OS_Command error_occured (void) { threads thread_to_process = thread_to_do(); /* take thread of queue */ /* * flash a LED to indicate we have an in the packet received error!! */ while (TRMT == 0); TXREG = 'e'; /* * initialise for slave node to receive */ thread[index_to_thread].id = 41; index_to_thread++; index_to_thread = index_to_thread % THREAD_LENGTH; }

OS_Event nRF_Transmit_data(void) { unsigned char message, bit_to_transmit; message = transmission_packet[tx_index_to_message]; bit_to_transmit = message >> tx_no_of_shifts; if (tx_no_of_shifts == 0) { tx_no_of_shifts = 8; tx_index_to_message++; } tx_no_of_shifts--; nRF_DOUT = bit_to_transmit; } /* send the bit - DOUT for transceiver */

OS_Event nRF_Receive_data(void) { unsigned char i; no_of_samples++; samples = samples << 1; samples = samples | nRF_DIN; if (no_of_samples == 3) { no_of_samples = 0; current_bit = lookup_value[samples]; samples = samples & 0x01; rx_byte = rx_byte << 1; rx_byte = rx_byte | current_bit; if (preamble_received == 0) { if (rx_byte == 0xAA) { rx_byte = 0; tx_no_of_shifts = 0; rx_index_to_message = 0; preamble_received = 1; } }

64

Appendix A

Haroon Mustafa Khan

else { rx_no_of_shifts++; if (rx_no_of_shifts == 8) { /* have received entire byte! */ packet_received[rx_index_to_message] = rx_byte; rx_index_to_message++; rx_no_of_shifts = 0; rx_byte = 0; if (rx_index_to_message == no_of_packets_to_receive) { preamble_received = 0; rx_index_to_message = 0; /* * put thread into queue */ thread[index_to_thread].id = 42; /* de-whiten packet */ for (i=0; i<no_of_packets_to_receive; i++) { thread[index_to_thread].data[i] = packet_received[i]; } index_to_thread++; index_to_thread = index_to_thread % THREAD_LENGTH; /* * RX data - (header&address, data, CRC) whitened */ INTE INTF T0IE T0IF } } } } } = = = = 0; 0; 0; 0;

65

Appendix B

Haroon Mustafa Khan

Appendix B Master Code


/* * * TITLE: master.c * * TOPIC: Wireless ECG * * METHOD: This program contains the code for the master node. * * WRITTEN BY: Haroon Khan & Bhavik Kant * * DATE: 21/9/02 */ #include <stdio.h> #include "nios.h"

#define #define #define #define #define #define

MYADDRESS PREAMBLE DW_INITIALISATION_BYTE CRC_INITIALISATION_BYTE DATA_PAYLOAD_LENGTH SYNCHRO_LENGTH

0x0A 0xAA 0x4A 0xB3 3 2 8 8 1

/* can't be larger than 0b01111111 */ /* no. of bytes */ /* no. of bytes */

#define DATA_LENGTH #define THREAD_LENGTH #define MASTER

/* Determines if we are the MASTER or SLAVE device */

/* * variables for receiving data */ volatile unsigned char rx_byte; volatile unsigned char rx_no_of_shifts; unsigned char lookup_value [] = {0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1}; volatile unsigned char no_of_samples; unsigned char current_bit; volatile unsigned char samples; volatile unsigned char rx_index_to_message = 0; unsigned char no_of_packets_to_receive; /* number of bytes to receive excluding preamble */ volatile unsigned char preamble_received = 0; /* * variables for transmitting data */ unsigned char transmission_packet_length; unsigned char tx_no_of_shifts; unsigned char tx_index_to_message = 0; unsigned char tx_no_of_trasmissions = 0; /* * variables to keep track of states */ unsigned char stage = 0;

unsigned char transmission_packet [DATA_LENGTH]; unsigned char packet_received [DATA_LENGTH]; unsigned char slot_type; unsigned char data_length []

= {SYNCHRO_LENGTH, DATA_PAYLOAD_LENGTH}; = 0; = 0; /* where on array we are */ /* which one we are processing */

volatile unsigned char index_to_thread volatile unsigned char current_thread volatile static struct threads { unsigned char id; unsigned char data[DATA_LENGTH]; };

typedef struct threads threads; typedef void OS_Command; typedef void OS_Event; volatile static threads thread [THREAD_LENGTH];

unsigned char state1, state2, state3; unsigned int shit = 0;

66

Appendix B

Haroon Mustafa Khan

/* * Prototypes of functions used. */ /* * initialising interrupts */ OS_Command init_timer0(void); OS_Command init_timer1(void); /* * for thread maintainence */ OS_Command create_thread (threads latest_thread); threads thread_to_do (void); /* * routines for transmitting */ OS_Command CRC_generate(void); OS_Command create_packet_structure(void); OS_Command data_whiten(void); OS_Command send_message(void); /* * routines for receiving */ OS_Command intialise_receive(void); OS_Command data_whiten(void); OS_Command create_packet_structure(void); OS_Command CRC_generate(void); OS_Command format_packet_to_receive(void); OS_Command error_occured(void); /* * ISR */ OS_Event OS_Event OS_Event OS_Event

clk1_ISR (int context); clk2_ISR (int context); clk0_ISR (int context); ext_ISR (int context);

OS_Event spurious_ISR (int context); OS_Event radio_tx(void); OS_Event radio_rx(void);

np_pio *ledout1 = na_LED_test_1; np_pio *ledout2 = na_LED_test_2; np_pio *ledout3 = na_LED_test_3; np_pio np_pio np_pio np_pio *rxen = na_nRF_TXEN; *din = na_nRF_RX; *dout = na_nRF_TX; *cs = na_nRF_CS;

np_timer *clk1 = na_timer1; np_timer *clk2 = na_timer2; np_timer *clk0 = na_timer0;

np_uart *pc_uart = na_uart2_debug;

int main(void) { unsigned char currentID; /* * Initialize timer0 interrupts - used for oversampling */ nr_installuserisr(na_timer0_irq, clk0_ISR,(int)clk0); clk0->np_timerstatus = 0; clk0->np_timercontrol = 0; /* * Initialize for timer1 interrupts - used for transmission */ nr_installuserisr(na_timer1_irq, clk1_ISR,(int)clk1); clk1->np_timerstatus = 0; clk1->np_timercontrol = 0; /* * Initialize timer2 interrupts - used for TDD scheme */ nr_installuserisr(na_timer2_irq, clk2_ISR,(int)clk2); clk2->np_timerstatus = 0; clk2->np_timerperiodl = 0xC254; clk2->np_timerperiodh = 0x01C9; clk2->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask;

/* * external interrupts - used for to synchronise for oversampling */ nr_installuserisr(na_nRF_RX_irq, ext_ISR,(int)na_nRF_RX); din->np_piointerruptmask = 1;

67

Appendix B

Haroon Mustafa Khan

/* * for spurious interrupts */ nr_installuserisr(na_uart2_debug_irq, spurious_ISR,(int)pc_uart); pc_uart->np_uartstatus = 0; pc_uart->np_uartcontrol = 0; /* disable rx interrupts */

stage = 0; dout->np_piodata = 0; rxen->np_piodata = 0; cs->np_piodata = 1; state1 = 0; state2 = 0; state3 = 0; ledout1->np_piodata = 0; ledout2->np_piodata = 0; ledout3->np_piodata = 0;

/* ouput data to low */ /* transmit mode */ /* channel 0 */

/* * print to screen */ printf("\n\nNow running Master node of WSP -> ECG.\n\n"); /* * print to LCD */ nr_pio_lcdinit(na_lcd_pio); nr_pio_lcdwritescreen("Master Node of current_thread = index_to_thread; while (1) { shit++; if (current_thread != index_to_thread) { of */ currentID = thread[current_thread].id; switch (currentID) { /* * Transmit Routines */ case 21: /* gives controll to physical layer */ CRC_generate(); break; case 22: create_packet_structure(); break; case 23: data_whiten(); break; case 24: send_message(); break; /* * this state gives controll to MAC layer when finished transmitting */ /* * Receive Routines */ case 41: intialise_receive(); break; case 42: data_whiten(); break; case 43: create_packet_structure(); break; case 44: CRC_generate(); break; case 45: format_packet_to_receive(); break; /* * this state gives controll to MAC layer to receive the data */ case 46: /* routine to handle bad packets */ error_occured(); break; } } } return 1; } /* thread on queue which needs to be taken care

WSP -> ECG");

68

Appendix B

Haroon Mustafa Khan

void spurious_ISR (int context) { printf(" :Spurious Interrupt!: "); pc_uart->np_uartstatus = 0; }

OS_Event clk2_ISR (int context) { clk2->np_timerstatus = 0; switch (stage) { case 0:

/* clear flag */

/* change from rx to tx mode */

din->np_piointerruptmask = 0; /* disable external interrupts */ clk1->np_timercontrol = 0; clk0->np_timercontrol = 0; rxen->np_piodata = 0; stage = 5; clk2->np_timerperiodl = 33330;/* delay for RX to TX - 1ms */ clk2->np_timerperiodh = 0; clk2->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; break; case 5: dout->np_piodata = 1; stage = 6; clk2->np_timerperiodl = 33330/2; clk2->np_timerperiodh = 0; clk2->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; break; case 6: dout->np_piodata = 0; stage = 1; clk2->np_timerperiodl = 33330; clk2->np_timerperiodh = 0; clk2->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; break; /* can send packet now */ clk2->np_timercontrol = 0; /* disable timer interrupts */ slot_type = 0; thread[index_to_thread].id = 21; /* * sample data */ thread[index_to_thread].data[0] = thread[index_to_thread].data[1] = thread[index_to_thread].data[2] = index_to_thread++; index_to_thread = index_to_thread break; case 2:

case 1:

0; 'm'; 'p';

/* packet type - resynch data /* 1st data packets */ /* 2nd data packets */

*/

% THREAD_LENGTH;

/* change from tx to rx mode */ rxen->np_piodata = 1; stage = 3; clk2->np_timerperiodl = 0x8696; /* delay TX to RX - 3ms */ clk2->np_timerperiodh = 0x0001; clk2->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; break; /* * can receive packet now and delay for next synchro packet */ din->np_piointerruptmask = 1; /* enable external interrupts to allow to receive data*/ /* * need to delay before */ clk2->np_timerperiodl = clk2->np_timerperiodh = clk2->np_timercontrol =

case 3:

next synch packet - 1.5secs 0xEE8C; 0x02FA; np_timercontrol_ito_mask + np_timercontrol_start_mask;

/* * initialise for slave node */ thread[index_to_thread].id = 41; index_to_thread++; index_to_thread = index_to_thread % THREAD_LENGTH; stage = 0; break; } state3 = ~state3; ledout3->np_piodata = state3; }

/* * method creates a thread - FIFO */ OS_Command create_thread (threads latest_thread)

69

Appendix B

Haroon Mustafa Khan

{ unsigned char i; /* * put thread into queue */ thread[index_to_thread].id = latest_thread.id; for (i=0; i<DATA_LENGTH; i++) { thread[index_to_thread].data[i] = latest_thread.data[i]; } index_to_thread++; index_to_thread = index_to_thread % THREAD_LENGTH; }

/* * extracts first thread to be done - FIFO */ threads thread_to_do (void) { unsigned char i; threads readthread; /* * take thread of queue */ readthread.id = thread[current_thread].id; for (i=0; i<DATA_LENGTH; i++) { readthread.data[i] = thread[current_thread].data[i]; } current_thread++; current_thread = current_thread % THREAD_LENGTH; return readthread; } /* * ID = 21 (TX) and ID = 44 (RX) * 8 bit crc check - g(x) = x^8 + x^2 + x^1 + 1 * TX data - pkt type, data * RX data - header&address, data, CRC code * OS_Command CRC_generate(void) */ { unsigned char i, j, bit0, bit5, bit6, bit7, CRC_LSFR, scrambled_bit, mess, message_length; /* * take thread of queue */ threads thread_to_process = thread_to_do(); /* * determine message_length = number of bytes to process */ message_length = data_length[slot_type]; /* * NB - MAC will also send packet type in data field.... make sure this is at the beginning */ CRC_LSFR = CRC_INITIALISATION_BYTE; for (i=message_length; i>0; i--) { /* initialise LSFR - NB-using 8 bit LSFR */ /* skip data[0] */

mess = thread_to_process.data[i]; for (j=0; j<8; j++) { /* scroll through entire byte */

bit0 = CRC_LSFR & 0x01; scrambled_bit = (bit0 ^ mess) & 0x01; mess = mess >> 1; bit6 = (CRC_LSFR & 0x40) >> 6; bit7 = (CRC_LSFR & 0x80) >> 7; CRC_LSFR = CRC_LSFR >> 1; bit5 = (scrambled_bit ^ bit6) << 5; bit6 = (scrambled_bit ^ bit7) << 6; bit7 = scrambled_bit << 7; CRC_LSFR = CRC_LSFR & 0x1F; CRC_LSFR = CRC_LSFR | bit5 | bit6 | bit7; } } if (thread_to_process.id == 21) { /* we are transmitting this packet */ /* * CRC code generated is in CRC_LSFR */ thread_to_process.data[message_length+1] = CRC_LSFR; /* * TX data - pkt type, data, CRC code */ thread_to_process.id = 22; /* create packet structure */ }

70

Appendix B

Haroon Mustafa Khan

else if (thread_to_process.id == 44) { /* ie. valid packet */ if (CRC_LSFR == thread_to_process.data[message_length+1]) { /* * RX data - header&address, data, CRC code */ thread_to_process.id = 45; /* format packet to receive */ } else { /* invalid packet */ thread_to_process.id = 46; /* incorrect packet */ } } // create the thread create_thread(thread_to_process); }

/* * * * * */ {

ID = 22 (TX), ID = 43 (RX) TX data - pkt type, data, CRC code RX data - header&address, data, CRC code OS_Command create_packet_structure(void)

unsigned char address, header, M_S, pkt_type; /* * take thread of queue */ threads thread_to_process = thread_to_do(); if (thread_to_process.id == 22) { /* we are transmitting this packet */ /* * format the packet that needs to be DW - everything except preamble */ M_S = MASTER << 7; pkt_type = thread_to_process.data[0] << 5; address = MYADDRESS & 0x0F; /* * M_S, pak_type, ....might want to put sequence no. as well */ header = (M_S | pkt_type) & 0xF0; /* * format packet to be sent */ thread_to_process.data [0] = header | address; /* * TX data - header&address, data, CRC code */ thread_to_process.id = 23; } else if (thread_to_process.id == 43) { header = thread_to_process.data[0] & 0xF0; M_S = header >> 7; pkt_type = (header >> 5) & 0x03; address = thread_to_process.data[0] & 0x0F; /* we are receiving this packet */

/* data whiten the packet to send */

if ( (M_S == 0) && (MASTER == 1) ) { /* ie. got from slave and we are master */ /* * RX data - header&address, data, CRC code */ if (pkt_type == 1) { /* check if ECG data */ thread_to_process.id = 44; /* correct sender */ } } } /* * create the thread */ create_thread(thread_to_process); } /* * ID = 23 (TX), ID = 42 (RX) * LSB first * TX data - header&address, data, CRC code * RX data - (header&address, data, CRC code) - all of which is been data whitened */ OS_Command data_whiten(void) { unsigned char DW_LSFR; unsigned char i, j, bit0, bit0a, bit3, bit2, bit6, scrambled_bit, scrambled_byte, message_byte, messa; unsigned char dw_length; /* * take thread of queue */ threads thread_to_process = thread_to_do(); /* * determing dw_length = no. of bytes which need to be whitened/de-whitened */ dw_length = data_length[slot_type] + 2; DW_LSFR = DW_INITIALISATION_BYTE; /* initialise LSFR - NB-dealing with 7 bit LSFR */

71

Appendix B

Haroon Mustafa Khan

for (i=dw_length; i>0; i--) { message_byte = thread_to_process.data[i-1]; scrambled_byte = 0; for (j=0; j<8; j++) { /* scroll through entire byte */

bit0 = DW_LSFR & 0x01; bit0a = bit0 << 7; messa = message_byte << 7; scrambled_bit = (bit0a ^ messa) & 0x80; scrambled_byte = scrambled_byte >> 1; scrambled_byte = scrambled_byte | scrambled_bit; message_byte = message_byte >> 1; bit3 = (DW_LSFR & 0x08) >> 3; bit6 = bit0 << 6; bit2 = (bit0 ^ bit3) << 2; DW_LSFR = DW_LSFR >> 1; DW_LSFR = DW_LSFR & 0xBB; DW_LSFR = DW_LSFR | bit6 | bit2; } thread_to_process.data[i-1] = scrambled_byte; } /* * work out what thread needs to be created */ if (thread_to_process.id == 23) { thread_to_process.id = 24; } else if (thread_to_process.id == 42) { thread_to_process.id = 43; } /* * create the thread */ create_thread(thread_to_process); } /* * ID = 24 * TX data - (header&address, data, CRC code) - all of which has been data whitened */ OS_Command send_message(void) { unsigned char i, datalength; threads thread_to_process = thread_to_do(); datalength = data_length[slot_type] + 2; /* take thread of queue */ /* determine datalength = number of bytes to process */

/* format packet to send */

/* create packet structure */

for (i=datalength; i>0; i--) { /* format packet to be sent */ thread_to_process.data[i] = thread_to_process.data[i-1]; } thread_to_process.data [0] = PREAMBLE; /* * TX data - preamble, (header&address, data, CRC code) whitened */ transmission_packet_length = data_length[slot_type] + 3; /* including preamble */ for (i=0; i<transmission_packet_length; i++) { transmission_packet[i] = thread_to_process.data[i];/* contains the packet that needs to be sent */ } init_timer1(); tx_index_to_message = 0; tx_no_of_shifts = 7; /* initate timer */

} /* * ID = 41 */ OS_Command intialise_receive(void) { threads thread_to_process = thread_to_do(); slot_type = 1; no_of_packets_to_receive = data_length[slot_type] + 2; no_of_samples = 0; samples = 0; rx_byte = 0; preamble_received = 0; /* initialise to receive preamble first */ din->np_piointerruptmask = 1; } /* excluding preamble */ /* take thread of queue */

/* enable external interrupts for receive */

72

Appendix B

Haroon Mustafa Khan

/* * ID = 45 * RX data - header&address, data, CRC code */ OS_Command format_packet_to_receive (void) { unsigned char i, datalength, pkt_type, TXaddress; threads thread_to_process = thread_to_do(); datalength = data_length[slot_type]; pkt_type = (thread_to_process.data[0] >> 5) & 0x03; TXaddress = thread_to_process.data[0] & 0x0F; for (i=datalength; i>0; i--) { thread_to_process.data[i+1] = thread_to_process.data[i]; } thread_to_process.data[0] = pkt_type; thread_to_process.data[1] = TXaddress; printf("Data Received: *%s*\t", thread_to_process.data); } /* * ID = 46 * when errors occur in the packet receieved - CRC fails or from wrong person! */ OS_Command error_occured (void) { threads thread_to_process = thread_to_do(); /* take thread of queue */ printf("\nError!\n"); } /* testing */ /* take thread off queue */

OS_Command init_timer1(void) { clk1->np_timerstatus = 0; clk1->np_timerperiodl = 16670; clk1->np_timerperiodh = 0; clk1->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; }

OS_Event clk1_ISR (int context) { clk1->np_timerstatus = 0; /* clear the irq condition */ clk1->np_timerperiodl = 16670; /* 16650 - works from 16670 to 19500 */ clk1->np_timerperiodh = 0; clk1->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; if (tx_index_to_message == transmission_packet_length) { clk1->np_timercontrol = 0; dout->np_piodata = 0; /* * create timer 2 interrupt to change modes */ clk2->np_timerstatus = 0; clk2->np_timerperiodl = 33340; /* 16670x2 */ clk2->np_timerperiodh = 0; clk2->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; stage = 2; } else { radio_tx(); } state2 = ~state2; ledout2->np_piodata = state2; }

OS_Event radio_tx(void) { unsigned char message, bit_to_transmit; message = transmission_packet[tx_index_to_message]; bit_to_transmit = message >> tx_no_of_shifts; if (tx_no_of_shifts == 0) { tx_no_of_shifts = 8; tx_index_to_message++; } tx_no_of_shifts--; dout->np_piodata = bit_to_transmit; } /* DOUT for transceiver */

73

Appendix B

Haroon Mustafa Khan

void init_timer0(void) { clk0->np_timerstatus = 0; clk0->np_timerperiodl = 5800; /* 16670/3 */ clk0->np_timerperiodh = 0; clk0->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; }

OS_Event clk0_ISR (int context) { clk0->np_timerstatus = 0; /* clear the irq condition */ clk0->np_timerperiodl = 5800; /* 16670/3 */ clk0->np_timerperiodh = 0; clk0->np_timercontrol = np_timercontrol_ito_mask + np_timercontrol_start_mask; radio_rx(); state1 = state1 ^ 1; ledout1->np_piodata = state1; }

OS_Event ext_ISR (int context) { din->np_pioedgecapture = 0; no_of_samples = 1; samples = 0x01; init_timer0(); state1 = ~state1; ledout1->np_piodata = state1; }

/* clear the irq condition */

/* initate timer */

OS_Event radio_rx(void) { unsigned char i; threads thread_to_process; no_of_samples++; samples = samples << 1; samples = samples | din->np_piodata; if (no_of_samples == 3) { no_of_samples = 0; current_bit = lookup_value[samples]; samples = samples & 0x01; rx_byte = rx_byte << 1; rx_byte = rx_byte | current_bit; if (preamble_received == 0) { if (rx_byte == 0xAA) { rx_byte = 0; tx_no_of_shifts = 0; rx_index_to_message = 0; preamble_received = 1; } } else { rx_no_of_shifts++; if (rx_no_of_shifts == 8) { /* have received entire byte! */ packet_received[rx_index_to_message] = rx_byte; rx_index_to_message++; rx_no_of_shifts = 0; rx_byte = 0; if (rx_index_to_message == no_of_packets_to_receive) { preamble_received = 0; thread_to_process.id = 42; /* de-whiten packet */ for (i=0; i<no_of_packets_to_receive; i++) { thread_to_process.data[i] = packet_received[i]; } /* * put thread into queue */ thread[index_to_thread] = thread_to_process; index_to_thread++; index_to_thread = index_to_thread % THREAD_LENGTH; /* * RX data - (header&address, data, CRC) whitened */ clk0->np_timercontrol = 0; }

74

Appendix B

Haroon Mustafa Khan

} } } }

75

Das könnte Ihnen auch gefallen