Design of a PC-Based Electrocardiogram (ECG) Recorder as - Internet Appliance

The advancement of medical science contributes towards lengthening the human life expectancy. Therefore the proportion of the elder people in the society is increasing. And taking proper care of these people should, most certainly, be one of the prime responsibilities of the society. ECG is the only way to check the heart condition, and if ECG can be done frequently, then it is easier for the physician to identify a problem from the ECG’s history of a person (it has long been preferred by physicians).


Introduction
The advancement of medical science contributes towards lengthening the human life expectancy.Therefore the proportion of the elder people in the society is increasing.And taking proper care of these people should, most certainly, be one of the prime responsibilities of the society.ECG is the only way to check the heart condition, and if ECG can be done frequently, then it is easier for the physician to identify a problem from the ECG's history of a person (it has long been preferred by physicians).
The importance of ECG as a medical tool has led to the development of various types of ECG recording system.The developed systems vary from a simple ECG recorder that can only monitor the ECG signal to a sophisticated system with computer analysis and database.With the use of the computer, patients can record and save their reliable ECG data by themselves at home.Moreover, the Internet services like e-mail and File Transfer Protocol (FTP) can be used as a communication tool to send the recorded ECG data to the medical center.What they need is an ECG data acquisition system at home, which is easy for recording, viewing and sending the ECG data to the medical center with reliable accuracy.To send the ECG data over Internet, the recorded ECG data should be made into a form suitable for transmission; for example, the size and the fidelity of the ECG data should be taken into consideration.
to work with this system.Besides that, it detects the presence of the heartbeat, calculates the current heartbeat rate and beat-to-beat interval while recording the ECG data in memory.To make a reasonable file size for easy transmission over the Internet, a lossless compression can be performed to the ECG data before it is saved into a file.
Leveraging the growing impact of the Internet on healthcare, this device can be used for cardiac research, cardiac rehabilitation, cardiac activities follow-up (like Arrhythmia and Pacemaker), sports, emergency unit (wireless ECG transfer by wireless Internet) as well as regular cardiac care for improving health.This system can be expand according to the organizational need.A hospital database can be developed where the individual patient will upload their ECG information regularly from home for diagnostic purposes.

Objective
The objectives of this chapter are:


To demonstrate a development process of a portable and reliable system that enables the recording of patient's ECG at home.


To show how to recondition the recorded data that will be suitable for transmission over the Internet and suitable for use in the analysis and measurement of PQRST waves of the patient's ECG.


To show how to develop software that must have the basic functions to get data from the hardware and send through the network.

Background study 2.1 The heart wiring
When the heart is working properly, it is a masterpiece of timed precision, with heart valves opening and closing on cue to prevent backward blood flow.Heart valves, chambers, electrical impulses, coronary arteries and veins all of these must be in perfect working order for the heart to function at its best.

The surface electrodes
The electrodes for surface recording of biopotential are generally made of silver-silver chloride (Ag-AgCl).This disposable foam-pad consists of an Ag-AgCl metal contact button at the top of a hollow column that is filled with a conductive gel.Most bioelectric measurements an interference level of 1 to 10μV peak-to-peak (pp) or less than 1% of the pp value of an ECG, is acceptable.

Interference
The capacitances between the patient, the power lines and ground cause a small interference current to flow through the body.These capacitances cause an interference current of 0.5μA pp to flow from the power supply lines (220V, 50Hz) through the body to ground [9].A typical situation with a mean current of 10nA pp in the wires, mean electrode impedance of 20KΩ and a relative difference electrode impedance of 50%, leads to an unacceptable high interference level of 200µV pp .There are two ways by which a high common mode voltage may cause interference.The first, obvious way is when the common mode rejection ratio of the amplifier is limited.Second, and much more important way a high common mode voltage may cause interference is when there are differences in electrode impedance and input impedance whish convert common mode voltage into a differential input voltage.
There are three situations.


The amplifier common is connected to ground.The amount of interference current Z rl is determined mainly by the capacitance between patient's body and the main power supply (C pow ).In a typical situation (C pow = 3pF, Z rl = 20KΩ) the common mode voltage is an acceptable 10mV pp .


The amplifier common is not connected to ground.The resulting current through the impedance of the electrode-skin interface of the right leg electrode depends on the values C pow, capacitance between body and ground (C body ), capacitance between amplifier common and main power supply (C sup ) and between amplifier common and ground (C iso ).It can be calculated that under typical conditions (Cbody = 300pF, Cpow = 3pF, Zrl = 20KΩ), the common mode voltage will be small, 1mVpp.


