Implementing Bluetooth Low Energy
Last month, Jeff explained how to acquire heart rate data from Polar Electro’s coded and noncoded chest straps through an input pin on a microcontroller. In this article he takes a closer look at Bluetooth Low Energy (BLE) and how you can communicate with it using some basic circuitry.
If you’ve purchased a desktop PC or even a peripheral of some kind in the last few years, you are already familiar with how Bluetooth technology has proliferated in the marketplace. Wireless technology has gained a strong foothold in our lives. Bluetooth has become an integral part of this generation’s umbilical essentials. The cell phone rivals the PC for possession of our time, and many are tied to working a keyboard for hours a day. While the cell phone allows us to maintain contact with those who might otherwise be out of reach, it seems to foster a need to interact constantly. Wireless ear pieces and sound bars vigilantly maintain a constant connection.
My latest desktop uses Bluetooth to eliminate the wires that have always mechanically tied my keyboard and mouse to within a few feet of the desk. The desktop is mains powered, but the peripherals require batteries. While a Bluetooth connection can be broken when a peripheral goes to sleep, the use case requires a continual connection since there is normally a perpetual flow of information. A mouse or keyboard spends most of its connection time idly waiting for the user. The demands on Bluetooth have required the technology to provide increasing bandwidth. There seems to be a constant need for more, better, faster.
As Bluetooth requirements have taken the technology in one direction, there emerges a new sector that has entirely different requirements. The scream or, better yet, whisper we hear from this new gathering is low power. “I have little to say, but of great importance.” Clearly, this is contrary to the “more is better” attitude of Classic Bluetooth. How can a need with such contrasting requirements be covered under the Bluetooth roof?
GOOD FIT?
First, we need to understand what are the factors that influence the direction taken. There are three: spectrum, license, and power. The 2.4-GHz Industrial, Scientific, and Medical (ISM) band has poor propagation characteristics, but the spectrum is available worldwide without licensing issues. It therefore falls into the low-cost category. The Bluetooth Special Interest Group (SIG) has some of the lowest licensing costs for its technologies. Again, low cost. Power, or the power requirements, certainly drive costs. However, of more importance here is the size requirement of the source and how long it will last. In most cases the physical size of the device will determine the size of the battery it can hold and thus determine useful lifetime. Low power also means lower costs.
While Classic Bluetooth technology fits with the spectrum and licensing requirements, it falls short on being low power like most other technologies. To this point, competing technologies all have similar power requirements. Their transmitter/receivers can trade power for distance, but since they essentially must remain connected, their power is fixed at a constant rate. With today’s battery technologies, the coin-cell sized battery, which is required in many of the purposed situations, just can’t supply sufficient sustained currents or required lifetimes.
With low power as the primary requirement, any renewed or new design must take on a completely different philosophy. Not only is this a breakthrough design, but how it was integrated with Classic Bluetooth is a marketing success. The most difficult part of any new design is getting the manufacturers to use it. Classic Bluetooth was already being used everywhere, so integrating any new circuitry into the same chips that were already providing Classic Bluetooth created a solution that offered dual-mode capabilities with minimum cost or headaches. In addition, single-mode solutions could decrease costs where Classic Bluetooth solutions were unnecessary. However, since the two modes served completely different use cases, both solutions remain viable, depending on the application.
— ADVERTISMENT—
—Advertise Here—
COMPARISON
Table 1 shows how Classic and LE (or Smart Bluetooth) differ from one another. As you can see, LE has a lower data rate; however, it can connect, send data, and close the connection much faster than Classic. This means a savings in power. Essentially, with a connection closed, there is little or no power consumption. So the real power is determined by the open connection versus idle ratio. There is no need to waste power on an open connection when there is no “new” data to send.
Here we see the basic differences between Bluetooth Classic and Low Energy. While the overall throughput is lower for LE, it is designed for fast and minimal contact to reduce its power requirements.
Bluetooth LE is based on using a CR2032 coin cell. About the size of a quarter, this 3-V lithium device has a capacity of approximately 230 mAh. The maximum suggested current draw of this cell is approximately 15 mA, which fits right into the LE specifications. To help keep this to a minimum, LE devices are divided into four types: advertisers, scanners, slaves, and clients. An advertiser might include only a transmitter to transmit packets and a scanner, only a receiver, to retrieve them. In a master-slave setup, while both can transmit and receive, a slave can only respond to a master’s requests, thereby keeping its required computing power to a minimum. In both examples we have a client-server relationship.
One of the basic concepts of LE is the state. Everything is a state, whether it’s a sensor’s value, the device’s name, or an I/O level and can be easily read or written. In fact notifications can automatically transfer a state or change of state (COS). This object oriented approach helps to reduce code requirements. When necessary, a client can provide access to the internet by being part of a gateway, which offloads IP stack requirements from every device. This client-server architecture uses a service-oriented model that organizes information into services that can be discovered and interacted with known procedures that allow work to be accomplished without knowing how.
ARCHITECTURE
Bluetooth LE architecture can be divided into three main components: the controller (radio), host (protocols and profiles), and application (characteristics and services for each profile) layers. The radio’s 2.4-GHz band is divided into 40 2-MHz-wide RF channels. Carrier deviations of 185 MHz denote logic 1 (+ deviation) and logic 0 (– deviation) states at a rate of 1 bit per microsecond.
The host directs dataflow through two protocols, the security manager for handling pairing and key distribution and the attribute protocol that defines the rules for six types of messages: client-to-server requests, server-to-client responses, client-to-server information, server-to-client notifications, server-to-client indications, and client-to-server indication confirmation. The Generic attribute profile defines procedures to discover services, characteristics, and relationships. Whereas the Generic Access profile defines how devices discover, connect, and bond.
At the app layer, things get a little more specific. An app profile describes the devices used in a specific profile. The characteristics of the device are in a data format known as Universally Unique Identifier (UUID). These are references to human-readable text that fully describe the formatted data. These specifications or services define the behavior on the server whenever a characteristic can be read and/or written.
While this was an extremely condensed overview of BTLE, it is sufficient background to let us get into this month’s project. If you were with me last month, I explained on how Finnish skiers training for athletic competition became the lab rats for the staple of today’s fitness equipment. Using Polar’s coded and non-coded chest straps, last month’s project showed how to interface with the RE-07 receiver to display the heart rate data sent by these chest straps. A natural progression of Polar’s chest straps was to modernize their proprietary transmission system with the BTLE technology opening up their use to the mobile applications market. And so, this month I expand the project by adding a BTLE module and use it to access data from the new BTLE enabled chest straps.
BTLE PROJECT
For this project, I chose to use the Microchip Technology RN4020 BTLE module that uses a simple ASCII command interface via a TTL serial port (see Figure 1 and Table 2). Like many modules today, the firmware is upgradable over the air (OTA). This device also supports an ASCII scripting language to allow the module to become a standalone device; however, for this project I will be using it strictly as a peripheral to the circuit presented last month (see Figure 2). The circuitry allows connection to the RN-2040 module via four connections +3.3 V, ground, TX, and RX (these are TTL signals). I started this project by connecting this module to a USB-to-TTL dongle. This way I could use a serial terminal on my PC and play with the commands to begin to feel comfortable with what I should expect as a response to various commands. The V (“version”) command is a good one to start with because it gives you some information on the level of firmware in your module. Listing 1 shows what you can expect from the module. You see the version and also using the D command, a dump of the present status consisting of the MAC address, the device name, connection status, bond status, server services, features, and TxPower.
The RN4020’s block diagram shows a core consisting of a radio and modem conforming to the BTLE 4.1 specifications. The I/O includes digital and analog as well as the TTL UART communication port. Internal memory exposes user configurable parameters and scripts.
The RN4020 BTLE module offers the user simple ASCII commands to carry out complex functions. This allows a user control of the module via a UART. The module has the capability of firmware updates “over-the-air,” keeping it relevant.
Listing 1
What you can expect from the module
V
MCHP BTLE v1.23.5 8/7/2015
D
BTA=001EC01CEFF9
Name=RNEFF9
Connected=no
Bonded=no
Server Service=80000000
Features=20000000
TxPower=4
In this case the server services support a central role, and if placed in client mode, its features are set to look like a heart rate monitor. (Just a coincidence!) You might want to update your firmware at this time if you want to have the latest and greatest. Nothing we’re doing here is dependent on doing this.
— ADVERTISMENT—
—Advertise Here—
OK. We want to connect with the BTLE chest strap. Where do we start? Well, the best place to start might be to see who is out there advertising a public address. This would be the F (“find”)—or start scan—command. There are two possible results: ERR (busy doing something else, sorry) or AOK (command acknowledgment). If there are devices in the vicinity, they are listed prior to the AOK in this fashion:
F
9059AF025269,0,,,-3A
AOK
You see a device with a MAC address of 9059AF025269, with a public address type, a null name, a null UUID, and a received signal strength (RSSI) of –58 dB. In order to find out more about this (or any) device, we’ll need to connect to it. The connect command E uses the address type and MAC address for the device of interest.
E,0,9059AF025269
AOK
Connected
The response is a command acknowledgment followed by the connection state. If we are connected, then we can ask about the client services using the LC command (or server services with LS), as you can see in Listing 2. The client has responded with three groups of items followed by an indication that the list is complete. Each group begins with a GATT service 16-bit UUID. All adopted services have been assigned a UUID beginning with 0x1800. The three service groups referred to here are: 0x180D Heart Rate, 0x180A Device Information, and 0x180F Battery. Each service includes a list of characteristics associated with it (see Table 3). These GATT characteristics have preceding blank space a 16-bit UUID beginning with 0x2A00 assigned to it, as well as a handle and property associated with it. Since a service can have multiple entries with the similar characteristics (see the first two or the last two above), all characteristics have a handle and property that define their use. The handle points to where the information is located and the property describes the type of operation allowed (see Table 4).
Listing 2
You can ask about the client services using the LC command
LC
180D
2A37,0012,00
2A37,0013,10
2A38,0015,02
2A39,0017,08
180A
2A23,001A,02
2A24,001C,02
2A25,001E,02
2A26,0020,02
2A27,0022,02
2A28,0024,02
2A29,0026,02
180F
2A19,0029,02
2A19,002A,10
END
Each profile, in this case the Heart Rate Profile, can have any number of services associated with it. Each service has characteristics that are used to describe or use the service. Universally Unique Identifier (UUIDs) are assigned numbers for profiles, services, characteristics, codes, and identifiers used in the Bluetooth wireless standard by the Bluetooth Special Interest Group (SIG).
Each characteristic value can have certain properties associated with it. These properties are bit mapped into the property’s 8-bit value.
We can retrieve the values for each characteristic by using the CURV command with its UUID or the CHR command with its handle. Doing so for each of the characteristics would reveal the information in Table 5. Note that if you use the CURV command, you will access the characteristic value. (The configuration is only available using the CHR and the handle.) The Device Information service exposes all of the manufacturer’s information. This is sent in a least significant octet (LSO) or byte-first format. Be sure to download the Heart Rate Profile and three Services for this profile to have the key to understanding the data presented. For instance, in the Heart Rate Service specifications, the body sensor location holds an 8-bit value corresponding to the placement of the sensor. You can find a list of the locations and their values at the Bluetooth Developer Portal webpage listed in the Resources section at the end of this article.
The read characteristic (CHR) command can retrieve any of the characteristic values available by referring to its Handle (pointer to the information).
The two remaining services—Heart Rate and Battery—are similar in that both have a notify property. This means that you can request that these automatically initiate data transfers to their connected devices. The Heart Rate is sent once per second. The Battery Level is sent only when its value changes. These services are dissimilar in that only the Battery Level can be read; the Heart Rate property has no entries. Since the Battery Level notification is only sent when its level changes, it may take a while to actually get a transmission, so you might choose to read its value at the beginning of a connection and alert the user if it is getting low. Note that in Table 5 its present value is 100%. On the other hand, reading the Heart Rate makes no sense since we want this to be continuously updated, so we need to enable notifications for this to begin operations. The Heart Rate characteristic at Handle 0x0013 gives us access to this function. As you can see in Table 5, it is presently 0x0000. In this case, there are only two possible values, 0x0000 = idle and 0x0001 = notify active. Remember that data expected in a LSO format, so the data for “notify active” would be 0x0100. We use the CHW command with the Handle and the data, like so:
CHW,0013,0100
Notify,0012,0032
AOK
Notify,0012,0031
Notify,0012,0030
…
That’s it! Now we have streaming data being sent automatically. Since no further requests are needed, the transmission times are kept extremely short, minimizing power requirements. All we need to do is monitor the data and perform some task based on it (Heart Rate.)
INTEGRATION
Last month, we gathered data from the chest strap through an input pin on the microcontroller. We need add a few additional routines to be able to carry on a conversation with the RN4020. All necessary circuitry is already in our circuit. We used the microcontroller’s serial port last time to allow Heart Rate information to be sent to a PC so large format digits could be displayed on a laptop screen. I want to be able to see the Heart Rate without having to squint at the microcontroller’s LCD while running on a treadmill during winter workouts. This microcontroller has a second serial port that shares I/O pins with the ICD3 (programmer/debugger), so I already have a connector on which I can add the RN4020. The down side is that I can’t debug the second serial port since they share the same pins. I can, however, easily reassign each serial function to the first port and debug them independently. Once debugged, I can assign both ports as needed.
Besides duplicating the serial routines for the second serial port in support of BTLE communication with the RN4020, two routines were added to the Main “loop,” Response and Request. The flowcharts in Figure 3 and Figure 4 show the request/response patter between RN4020 and the chest strap. When a request is answered by the correct response, the mode increments until Mode 6 completes and the chest strap begins Notification. Notify responses are interpreted and the Heart Rate displayed on the LCD as well as sent directly out the first serial port (to the PC). Note the Notify string is the same as that mysterious string we used last month. Did you guess correctly?
— ADVERTISMENT—
—Advertise Here—
The variables Mode and Resp in addition to a few flags direct the flow of execution through the process of initiating the RN4020 BTLE module. After each command is sent, the module’s responses are monitored and identified.
A matching Mode’s Response allows Mode to increment. Once the module has successfully been set up and notifications begin, these Notifications are deconstructed to retrieve the Heart Rate which is displayed on the LCD (and sent out the serial port to any connected PC running the large display Application.)
Bluetooth has improved this fitness product and opened it up to the world. While you can get Polar’s H7 chest strap for about $80, I’ve seen BTLE Heart Rate sensors on eBay for less than $10, and that includes shipping! The RN4020 module is about $10; however, it’s about the size of a postage stamp and has solder points on 0.05″ centers. For those that would like something a bit easier to use take a look at the MIKROE-1715 or RN4020-PICTAIL, both available from Mouser. You’ll pay more but the 0.1” headers create much friendlier connections.
Almost all the Bluetooth USB dongles being sold now are dual mode and support at least Bluetooth 4.0. This means your PC now has access to all the LE functions. If you want to write a PC application, like a connection to a BTLE chest strap, you must use APIs. Using an RN4020 connected to a USB-to-TTL (i.e., FT232R Breakout, Sparkfun) will give you access to the ASCII command set and avoid imperial entanglement. The fitness industry has decided that your smart phone is the only necessary recipient of any of their support apps, so if you want to receive Heart Rate data on your PC, it’s up to you. While the purpose of this project was to show you how you might want to gather data from a BTLE chest strap using a microcontroller, the above dongle would allow you to experiment further using your PC and Liberty BASIC. Liberty BASIC can easily handle talking with the RN4020 module using a very simple Windows-based language. If you try the free version of Liberty BASIC, you’ll surely spend the $60 for a licensed copy.
WHERE TO NOW?
Using BTLE for monitoring Heart Rate is only the beginning. As you can see in Table 6, many of the adopted profiles relate to the medical and health industries. This is an indicator of the growing market for health-related products. Affordable healthcare continues to be one of the biggest concerns of our time. Wireless sensors make it possible for vitals to be monitored discreetly in real time, with stats being forwarded to medical staff as necessary.
While this is an ongoing process, presently a number of profiles have been fully adopted by Bluetooth SIG. You can follow this process by visiting: www.bluetooth.com/specifications/adopted-specifications.
Data mining is already allowing specialized content to be delivered to the webpages we view. It will now be possible to deliver special content to displays based on how you move throughout the world. Proximity, alert, location, and navigation are other exciting profiles that can be leveraged to make our lives more efficient. Lighting and air conditioning will be adjusted as you enter and exit different areas of your home. Presently, your phone is you (has the BTLE to advertise your presence), but this ability will soon be more personal, through your jewelry, wallet, and keyfob.
Which camp do you belong to? Is this all an invasion of your privacy, or improving your lifestyle? It would seem to some people, like those who use social media, that they can’t open their lives wide enough to the world, while others remain vigilant to HIPAA laws and any activities that might expose them to identity theft. As long as we have control of our government, our freedoms shall remain protected.
The cellphone is one of the most powerful contributions to the humanity developed in the last generation. It has truly brought communication to the world as we have experienced firsthand from social media entries of refugees fleeing from their homes in Syria. Using BTLE we can share data from any wireless black box. What will your next black box include? You might bring joy to someone, check your speed, order in, or save someone’s life. The future is in your hands. Let’s all be a force for good.
RESOURCES
Bluetooth Characteristic Body Sensor Location,https://developer.bluetooth.org/Pages/XMLViewer.aspx?u=gatt/characteristics/Documents/org.bluetooth.characteristic.body_sensor_location.xml
R. Heydon, Bluetooth Low Energy: The Developer’s Handbook, Pearson Education, 2013.
SOURCES
PIC18F26K80 Microcontroller and RN4020 BTLE module
Microchip Technology | www.microchip.com
RE07 Polar Heart Rate Receiver
Polar Electro | www.polar.com
Liberty BASIC
Shoptalk Systems | www.libertybasic.com
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • MAY 2016 #310 – Get a PDF of the issue
Sponsor this ArticleJeff Bachiochi (pronounced BAH-key-AH-key) has been writing for Circuit Cellar since 1988. His background includes product design and manufacturing. You can reach him at: jeff.bachiochi@imaginethatnow.com or at: www.imaginethatnow.com.