MCU-Based Heart-Rate Monitoring
Health-monitoring devices are all the rage. This month, Jeff explains how to acquire heart rate data from Polar Electro’s coded and noncoded chest straps through an input pin on a microcontroller. He details how to use the microcontroller’s serial port to display the data on a laptop.
Chris Van Allsburg, author of The Polar Express, worked with director Robert Zemeckis to bring his charming Christmas story to life (well, animation) in 2004. While the method of travel to and from the snowy North Pole in this story is a train, it has nothing to do with Finland, where skiers training for athletic competition became Guinea pigs for the first wireless heart rate monitors. This technology is responsible for beginning a new genre of fitness equipment established in the early 1980s by Polar. Polar Electro specializes in bringing fitness and training equipment to the not only professionals, but also those individuals who take physical fitness seriously. The Polar Loop activity band is a strong competitor in the present fitness rage giving wearers support feedback of their daily activity profile. This is all beginning to shape the future of medical monitoring and diagnostics.
I first was introduced to heart rate monitors when I bought a second-hand treadmill. The model contained a red LED that blinked along with my heart rate, as long as I was wearing the associated chest strap. It used a Polar T-31 non-coded chest transmitter. While chest straps have improved since then, it’s a good place to start because the basics are the same.
Electrocardiography is the process of recording the electrical activity of the heart using electrodes placed on a patient’s body. These electrodes detect the tiny electrical changes on the skin that arise from the heart muscle changes during each heartbeat. A heartbeat is the lub-dub we associate with the two halves of the heart, the left and right. Each half has an upper part the atrium and a lower part the ventricle. The atrium is a collection point for the blood waiting to be gulped into the ventricle by the atrium’s gentle squeeze. A one-way valve allows blood to flow into the ventricle but not back into the atrium. Instead, once the atrium has finished, the blood now filling the ventricle is forced out by ventricle contraction. A second one-way valve directs the blood to exit the ventricle.
The blood flowing into the left atrium comes from the lungs and contains oxygen. The left ventricle pumps this blood to the body. The blood flowing into the right atrium comes from the body, which has used the oxygen. The right ventricle pumps this deoxygenated blood to the lungs. The pacing of the heart muscles that provide this pumping action and therefore the heart’s rhythm are choreographed by the brain. Within the brain, our autonomic nervous system is regulated by the hypothalamus. Autonomic functions include cardiac regulation and control of respiration among others. The electrical signals sent to the heart muscles form a pattern we can see using some electrical equipment.
Normal resting heart rates range from 60 to 100 beats per minute (bpm). Heart rate can be measured manually by listening to the heart with a stethoscope or “feeling” the artery’s pulsation. Electrical activity can be picked up by amplifying heart muscle electrical activity. To do this, 10 electrodes are placed at predetermined positions on the body, four on each of the extremities (arms and legs) and six across the chest (and around left side). This placement creates a somewhat 3-D view of differential signals across different area of the heart.
A typical signal is shown in Figure 1. It can be divided into a number of divisions arbitrarily called PQRST, where P is the contraction of the atria, QRS is the relaxation of the atria and contraction of the ventricles, and t is the relaxation of the ventricles. The complete cycle takes about one-third of a second. You can see in Figure 1 that the spike during QRS is easy to locate. Without requiring electrodes to be placed all over our bodies, a reasonable signal can be generated with just two electrodes. That’s the basis of the heart rate monitor’s chest strap.
CHEST STRAP TRANSMITTER
It’s not apparent in Photo 1, but there are two electrodes embedded in the chest strap. These are covered with conductive plastic and integrated into the surrounding insulating plastic to make a water resistant package. The low power (battery) requirements for this circuit require some clever circuitry as there is no On/Off switch. The input amplifier (EKG) is not only used to acquire the “R” peaks of a heartbeat, but also determine a lack of heartbeat, or more likely that the user has removed the device. As each peak is detected, a 5-ms burst of 5-kHz carrier is transmitted; otherwise, the transmitter output is suppressed. Without external stimulation, the circuitry remains in its lowest power state, just waiting to jump into action.
The initial design required a receiver to merely receive these bursts. The length of time between bursts (Heartbeat EKG peaks) is easily measured to calculate the number of beats per minute. The technology was quickly accepted by exercise equipment manufacturers and fitness centers. Even though the range of these transmissions is relatively short, a fitness center often has many pieces of equipment. Suddenly receivers were picking up transmissions from multiple chest straps, resulting in racing and erratic heartbeat computations.
The system’s simplicity means that there are a few parameters that are fixed. The minimum time between pulses is 25 ms. Any additional pulses within the 25-ms window will be missed. But this isn’t an issue, even if we use 240 BPM (as a maximum heart rate), which has a minimum pulse (A)-to-pulse (A) time of 250 ms.
One option would be to add a second pulse (B), with an A-to-B time equal to a transmitter ID. As long as this time was less than 125 ms, you could still figure out which pulses are A-B, B-A, or A-A. There are many potential encoded variations. The hope being that interfering transmissions would vary such that using some basic rules, the extraneous signals could be separated from one another. The Polar receiver (RE07) can accept both uncoded and coded transmitters and output a pulse every heartbeat.
Polar receivers (and chest straps) are available through their OEM division and many distributors like Parallax, Adafruit, and eBay. About the size of a postage stamp, this module requires 3 to 5 V and outputs a positive pulse for every heartbeat it receives. For this project I use a standard circuit consisting of a microcontroller with user push button inputs and LCD output. The circuit also features a serial port, SPI, and I2C interfaces. The sensor port has power and a connection to an interrupt on change-of-state pin (COS) of Port B, so this will be an easy connection.
A pulse output from the Polar receiver will cause an interrupt on each pulse. I’ll use this interrupt to read the present value of HeartBeatmsH:L that increments thanks to a Timer 2 interrupt (see Figure 2). Once the value has been saved to SampleH:L, HeartBeatmsH:L is cleared, to begin timing the next pulse. SampleH:L is validated by checking it against maximum and minimum constants. The GoodSample flag is used in the Main loop to see if there is a new value to convert. Two lines of code will allow the circuit’s LED to mirror the state of the pulse coming from the Polar receiver as a visual indication of heartbeat. This is a quick and dirty indicator that the receiver is operating correctly.
The main loop is responsible for converting each sample and displaying the results on the LCD. To do this, two 16-bit math routines, both divide and multiply will be used. While this microcontroller has an 8-bit hardware multiply, I’m using a couple of fixed-point routines that do not depend on the hardware. If you refer to Figure 3, you’ll see two different conversions. The first converts the 16-bit binary value SampleH:L to five decimal digits. The second converts SampleH:L into an 8-bit binary value BPM.
Since I am measuring in milliseconds, I can use fixed-point arithmetic and eliminate the use of fractions. Refer to the formula: BPM = 60,000 ms/period in milliseconds. You’ll notice that the value 60,000 fits into a 16-bit number. With a maximum rate of 240 BPM, the period would be 60,000/240, or 250 ms. With a minimum rate of 30 BPM, the period would be 60,000/30, or 2,000 ms. These are the values used as HeartBeatMaxH:L and HeartBeatMinH:L back in Figure 1 to put some restrictions on the sample gathered through the COS input. We only need an integer conversion for BPM and the 16-bit divide routine gives us that without having to deal with the remainder (unless you wish to round up where appropriate.)
Even though the resulting BPM will fit into an 8-bit value (240 max), I’m using a routine I already wrote that converts a 16-bit value (up) to five ASC digits. This routine uses eight flags bits to enable some formatting of the data. Two bits are used for displaying a sign (+/-) before a value, one as an enable and one for the actual sign. A third bit allows all preceding zeros of any value to be replaced by <space> characters. The last 5 bits enable displaying a decimal point before any of the five digits. While I’m suppressing preceding zeros here, no other formatting is used. This last routine is used to convert the 16-bit millisecond value to decimal digits for the millisecond display on the LCD’s first line and converts the16-bit BPM value to decimal digits used for BPM on the LCD’s second line.
You say this little LCD is fine, but when you run on your treadmill, you are not in a position to be able to easily view it. Well, since we have a UART port available, let’s consider using a laptop to display the heart rate in a character size that you can’t miss, even from across the room! You can format the BPM data and pass it to a laptop via a wired TTL-to-USB adapter like the FTDI TTL-232R-3V3 or wirelessly using a JY-MCU Bluetooth module.
Perhaps you want to write an application that plots out your heart rate over time or stores it for future use. You might want to collect from a number of other sensors (e.g., GPS data with elevation information or body temperature and stride and pace). I’ll leave these thoughts with you so you can expand this project as you see fit.
If you have a smart phone, you already have access to some pretty serious training and fitness apps. I don’t want to dedicate my smartphone to a fitness app while running indoors. I’ll want to use it for making calls or listening to music while running, so I use a laptop for BPM feedback.
To implement a connection with my laptop, I’ll use a serial link. The UART connections are simple, only TX, RX and ground are necessary. If you are using a TTL-to-USB wired adapter, then the whole circuit can be powered from the USB adapter since these offer a power output as well as communications, with no wall-warts or batteries to worry about. Let’s add a little extra code to the project to send BPM data out the serial port each time the circuit receives a pulse from the Polar receiver. The data will take the form Text,value1,value2.
A sample transmission for a BPM of 60 will be “Notify,0012,003C”. I’ll explain this slightly puzzling format shortly.
In many columns I’ve used Liberty Basic whenever I wish to quickly write an application for a Windows PC (including 10). The whole application has only four functions: Comm, GetMessage, Tick, and Display. Comm is used to select and set up a serial port on which to receive data messages. Get message checks to see if any new data has been received and either captures everything until a carriage return (CR) or times out. A flag is used to indicate “good data” versus a timeout. The Tick routine executes after expiration of the timer variable. This value is updated by the Display routine. The purpose of Tick (in this application) is to increment x from 0 to 3, with a reset to 0 when x > 3. The value of x is used to provide the Display routine guidance as to what is displayed.
The display routine has two screens, a Waiting Screen and a BPM Screen. When the application is run, a main window is created with a menu bar atop a large graphic box (see Figure 4). The display routines use this Graphic Box as a frame in which to display their data. If the selected Comm port does not have any data available, either because no data is being sent or it’s not the correct port, then the Waiting Screen will display periods as is typical for many applications waiting for something to finish. The value of x displays one of four possibilities: “ ”,”. ”, “.. ”, “…”. While in this mode, the Tick timer value is set to 1,000 ms (1 s). Once real data has been received, the BPM value received is displayed in 220-point font, and the BPM value is used to calculate a new Tick timer value of half the BPM period using the formula: Timer = 30,000/BPM. By setting the Tick value to half of the BPM period, Tick will be in sync with the actual heartbeat. The label “BPM” is added to the bottom of the Graphic Box in 100-point type. The value of x is used here to alternately print the label or “spaces,” which allows the label to blink in sync with the actual heart rate. This is all accomplished with less than three pages of BASIC code (see Figure 5).
Today, when you think about sending 25-ms pulses as RF signals, you might chuckle and think, “What a waste.” But once you look at the current requirements for other wireless protocols, you find a lack of technologies that offer the flea power of these simple transmitters. However, Bluetooth Low Energy (BTLE), if used correctly, can fall into this realm. In fact it was designed especially for this purpose. BTLE is quite a different animal from its predecessor.
Bluetooth Core Specification refers to as Basic Rate/Enhanced Data Rate (BR/EDR) connection that connects consumer Bluetooth devices. This connection is open for the duration, whether data is constantly streaming or sporadic. An open connection means continual current requirements.
BTLE (also called Bluetooth Smart or Version 4.0+ of the Bluetooth specification) is a version of Bluetooth that was designed specifically for the Internet of Things (IoT). The big difference has to do with a change in philosophy, at least in those instances where data is minimal. Don’t waste connection time.
For this reason BTLE has been growing in popularity with many battery operated sensor-based wireless connections. Heart rate monitors are no exception. The latest fitness accessories tout Bluetooth Smart technology. This is a perfect tie-in with the next column, which will continue building on what was presented here. We’ll take a closer look at BTLE and how you can communicate with it using the same basic circuitry hardware, sans a BT receiver.
By no means should this preclude you from experimenting with some of the non BT heart rate hardware that has been around for a long time. These make a firm foundation from which you can jump into the future. Oh yes, in case you didn’t recognize it before, the crazy string of data, “Notify,0012,003C”, used to send BPM to the PC is in fact the data string that a BTLE device uses to automatically broadcast BPM, once it has been instructed to, by another device. Stay tuned for the Polar Express’s return voyage next month in Part 2 when we explore BTLE and how this is accomplished.
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • APRIL 2016 #309 – Get a PDF of the issueSponsor this Article