In all cases, the common mode voltage can be largely reduced if a driven right leg circuit is added.An extra amplifier drives the patient to the same voltages, as the voltage of the amplifier common mode voltage can be made much smaller this way than the voltage across Z rl .

Data acquisition system
With the analog low-pass filter, high frequency noise and interference can be removed from the signal path prior to the analog-to-digital conversion.Using a sampling frequency (f s ), typically called the Nyquist rate.If there is a portion of the input signal that resides in the frequency domain above f s /2, that portion will fold back into the bandwidth of interest with the amplitude preserved [15].This frequency folding phenomena can be eliminated or significantly reduced by using analog low-pass filter prior to the ADC input.Consequently, this signal will not be aliased into the final sampled output.There are two regions of the analog low-pass filter illustrated in Figure 2. The region to the left is within the bandwidth of DC to f s /2.The second region, which is shaded, illustrates the transition band of the filter.Since this region is greater than f s /2, signals within this frequency band will be aliased into the output of the sampling system.The effects of this error can be minimized by moving the corner frequency of the filter lower than f s /2 or increasing the order of the filter.In both cases, the minimum gain of the filter at f s /2 should be less than the signal-to-noise ratio (SNR) of the sampling system.

Active filters
The active filter offers the advantage of providing isolation between stages [11].This is possible by taking advantage of the high input impedance and low output impedance of the operational amplifier.In all cases, the order of the filter is determined by the number of capacitors at the input and in the feedback loop of the amplifier.The Double Pole, Voltage Controlled Voltage Source is better known as the Sallen-Key filter realization.This filter is configured so the DC gain is positive.In the Sallen-Key Filter realization shown in Figure 4, the DC gain is greater than one.In the realization shown in Figure 5, the DC gain is equal to one.In both cases, the order of the filters is equal to two.The poles of these filters are determined by the resistors and capacitors values of R1, R2, C1 and C2.

Low power design
It is possible to have the system to manage its own power consumption by software control utilizing a microcontroller.Some microcontroller like the PICmicro TM family from Microchip can source up to 20mA of current and provides power to other components.In this case, one can simply connect the Vdd pin of an external component to an input-output (IO) pin of the microcontroller.Currently, most of the op-amps, analog-to-digital converter (ADC), and other devices manufactured today are low powered and therefore can be powered by this technique.Many techniques are used to reduce power consumption in the microcontroller.The most commonly used methods are SLEEP mode and external events.The microcontroller can periodically wake-up from sleep using the Watchdog Timer or external interrupt, execute code and then go back into SLEEP Mode.

Data compression
In these applications, the loss of even a single bit could be catastrophic.In the case of ECG file, it is important to preserve the actual recorded ECG data when transmitting to the physician for later analysis.Thus, the lossless compression technique is more suitable to be used for the compression of ECG data.Huffman codes have the unique prefix attribute, which means they can be correctly decoded despite being variable length.

Heartbeat detection techniques
The recognition of almost all ECG parameters is based on a fixed point identifiable at each cycle.R-peak is suitable for use as the datum point, because it has the largest amplitude and sharpest waveform that can be extracted from ECG.For the detection of R-peak, the amplitude level triggering method is based on the square of the derivative.The high frequency components of an original signal are indicated by differentiating the filtered ECG signal.The reliability of the identification is increased by squaring this differentiated value, which will highlight the high frequency components.After this processing, the R-peak can be detected by determining the known amplitude level as a triggering level.The triggering level can also be adaptively determined.Thus, the value of the triggering level is dependent on the upper values of the ECG signal.The R-wave triggering threshold value can be determined by try and error to find out the most suitable value [19].The value of the triggering threshold can adaptively change with the base line value of the ECG signal.The R-peak can be recognized by determining the squared value that is greater than the R-wave triggering value.The current RR-interval can be calculated by differentiating the previous Rwave time with the current R-wave time and the heartbeat can be calculated by the following formula.

Block diagram of the hardware design
The proposed block diagram of the ECG recorder is shown in Figure 6.Three electrodes were used in the ECG recorder; two electrodes are used to sense the ECG signal and the other one is for noise reduction.The weak ECG signal acquired from electrodes is first amplified by the preamplifier with a gain of about 500 before it is filtered by a 96Hz lowpass filter to eliminate most of the electromagnetic noise.The offset null circuit is to eliminate the DC voltage between the two electrodes.The filtered signal is further amplified to about 1V and the offset of the signal is shifted to 1.25V by another stage of amplifier.It is necessary to shift the signal offset to 1.25V so that all the negative voltage is shifted to positive because the ADC accepts pseudo-differential inputs ranging from 0V to reference voltage of 2.50V.The amplified signal is digitized by a 12-bit ADC sampled at 500 samples per second before it is sent to the microcontroller via 3-wire serial interface.In the block diagram, there is a power supply unit that produces +5V and -5V needed by the analog circuits.The power supply for analog circuit can be shutoff by a control line connected to the microcontroller.Besides that, this unit can detect the battery level and signal the microcontroller in case of battery low.The recorder has an 8-bit microcontroller to control its operations like initializing the ECG recording circle, stop recording, shutdown the circuits when there is no activity and monitor the battery status.It also implements the communication protocol between recorder and the computer.The ECG recorder is physically isolated from the 240V power line using opto-isolator for the safety of the patient.

Amplifier design
The amplification of ECG signal can be divided into two stages, the preamplification stage has a gain of about 500 to improve Common Mode Rejection Ratio (CMRR) and the second stage of amplification has a gain of two to make the overall gain of 1000 that will amplify the signal voltage to about 1.0V so that it is high enough to input to the ADC.The 50 Hz line interference can be sufficiently reduced by having a third electrode connected to the amplifier's common ground, which put the patient's body voltage potential to the amplifier's common voltage.The ECG recorder is optically isolated from the main power line and the amplifier is powered by battery, which delivers very clear voltage supply.DC input voltage of up to 200mV should not result in saturation of the amplifier.The INA118 uses a single external resistor to set gain from 1 to 10000.It is laser trimmed for very low offset voltage (50μV) and high CMRR (110dB at 1000 gain).It operates with power supplies as low as ±1.35V and quiescent current is only 350μA, which is very suitable for battery operation.The INA118 has eight pins which are the positive input pin (V in + ), negative input pin (V in -), positive voltage supply pin (V + ), negative voltage supply pin (V -), output reference pin (Ref), two pins for gain setting (R G ) and output pin (V o ).To set G to 500, In the recorder design, two 51Ω resistors are connected in series between the two R G pins to set the amplifier gain to 491.
The LMC6464 quad Operational Amplifier (OA) from National Semiconductor is used in the second stage of signal amplification.The filtered ECG signal is input to the inverting input of the OA through a 10KΩ resistor and the output is feedback to the inverting input pin by a 20KΩ resistor to set the inverting amplifier gain to two.The offset of the ECG signal is shifted to +1.25V by connecting the non-inverting input of the OA to a +1.25V voltage reference through a 10KΩ resistor.A 20KΩ resistor is then connected between the ground and the non-inverting input to make the amplifier balance.

Filter design
The filtering system for the ECG recorder can be divided into two parts, the low-pass filter and the high-pass filter.The low-pass filter is a second order Butterworth Filter designed to give a cutoff frequency of 96Hz.At this cutoff frequency, most of the electromagnetic noise will be filtered out.The LMC6464 OA is used to build the filter with two resistors and two capacitors connected to form a Sallen-Key configuration as shown in Figure 9.The values of the two resistors were 8.2KΩ and 15KΩ and the values of the two capacitors are 0.1μF and 0.22μF.The calculation of cutoff frequency (f c ) is as follows: The high-pass filter has a cutoff frequency of 0.3Hz to eliminate the DC signal.It was built by using a LMC6464 OA, a 1MΩ resistor and a 0.47μF capacitor to form an integrator circuit.The output of the preamplifier was integrated and connected back to the Ref pin of the INA118.Cutoff frequency calculation for the high-pass filter is given by equation 4.

Electrodes, wires and guarding circuit
The electrode that has been selected for the ECG recorder is the disposable foam electrode.Two electrodes are used to form a single lead pair where one will be placed on the left arm and the other will be placed on the right arm.Another electrode, which is used for noise reduction will be placed on the right leg or hand.The lead wires have to be made short, preferably less than one meter to reduce the electromagnetic interference.The length of the lead wires must be equal so that the difference of impedance in the two lead wires can be minimized.The difference of impedance in the lead wires can cause the potential divider effect, which converts the common mode voltage to differential voltage.The wires used in the ECG recorder were shielded with a single guarding circuit to drive the shield back to common mode voltage.The guarding circuit consists of the LMC6464 OA connected as a uni-gain amplifier.The common mode voltage from the INA118 was input to the noninverting input of the OA and the output was feedback to the inverting input.The high input impedance from the non-inverting input of the OA will isolate the guarding circuit from the IA so that the operation of the IA will not be interrupted. -

Analog to digital converter
The MAX145 ADC from MAXIM Integrated Product was selected in the development of the ECG recorder.It is a serial 12-bit ADC with low power consumption, automatic shutdown and fast wake-up time.It has an internal track-and-hold circuitry eliminating the need for external sample-and-hold amplifier.The reference voltage of 2.5V was used in the ECG recorder to limit the Quantization Noise to 1mV pp .A serial ADC has more complicated data transfer process compared to parallel ADC.However, a serial ADC has been chosen to minimize number of pin used for data transfer because the PIC16F84 microcontroller that is used to control the ADC has limited number of IO pin.In addition, a serial ADC will use up less space to make the recorder compact.The MAX145 pin 2 and pin 3 are pseudodifferential inputs which only accept input signal ranging from zero to a reference voltage set at pin 5, which is 2.5V in the ECG recorder design.The pin 2 of MAX145 is connected to the ground and the analog ECG signal is input to the pin 3 of MAX145.Because MAX145 only accept positive input voltage, the offset of the ECG signal is shifted to 1.25V before it is input to the pin 3 of MAX145.
Only three pins need to be connected to the microcontroller from MAX145, via the pin 7 (DOUT), pin 8 (SCLK) and pin 6 (active low chip select/active high shutdown).Pin 7 and 8 is used for reading out the digitized ECG sample serially and pin 6 is a control pin to activate the analog-to-digital conversion process.The serial data output format for MAX145 is a stream of 16-bit data stream.The first bit must be logic high to indicate the end of conversion.The next three bits must clock out high followed by the 12 bits of data in MSBfirst format.After the last bit has been read out, additional serial clock pulses will clock out trailing zeros.DOUT changes on the falling edge of SCLK.That means the DOUT pin should be sampled when SCLK is high.

Power supply unit
The basic function of the power supply unit is to produce +5V and -5V from a single +4.5V supply from the battery.The MAX681 voltage converter is used to convert +4.5V to both +9V and -9V.It is a monolithic, dual charge-pump converter that provides positive and negative outputs of two times a positive input voltage.The +9V is regulated to +5V by using the MAX666 voltage regulator and the -9V is regulated to -5V by using the MAX664 voltage regulator.With this configuration, the input voltage from the battery can drop to +3V without affecting the output voltage of the power supply unit.This is because MAX681 voltage converter can convert the +3V to +6V for the MAX666 voltage regulator and -6V for the MAX664 voltage regulator.The MAX666 contains on-chip circuitry for low power detection.If the voltage at pin 3 of MAX666 falls below the regulator's internal reference of 1.3V, then pin 7 or the Low Battery Output pin goes low.The threshold for low battery indication can be set by using two external resistors with the values of 2MΩ and 1.2MΩ to form a voltage divider to the supply voltage.The divided voltage is then input to pin 3 of MAX666.The MAX666 can be shutdown by logic input at pin 5.When in Shutdown State, the maximum drain current is limited to 12μA, which is desired for low power design.

Microcontroller
The microcontroller acts as an intelligent unit to perform all the operation of the ECG recorder such as power management, ECG samples data acquisition and implementation of the computer interfacing protocol.Microcontroller selected for the ECG recorder is the PIC16F84 from Microchip Technology Inc.It is a low cost 8-bit microcontroller operating at the speed of 4MHz.The microcontroller has pins connected to the ADC, power supply unit and the opto-isolator.Pin 18 (RA1), pin 1 (RA2) and pin 2 (RA3) of the PIC16F84 microcontroller are connected to the MAX145 ADC.RA1 is the clock output to clock out serial data from the ADC.It is connected to the SCLK pin of the ADC.RA2 is the serial data input pin to receive the serial data from the ADC.It is connected to the DOUT pin of the ADC.RA3 is the chip-select output pin, which will power up the ADC when RA3 is high and shutdown the ADC when RA3 is low.It is connected to the pin 6 of the MAX145 ADC.Pin 3 (RA4) and pin 17 (RA0) are connected to the power supply unit.RA4 is an output pin to power off the analog circuitry and RA0 is the input pin for battery status.Pin 6 (RB0) and pin 7 (RB1) are used for serial data transfer with the computer.RB0 is for receiving data and RB1 is for transmitting data.The flowchart for the microcontroller firmw a r e i s s h o w n i n F i g u r e 1 7 .O n c e t h e microcontroller power is up or being reset, it sets its IO pins direction by setting the internal registers, TRIS A and TRIS B [20].RB0, RA0 and RA2 are set as input pins whereas RB1, RA1, RA3 and RA4 are set as output pins.The microcontroller then set all the output pins' initial state to logic high.
After initialization, it enters the Ready State.The Ready State puts the microcontroller in SLEEP mode and puts the ECG recorder to the lowest power consumption while waiting for the present of data from the computer serial port.Before entering the SLEEP mode, the microcontroller will enable RB0 pin interrupt.
When in SLEEP mode, the microcontroller will eventually wake up by the watchdog timer and go back to SLEEP mode.When a start-bit is detected at RB0 pin, the microcontroller will wake up, send back an "OK" string to the computer and wait for the command string from the computer.It then parses the command to determine whether the computer wants to start recording ECG or wants to check battery status.If the command is not valid, the microcontroller will reset.
In the check battery routine, the microcontroller will check the status of RA0 pin and send back the battery status to the computer.The routine then goes back to Ready State.In the record ECG routine, the microcontroller initializes its internal timer to start the analog-todigital conversion of the ECG signal every two milliseconds.It sends one ECG sample together with the battery status to the computer every two milliseconds.The record ECG routine is designed such that the computer has to send back an acknowledgement byte to the microcontroller before 255 samples of ECG data have been sent to the computer.This is to prevent the recording process to run continuously without knowing whether the computer is receiving the ECG data.The recording process will stop and go back to SLEEP mode if there is no acknowledgement received from the computer after 255 samples have been sent to the computer.

Opto-isolator
The H11L1 opto-isolator is used to isolate the ECG recorder from the 240V power line.It has an infrared emitting diode optically coupled to a high-speed integrated detector with Schmitt trigger output.The H11L1 can isolate maximum peak voltage of 7500V before the isolation breaks down.For the ECG recorder, two H11L1 opto-isolators are used to isolate the transmit data and receive data lines for the serial port.With the use of opto-isolator, there will be no electrical path connecting the patient and the computer, which is then connected to the 240V power line.

RS-232 transceiver to USB
The RS-232 transceiver is used to convert the TTL level logic at the ECG recorder to RS-232 level logic at the serial comport and vice versa.The MAX3232 low-power RS-232 transceiver is used in the ECG recorder.It requires four 0.1μF external capacitors to operate and typical supply current of only 300μA.The low power consumption of this component makes it possible to be powered by the RTS line of the computer serial port.This part cannot be powered by the battery because it is not isolated from the 240V power line by the optoisolator.

Communication protocol between computer and ECG recorder
The ECG recorder is interfaced to the computer via RS-232 port with the setting of 19200 baud, 8 bit data, no parity bit and one stop bit.To activate the ECG recorder, the computer has to send a set of commands to the ECG recorder.The communication starts with a function call from the computer software either to get the battery status of the ECG recorder or to start a recording process.
-Set all ouput pin to High.
-Set interrupt on f alling edge.
-En t e r SL EEP mo d e .
-Wait for command string -Parse the command string

Valid command?
What is the command?

Check status routine:
-Check the value at RA0 pin.
-Send status to the computer.

Record routine:
-Initialize timer to overflow every 2ms.
-Send back digital data to computer.

Interrupt at RB0
No Yes "REC" "STA" To get the battery status of the ECG recorder, the computer will first send a one-byte data with hexadecimal value of '0xAA' to wakeup the ECG recorder.Upon receiving the one byte data, the ECG recorder will wakeup from sleep, power up the analog circuit and send back an "OK" string to indicate that it is now ready to receive a command from the computer.The command format begins with one byte of 'SOH' ASCII character and then followed by three letters string.To get the battery status, the letter string is "STA".When the ECG recorder receives a 'SOH' followed by a "STA" string, it will check the battery status and send back the battery status to the computer.It first sends a "SOH" byte followed by the status byte, which is an ASCII letter 'L' if battery level is low and an ASCII letter 'H' if battery level is normal.After sending the status byte to the computer, the ECG recorder goes back to sleep mode.To start the ECG recording process, the computer sends a byte with value '0xAA' to the recorder.Then the ECG recorder wakes up from sleep, power up the analog circuit and sends back an "OK" string to the computer.The computer then sends a 'SOH' byte followed by a "REC" string command to the ECG recorder.When the ECG recorder receive the "REC" string command, it will initiate the ECG recording process and send back a 'SOH' byte to the computer to signal that the ECG samples are coming.Then it sends a sequence of ECG sample to the computer, two bytes of data per sample.Before the ECG recorder has sent 255 samples, the computer must send a byte with hexadecimal value '0xff' to the ECG recorder to continue the recording process.Otherwise, the ECG recorder will stop recording and go back to sleep mode.The communication protocol is illustrated by Figure 15.

Software design
The software design part involves the design of multiple functioning objects and the design of data flow between them [21,22].The functions and data structures of several main objects in the ECG software are described in the following sections.The algorithms used in the compression of ECG data and heartbeat detection are described in the Data Compression Unit and the Heartbeat Detection Unit.

Data flow diagram
The data flow diagram in Figure 20 shows the flow of information between different objects and variables for the ECG recorder software.The object can be hardware, Graphic User Interface (GUI), file on disk, variable in the program memory or running thread.The information can be in the form of command or variable passed from one object to another.
The GUI objects are objects that interact with the user.They are the objects that the user can see in the main window or as a dialog box.The GUI objects in the data flow diagram together with their description are listed in the Table 1.The recording process is initiated by the user from the Record Bar.When a Start Recording command is received by the CECGRecorder object, it will start the Record Thread.The Record Thread then activates the appropriate serial port and start sending and receiving serial data from the ECG recorder hardware.The Record Thread will decode the serial data into digital samples of ECG signal and the battery status.The ECG samples are then appended to the TempSampleArray, an instance of CWordArr that represents ECG signal in the memory.The battery status will be stored in a variable that later will be used to update the battery status display at the Record Bar.While the TempSampleArray represents the recording ECG signal in the memory, Record View displays it in graphical form.The Record View constantly reads the TempSampleArray and updates its display so that the user will see the real-time signal.Meanwhile, another thread, the Heartbeat Detection Unit will examine the recording signal to check whether a heartbeat is present in the signal.If a heartbeat is detected, the thread then calculates the current heartbeat rate and updates the Info Bar.

GUI object Description
Record Bar This is the control panel for the ECG recorder to start or stop the ECG recording process.It displays the battery status of the ECG recorder, the start time and the time elapsed.
Info Bar Displays the heartbeat rate and the RR-interval.It also displays animation when a heartbeat is detected by the program.

Record View
Displays the real-time graph of the ECG signal when the recording process is running.

ECG View
Displays the recorded ECG signal or the ECG document in a graph.This object enables the user to scroll through the whole ECG document by a Scroll Bar.It also enables the ECG signal to be zoomed to 5 different sizes.

Setup Dialog
This dialog box is for the user to set the name of serial port where the ECG recorder hardware has been connected.Besides that, the user can also set the patient's information here.
Table 1.Description for the GUI Objects When the recording process is stopped by the user, a new CECGDoc object will be created.The TempSampleArray will be copied to another instance of CWordArr class, which is the SampleArray and the patient information from the setup data will be copied to the member variable of the CECGDoc.The CECGDoc object represents the recorded ECG signal in the memory.It includes every detail of the recorded ECG such as the record time, the length of the recorded ECG and information of the patient, to whom the ECG belongs.The CECGDoc is graphically displayed by the CECGView.In the CECGView, one can see everything in the CECGDoc.It includes five types of zoom view to view the recorded ECG signal in different sizes.The zoom size of the CECGView can be controlled by the user in Tool Bar or in program menu.The CECGDoc can be saved on a disk as an ECG file.Actually, the patient information and the SampleArray are saved to the file when a CECGDoc is saved.The patient information is saved directly to the ECG file while the SampleArray will be compressed first before it is saved to the ECG file.The Data Compression Unit is responsible to compress and decompress the SampleArray.

Main frame window
The main frame window is the main display for the ECG software that is showed when the program starts.Like other standard window program, it has a main menu, toolbar, status bar, minimize box, maximize box and close box.It is a Multiple Document Interface (MDI) frame, which may contain several child frames so that two or more ECG files can be viewed at the same time.If the main frame window is closed, the program will also be terminated.

CECGRecorder class and the recording thread
CECGRecorder is a class that abstractly represents the ECG recorder in the ECG software.
This class provides all the functions to control the ECG recorder hardware.All the low-level protocols to communicate with the hardware are automatically handled here.To use the CECGRecorder class, one must call the Activate function first and pass two arguments with it.One argument is strings to specify the name of serial port that connects to the recorder hardware, and the other argument is a pointer to the data structure to store the ECG samples when recording ECG.The member functions of this class are listed in the Table 2.

Member Function Description
BatteryStatus Method to return the battery status of the ECG recorder hardware.

StartRecord
Method to start the record thread.

StopRecord
Method to stop the record thread.

IsRecording
Method to check whether the record thread is running.

Activate
Method to activate the CECGRecorder.

DeActivate
Method to deactivate the CECGRecorder.

IsActivated
Method to check whether the CECGRecorder is activated.

HardwareAvailable
Method to check whether the recorder hardware is still connecting to the activated comport.
Table 2. Member Function for CECGRecorder Class

Data structure of the ECG signal
CWordArr Class represents the ECG signal in the program memory.It is a thread-safe array, which enables multiple threads to add data to it and get data from it at the same time without blocking each other.Each element of the CWordArr consists of 16-bit word, which manages to hold a 12-bit ECG sample.An ECG sample can only be added to the top of the CWordArr so that the position of ECG samples in the CWordArr will follow exactly like the ECG signal.When reading from the CWordArr, ECG sample in the CWordArr can be read out at any position and will not be deleted from the CWordArr.It is designed to be like this so that multiple threads can read out ECG sample in the CWordArr at different position simultaneously.Beside adding and reading ECG sample, the CWordArr class includes method to get the length of the ECG sample.

Data compression unit
The Data Compression Unit compresses the SampleArray into a compressed data stream before it is saved to a file.The compression process is divided into two steps.First, the ECG samples stored in the 16-bit array are converted to a stream of 12-bit ECG samples stored in CByteArray.In this step, no compression is actually done except to eliminate the redundant bits in the SampleArray.Then the CByteArray data stream is compressed by using Huffman algorithm.To implement the Huffman algorithm, the frequency of occurrence of each byte in the CByteArray is counted and the result is stored in the Counts array.The Counts array is then scaled down so that they fit in a byte and then stored as initial weights in the NODE array.From the NODE array, a Huffman tree is built.The Huffman tree is then converted to Huffman codes by a function that recursively walks through the tree, adding the child bits to each code until it gets to a leaf.When it gets to a leaf, it stores the code value in the CODE element and return.The Counts array, which has been scaled down, is saved in the ECG file so that the Huffman tree can be rebuilt in the data expansion process.When the Huffman codes are available, the CByteArray can be compressed by saving the Huffman code correspondence to each byte in the CByteArray into the ECG file.The Data Compression Unit is also responsible to expand the compressed data to SampleArray.The expansion process is also divided to two steps.First, it converts the Huffman codes to CByteArray and then converts the CByteArray to SampleArray.

Heartbeat detection unit
The Heartbeat Detection Unit is a thread that detects the present of heartbeat in the ECG signal.The algorithm used to detect the heartbeat is to find the presence of R-wave in the signal by amplitude triggering method.In this method, the average value of the signal is calculated by taking the latest 1000 samples into calculation.The triggering threshold is set to 600 units higher than the calculated average value.This value is determined by trial and error to find the most suitable value.Then, the ECG sample is read in one by one.An Rwave is considered detected when it can fulfill the follows conditions.


The ECG sample value is higher than the triggering threshold.


The differential value between the current ECG sample and the previous one is greater than three units.


Four consecutive decrease of sample value followed by four consecutive increase of sample value is detected.

Discussion
The ECG recorder has been constructed prototype on a board and tested for its electrical characteristics.The microcontroller firmware is tested by software simulation before it is transferred to the PIC16F84 microcontroller.The microcontroller can successfully get the ECG samples from the ADC and send it to the computer.To test for the stability of the recorder, it is put in record mode for long duration and it is able to continuously sending data to the computer for more than 3 hours.When the recorder is in recording mode, it automatically goes back to power saving mode if the ECG recorder is disconnected from the computer.At battery low condition, the recorder can still work until the battery voltage drops to less than +3V.The battery low indicator will turn on when the battery level drop below +3.5V and left some time for the user to stop the recorder before it stop working by itself.

Testing for the amplifier gain
The voltage gain for every stage of the amplifier was measured.By using a sinusoidal signal with frequency of 20Hz, the peak-to-peak voltage at the input and output is measured by an oscilloscope.The measurement result for the preamplifier and second stage amplifier are shown in the Figure 17 and Figure 18.From the Figure 17 and Figure 18, the voltage gain for the preamplifier is 497.2 and the voltage gain for the second stage amplifier is 2.0.Thus, the total voltage gain for the two amplifiers is 994.4.

Testing for the filter
To measure the frequency response for the analog circuit, a sinusoidal signal with different frequency was applied to the differential input of the preamplifier.The input signal is set to voltage of 25mV and then the output voltage for every frequency at the final stage amplifier was measured by an oscilloscope.From the measured result, a graph was plotted to find the cutoff frequency for the high pass filter and the low pass filter.Figure 19 shows the measurement result for frequency response.From the Figure 19, the cutoff frequency for high pass filter was 0.23Hz and the cutoff frequency for low pass filter was 79Hz.

ECG file size
The graph in Figure 25 shows the size of the ECG files and its record duration.The increasing rate for the ECG file is approximately 0.5236 kilobyte per second.If the result is compared with the increasing rate without compression, which is 0.7324 kilobyte per second, the compression ratio achieved is 39.9%.

Conclusion
Electrocardiogram (ECG) has long been used as an important medical tool in monitoring patient's heart activities.In some cases, the patient has to go to the medical center very often to record their ECG for the diagnostic of the physician.This chapter describes the design and development of an electrocardiogram (ECG) recorder for single-lead recording that enables the recording of ECG at home and development of software to receive the ECG data from the recorder.The ECG data is saved in a compressed format for easy transmission over the Internet.The ECG recorder is a battery-powered device and its design emphasises on low power consumption.The ECG recorder is used as a peripheral connected to the computer via RS-232 port as well as USB simulator.The software was can be developed using Visual C++ or Java programming language.This design has been tested with the real patient and the ECG output has been verified by the medical doctors.The software can display the ECG data and clearly show the P, Q, R, S and T waves for diagnosis.The system consists of ECG recorder hardware and a software program.The recorder hardware has the following characteristics:


It is battery powered and small in size.Therefore, it is very portable and easy to use. It provides amplification, noise filtering, analog-to-digital conversion and data acquisition of ECG signal.In addition, it has the ability to monitor its battery status and manage its power usage. It samples the ECG signal at high resolution of 12-bit and with the sampling rate of 500 samples per second.Therefore, the digitized ECG signal is suitable for use in the analysis and measurement of PQRST waves of the patient's ECG.


This battery operated portable device has safety medical standards that comply with IEC601-1, AAMI EC11 (protective class).
The ECG software has the following characteristics:  It can control the recorder hardware and get the digitized ECG data from the hardware via serial port.


It provides the display of the real time ECG signal, patient's heartbeat rate and the battery status when recording ECG.When viewing the recorded ECG signal, the user can scroll through the signal by a scroll bar.Besides that, the ECG signal can be zoomed to five different sizes.


It compresses the ECG data before saving the data to a file and expands it when the file is loaded.This makes the ECG file small and easy to send through the Internet.

Suggestion for future expansion
The following improvements can be made to make the system more powerful and useful.


The program can be expanded to be a client-server program so that the patient's ECG file can update directly to the medical center's database and thus providing a more secure transmission.


The security part of the program can be further improved by providing some data encryption to the ECG file so that only the intended person can view the patient's ECG data.


Besides that, the program can be developed so that it includes digital filter to further reduce the noise level.


The prototype can be expanded to make it work with handheld devices such as palm top to make the recorder mobile.The ECG recorded at the handheld device can then be downloaded on the computer.


To make the recorder a wireless device by adding the radio communication circuitry to the recorder hardware and computer.


To view of more flexibility, this device can be modified further to work with direct telephone line interface whereby the communication and ECG data will be transferred to the server automatically.A modem and a communication protocol need to be embedded with this device.

Fig. 11 .
Fig. 10. Circuit Diagram for the ADC Fig. 12. Circuit Diagram for the Microcontroller

Fig. 15 .
Fig. 15.Communication Protocol Between the Recorder and Computer Fig. 16.Data Flow Diagram for the ECG Software

Fig. 23 .
Fig. 23.Document View for the ECG Software Fig. 25.ECG File Size versus Record Duration Graph