Bluetooth® Low Energy Connections with basic_ble example#

Texas Instruments

2 - 3 hours read

Introduction#

In this module we will learn about Bluetooth® low energy (LE) connections. How is a Blutooth LE connection formed? What information needs to be shared by two devices in order for them to stay connected? How can Bluetooth LE connections be updated? This tutorial will give you an overview of how to set up Bluetooth LE connections suited to your needs.

In this lab we will be working with basic_ble and BTool.

Basics about Bluetooth LE connections will be provided. The first task, will consist of building a connection with basic_ble on the peripheral device. The second one as SimpleLink CC2340R5 LaunchPad as a central device together with the program BTool. Then we will discuss about connection parameters and how to update them, from the Central and Peripheral side, respectively. The two last section will consist in end a connection with a specific function and to customize your project by blinking a LED at each connection event.

This tutorial will take about two hours to complete and requires basic embedded programming skills (see the Prerequisites section for details).

Prerequisites#

Hardware#

  • 2 SimpleLink CC2340R5 LaunchPad Targets

  • 2 SimpleLink LaunchPad XDS110 Debugger

  • USB cable

  • SmartPhone or Tablet with a GATT Table viewer application installed (such as TI SimpleLink Connect app)

Software#

  • Code Composer Studio version 12.3 and newer or IAR 9.32.1 installed with support for CC23xx devices.

  • SIMPLELINK-LOWPOWER-F3-SDK Software Development Kit (SDK)

  • BTool (located in the tools\ble5stack directory of the SimpleLink™ Device SDK)

  • Bluetooth LE Client app, such as TI SimpleLink™ Connect app

Note

Have a look the following lab to have more information on the TI SimpleLink Connect App.

Readings#

  • SDK User’s Guide You should particularly have a look on the Generic Access Profile (GAP) and Generic Attribute Profile (GATT) sections, it will help you to understand a bit more about the theory behind Bluetooh™ Low Energy protocol.

Agenda#

In this training, we will discuss how to the set up a connection with basic_ble example for custom development.

1. Discuss how a Bluetooth LE connection is formed

2. How to set your peripheral device

3. How to set your central device and start a connection

4. How to set a clock

5. Discuss about connection parameters

6. Discuss about connection interval

7. Discuss about peripheral latency

8. Discuss about supervision time-out

9. How to end a connection

10. A brief project to blink a LED at each connection event

About Bluetooth LE Connections#

What is a Bluetooth LE connection? A connection implies a link between devices over time. Bluetooth LE is a synchronous radio frequency (RF) protocol, meaning that any transmission between devices must be scheduled. The opposite of this is an asynchronous connection, where the receiving device listens constantly or periodically, and the transmitting device can transmit at any time. A Bluetooth LE connection can thus be perceived as a series of meetings where two devices transmit and receive information at the same time, on the same radio frequency. In order for this to work, the devices must agree on where (that is, on what frequency) and when next to meet. The BLE5-Stack handles connection timing and frequency hopping. The latter will not be further explained in the following text.

Note

If you want to know more about frequency hopping, you can read more about this in the Bluetooth Core Specification Version 5.3 and the TI BLE5-Stack User’s Guide mention in the reading section section above.

../_images/meeting.png

Organizing a radio meeting#

A Bluetooth LE connection always consists of two devices. The device that initiates the connection is called the Central. This device also has the final word on timing and frequency hopping. The device that responds to a connection initiation is called the Peripheral.

Bluetooth LE Connection Life Cycle#

As mentioned, the connection must be initiated by the Central and then accepted by the peripheral device. The connection can be terminated from either the Central or the Peripheral.

The two Bluetooth LE devices are connected as long as they periodically exchange data. The exchange is called a connection event and consists of both devices transmitting and receiving information consecutively. Each connection event starts with the Central transmitting and the Peripheral receiving. Then the Peripheral transmits and the Central receives.

../_images/connection_event.png

Connection event#

#### Quiz Which statement is true? 1. [ ] The initiator of the connection automatically becomes the Peripheral device. > The initiator of the connection becomes the Central device. 1. [ ] The Peripheral device dictates the terms for the connection. > The Central device is the decision maker. 1. [x] A connection consists of one Peripheral and one Central device. #### Which of the following is **not** a GAPRole? 1. [ ] Broadcaster > The *broadcaster* GAPRole is defined as a nonconnectable advertising device. 1. [x] Beacon > A nonconnectable beacon is defined with the broadcaster GAP role. 1. [ ] Peripheral > The *peripheral* GAPRole is defined as a device that advertises and is connectable. 1. [ ] Observer > The *observer* GAPRole is defined as a device that can scan for advertisements but not connect to other devices. 1. [ ] Central > The *Central* GAPRole is defined as a device that scans for advertisements, initiates connections and operates as Central in one or multiple connections. #### Can the Central and the Peripheral communicate outside of the connection events? 1. [ ] Yes, special requests can be sent at any time. 1. [x] No, all requests must be sent in connection events.

Bluetooth LE Connection Limitations#

Before Bluetooth Core Specification v4.1, a Bluetooth LE peripheral device could connect to only one Central device at a time. Over time, Bluetooth LE has evolved to support more complex topologies, e.g. a star network configuration where one Central device connects to multiple peripheral devices. Or a network where peripheral devices can connect to multiple Central devices, and a device can operate both as a Peripheral and Central role (in different connections) simultaneously without needing to swap roles. Still, Peripherals cannot connect to each other, but instead are limited to connect with Central devices.

The specification does not limit the number of connections. The available memory resources of the device and the time domain determines the maximum number of connections supported. The user can profile the heap used in the project to determine the maximum amount of connections that can be supported.

  • For more information, see the Debugging Common Heap Issues chapter in the Debugging section of the TI BLE5-Stack User’s Guide in the reading section.

  • See the basic_ble example on the Peripheral + Central role for a simultaneous Central/peripheral GAPRole. To modify the role of the example, open your basic_ble.syscfg file, then go to BLEDevice Role. All roles are provided on the same basic_ble example.

../_images/running_mode_modify.png

Role on Sysconfig#

Task 1 - Set up a connection with basic_ble on the peripheral device#

Here we will consider our Smartphone as a central device. Thus, you need to have Bluetooth LE scanner apps on it, check the software needed section for more informations. For our central device to have something to connect to, we need to set up a Bluetooth LE peripheral device. Flash one of your SimpleLink™ CC2340R5 Modular LaunchPad™ with basic_ble in a Peripheral role (follow the Role on Sysconfig picture to know how to change the configuration). If you need help, follow the instructions in the Quick start guide section located in the reading section. If you want to check that your peripheral device is advertising, you can use your phone, using a Bluetooth LE Client app.

../_images/ScanningBLEBasicSmartPhonebis.png

Scanning view on TI SimpleLink™ Connect app#

Hint

Now we have a peripheral that our central device can connect to. Let’s proceed!

Acquire an other device SimpleLink CC2340R5 LaunchPad which play the central role in the connection. Flash the host_test example from your SIMPLELINK-LOWPOWER-F3-SDK on one device. Flash the other SimpleLink CC2340R5 LaunchPad with the basic_ble example in a Peripheral role.

Hint

To change the role on basic_ble, open your basic_ble.syscfg file, BLEDevice Role. All roles are provided on the same basic_ble example.

../_images/running_peripheral_modify.png

Change the role on Sysconfig#

Open BTool

BTool is a tool bundled with the SimpleLink SDK, found under <SDK_INSTALL_DIR>\tools\ble5stack\btool. In order to use it, your computer must be connected to a LaunchPad running the host_test example project. In this module we will use BTool to control a Bluetooth LE central, but it can be used for other situations as well. This means that not all commands found in BTool are suitable or permitted.

Open Run_BTool.bat in <SDK_INSTALL_DIR>\tools\ble5stack\btool. Then click on the Device menu and New Device, the pop up window below shoul appears.

../_images/BTool_device_connection.png

Connection with BTool#

You will be prompted for the COM port of the device. You can find this by opening the Windows device Manager. Right click on This PC → More → Properties, device Manager is found on the menu to the left. Look for the port called XDS110 Class Application/User UART.

../_images/find_COM.png

Find device COM port#

If everything went well, BTool will start printing green and blue events. (If you’re seeing yellow or red events, please make sure you found the correct COM port and that the device is not paused by a debug session in CCS. You may also need to hit the LaunchPad reset button before connecting to BTool.)

If you scroll all the way to the top of the BTool log, you can see that the device has been initialized as a Central by GAP.

../_images/btool_gapdeviceinit.png

GAP device init#

To the left BTool displays information about the host device. This is also where information about any active connections will be displayed. In the center BTool prints out a log of all commands and events. To the right, some actions are displayed.

When the user sends a command, this is printed in green. These command log entries start with <Tx> as they are transmitted from BTool to the device running Host Test. Events received from the LaunchPad running Host Test are printed in blue and start with <Rx>. For each command sent, BTool will receive one GAP_HCI_ExtentionCommandStatus event to indicate that the command was received.

Once the image below is openned, click on the Scan button, it will takes few second to the central to scan all the advertisements around. Then open the combo box Slave BDA and search for your peripheral MAC Address. Once you find it, click on the Establish button, you should create your connection between both devices!

../_images/BTool_scan_and_establish.png

How to establish a connection with BTool#

Hint

Now we have a peripheral that our central device can connect to. Let’s proceed!

What Happens on the Peripheral Side?

By default, basic_ble advertises with connectable undirected advertisements. This is defined through SysConfig in BLEBroadcaster ConfigurationAdvertisement Set XAdvertisement Parameters X in the Legacy Event Properties Options field. You can read more about advertising properties in BLE Scanning and Advertising. When using connectable undirected advertisements, the peripheral device accepts connection requests from any initiator. The peripheral does not send a packet to notify the central that the connection has been accepted. Instead it waits for the first connection event.

../_images/establish_connection.png

Establish connection flow diagram#

Task 2 - Set up a connection with basic_ble on both central and peripheral device#

The purpose of this section is to know a bit more about basic_ble with central role. Thus, flash one of your SimpleLink™ CC2340R5 Modular LaunchPad™ with basic_ble in a Central role (follow the Role on Sysconfig picture to know how to change the configuration).

Once your device is flashed, open a serial terminal on the dedicated PORT COM of your device (XDS110 Class Application/User UART (COMXX)). You should have a similar display than below, note that your BLE ID Address and your BLE RP Address should be different.

../_images/Central_role_UART_display.png

Central role serial terminal display on UART port#

Now the central device is ready to use, you’ll be able to scan, connect and change basic stuff through the menu. Use the buttons of your device to navigate in the menu. To scan for potential devices advertising, press the right button to select Scan menu then Scan for devices.

After the scanning, the display shows a scan status:

Scan Status#
  Scan status: Scan disabled - Reason: X Num results: X

The reason parameters represents if the scanning was interrupt by user request (0) or by duration expiration (1).
The Num results parameters represents the number of recorded advertising reports.

To connect to a specific device, go back to the main menu, select Connection menu then Connect to a device and search the address of your peripheral device.

With your second device flash the basic_ble in a peripheral role and open a serial terminal on the dedicated PORT COM (XDS110 Class Application/User UART (COMXX)). You should have a similar display than below for your peripheral device, note that your BLE ID Address and your BLE RP Address should be different.

../_images/Peripheral_role_UART_display.png

Peripheral role serial terminal display on UART port#

Here you can check the RP Address of your peripheral device, start the connection from the central side on this address.

After the connection, the display shows a Conn status on both side (central and peripheral):

Conn status#
  Conn status: Established - Connected to 0xAAAAAAAAAAAAA connectionHandle = X

Hint

Now we have a peripheral connected to a central. Feel free to navigate in the Connection menu and the Work with a peer device one.

Task 3 - Create a oneshot or periodic clock using clockP module#

Let’s set up a timer on the basic_ble example. This code will be usefull to call specific functions, later in this lab. It exist three different ways to implement a Timer, the first one shows how to add a new event in the stack but need a deeper change in the embedded code and modify the SDK files. The second one and the third one use only an argument calling a callback function, the difference between both methods are the clock type.

This method is the easiest way to implement a clock with ClockP module. First include the rights librairies and all instances needed for the clock usecase.

The Peripheral_AppEventHandler() is the function passed in argument at the clock construction. The BLEAppUtil framework manage the stack to run the function at the proper time. Thus, the stack is not disturbed by the new code.

The Clock module is feature developped from FreeRTOS, then we don’t have any testing coverage for that module, so we recommend to use ClockP module.

Add this code at the beginning of the app_peripheral.c file#
   #include "util.h"
   #include <ti/bleapp/ble_app_util/inc/bleapputil_internal.h>

   static Clock_Struct clkPeriodic;
   
   #define CLOCK_DURATION        5000
   
   //*****************************************************************************
   //! Prototypes
   //*****************************************************************************
   void Peripheral_AppEventHandler();

The Peripheral_AppEventHandler() is the function passed in argument at the clock construction. The BLEAppUtil framework manage the stack to run the function at the proper time. Thus, the stack is not disturbed by the new code.

Here you can find the code to initialize the clock.

Add this code in the Peripheral_start() function just before the BLEAppUtil_advStart() function.#
  // Initialize clock instance.
  Util_constructClock(&clkPeriodic, (void *)BLEAppUtil_invokeFunctionNoData, CLOCK_DURATION,0,0, (uint32_t)   Peripheral_AppEventHandler);

Here the Util_constructClock() builds the clock with its structure (clkPeriodic), its duration (CLOCK_DURATION), its period (here 0), the start flag (here 0FALSE) and the callback function (Peripheral_AppEventHandler).

This method allows you to create a new event in the BLEstack in order to call a specific function.

First include the rights librairies and all instances needed for the Timer.

Add this code at the beginning of the app_peripheral.c file#
  #include <ti/drivers/dpl/ClockP.h>
  #include <ti/bleapp/ble_app_util/inc/bleapputil_internal.h>

  static ClockP_Struct clkPeriodic;
  ClockP_Params clockpParams;
  ClockP_Handle clockHandle;

  #define SP_PERIODIC_EVT_PERIOD               5000
  #define CLOCK_MS                  1000

  //*****************************************************************************
  //! Prototypes
  //*****************************************************************************
  void Peripheral_ClockCb();
  void Peripheral_AppEventHandler();
The Peripheral_ClockCb() function is the callback function called when the clock has end#
  void Peripheral_ClockCb(){
    BLEAppUtil_enqueueMsg(BLEAPPUTIL_EVT_APP_EVENT, 0);
  }

The BLEAppUtil_enqueueMsg() function create an event and put it in the queue, once the event is on the top of the queue the Peripheral_AppEventHandler() function is called to run your code. Thus, the stack is not disturbed by the new code. The code below is now necessary to add the new event to the stack.

This function should be in the app_peripheral.c file#
  void Peripheral_AppEventHandler()
  {
    //add your code here
  }

Find below a converter tool to know exactly the duration of the timer depending on the define CLOCK_MS.

CLOCK_MS :
Timer is ms long

To start the timer, you need to call the function below wherever you seem it’s better for your implementation.

  ClockP_start(clockHandle);
  Util_startClock(&clkPeriodic);

Hint

Let’s try to implement a specific function and see if your code works, by building and flashing it.

What is connection parameters#

When forming a connection, four parameters must be determined. They all have to do with the connection timing:

Connection Parameter

Description

Range

Increment

Min Connection Interval

Minimum connection interval

7.5 ms to 4 s

1.25 ms

Max Connection Interval

Maximum connection interval

7.5 ms to 4 s

1.25 ms

Peripheral Latency

Number of skipped connection events

0 - 499

x

Supervision Timeout

Connection supervision timeout

100 ms to 32 s

10 ms

The connection parameters are set in the Central before initiating the connection. GAP handles these parameters. In BTool, you can find the connection settings just below the Discovery section. Please note that in BTool, these connection settings cannot be used to update the connection parameters during an active connection.

../_images/connection_settings_btool.png

Connection Settings tab on BTool#

Note

Note that in BTool Min Connection Interval and Max Connection Interval are writting from 6 to 3200, these are increments units.

Connection Interval#

What’s Connection Interval#

The connection interval is the time between each connection event. The connection interval must be agreed upon by the two devices in the connection in order for them to be transmitting and receiving at the same time. The connection interval has to be between 7.5 ms and 4 s to comply with the [Bluetooth Core Specification Version 5.2]. Each connection event consumes power, therefore we generally want a large connection interval. On the other hand, the connection interval represents latency. This means that in a connection with 1 s connection interval, a button press on the Peripheral device might not be registered on the Central device before 1 s has passed.

The connection interval is defined in terms of a minimum and a maximum value. If you want your application to have a fixed connection interval, you can give both variables the same value. Sometimes we want to give the Central device the freedom to change the connection interval without any further input from the user. In that case, give the minimum and maximum variables different values. The Central device will then be free to change its connection interval, as long as it stays within the defined limits. Per default, the device will start with as large connection interval as possible (i.e. the max value will be chosen by the BLE stack as the connection interval) in order to minimize power consumption. Your peer device may have specific connection interval requirements so make sure the connection interval you choose is supported by the peer you wish to connect to.

#### Quiz For an application that needs low latency between an event happening and a message being transmitted, which connection interval would you choose? 1. [ ] 5 ms > This is not a permitted value for connection intervals within the Bluetooth LE protocol. 1. [x] 7.5 ms 1. [ ] 1 s > This connection will not be able to transfer data with as low latency as a connection with a lower connection interval. #### Consider the following connection settings and decide what the initial connection interval will be: ```{figure} resources/connection_settings.png Connection settings ``` 1. [ ] 160 ms > Remember that the connection interval is given in units of 1.25 ms. 1. [ ] 200 ms > The BLE5-Stack will minimize power consumption... 1. [ ] 320 ms > Remember that the connection interval is given in units of 1.25 ms. 1. [x] 400 ms #### Which statement(s) are true? - [x] If the Peripheral and Central device have different acceptable values for the connection interval, they can still form a connection. > The Central device will decide the connection interval. - [ ] A small connection interval gives a less robust connection. - [ ] The supervision time-out breaks the connection if there has been no connection event for the given time. If this is inconvenient, supervision time-out can be disabled. > All four connection parameters must be present and enabled. The highest supervision time-out permitted is 32 s. If your devices need to communicate more seldom than this, perhaps it is better to disconnect and reconnect for each data transfer? - [x] A connection event begins with the Central transmitting and the Peripheral receiving. Then the Peripheral transmits and the Central receives.

Task 4 - How to modify the connection interval in my project#

For this section, the clock implemented in the create a oneshot or periodic clock using clockp module section is needed. The function BLEAppUtil_paramUpdateReq() will be used to change the connection interval and the parameters of the following sections as well.

First we need to create a new request for the new connection parameters:

  gapUpdateLinkParamReq_t newReq =
  {
    .connectionHandle = 0,
    .intervalMin = DEFAULT_DESIRED_MIN_CONN_INTERVAL,
    .intervalMax = DEFAULT_DESIRED_MAX_CONN_INTERVAL,
    .connLatency = DEFAULT_DESIRED_PERIPHERAL_LATENCY,
    .connTimeout = DEFAULT_DESIRED_CONN_TIMEOUT,
    .signalIdentifier = 0,
  };
../_images/connection_interval_modify.png

Connection Interval on Sysconfig#

This request reuse the parameters provide in sysconfig in the Peripheral ConfigurationConnection Update Request Params section. The define are not implemented in the embedded code yet so you can create your own request as shown above. Then in the callback function Peripheral_AppEventHandler() you need to specify the connection handle and call the BLEAppUtil_paramUpdateReq() function.

  void Peripheral_AppEventHandler()
  {
    newReq.connectionHandle = peripheralAdvHandle_1;
    state = BLEAppUtil_paramUpdateReq(&newReq);
  }

Peripheral Latency#

What’s Peripheral Latency#

The peripheral latency parameter allows the peripheral device to skip a number of consecutive connection events. During this time, the peripheral is not listening at the central connection events. The parameter corresponds to the number of connection events skipped. If the peripheral does not have any data to send, it can skip connection events, stay asleep, and save power. The peripheral can skip connection events but must not skip more than allowed by the Peripheral latency parameter or the connection fails. See picture below for more details.

../_images/peripheral_latency.png

Diagram representing peripheral latency#

How to modify Peripheral Latency in my project#

To modify this connection parameter, you have to open your basic_ble.syscfg file. Open the BLEPeripheral ConfigurationConnection Update Request Params section. Then, modify the value of Requested Slave Latency with the number of hop increment you want.

../_images/peripheral_latency_modify.png

Peripheral Latency on Sysconfig#

Supervision time-out#

What’s Supervision time-out#

The Supervision time-out parameter is the maximum time between two received packets before the peripheral and the central connection is considered lost. If this time passes without a successful connection event, the device terminates the connection and returns to an unconnected state. This value is fixed at the beginning of the connection and could be between 100ms to 32s in increments of 10ms.

How to modify Supervision time-out in my project#

To modify this connection parameter, you have to open your basic_ble.syscfg file. Open the BLEPeripheral ConfigurationConnection Update Request Params section. Then, modify the value of Requested Conn Timeout (ms) with the value you want.

../_images/supervision_time_out_modify.png

Supervision Time-out on Sysconfig#

Task 5 - End a connection with code execution#

Either the Central or the Peripheral can terminate a connection for any reason. One side initiates termination and the other side must respond before both devices exit the connected state. Use the GAP_TerminateLinkReq() command to terminate an existing connection.

Let’s program the Peripheral to disconnect at the end of the clock implemented in the clockp module section. The function, defined in GAP, tells GAP to terminate the connection. This gets broadcasted to the Central, along with a reason why the connection was terminated. Simultaneously, a GAP_LINK_TERMINATED_EVENT gets posted in the GAP message event queue. (This event gets posted whether the termination was intentional or not.) Let’s try to implement this, knowing that the function to terminate the connection should be like below:

  GAP_TerminateLinkReq(<STORED_HANDLE_ADVERTISE_SET>,0x13);

Warning

Make sure your clock is already implemented as the
clockp module section did, before trying to achieve this section.

Here is a solution how to use GAP_TerminateLinkReq()
  • First let’s start the clock just after the connection is established. To do so call the ClockP_start() function as below:

    The Peripheral_GAPConnEventHandler() function is located in the app_peripheral.c file#
      void Peripheral_GAPConnEventHandler(uint32 event, BLEAppUtil_msgHdr_t *pMsgData)
      {
          switch(event)
          {
              case BLEAPPUTIL_LINK_ESTABLISHED_EVENT:
              {
                  /* Check if we reach the maximum allowed number of connections */
                  if(linkDB_NumActive() < linkDB_NumConns())
                  {
                      /* Start advertising since there is room for more connections */
                      BLEAppUtil_advStart(peripheralAdvHandle_1, &advSetStartParamsSet_1);
                  }
                  else
                  {
                      ClockP_start(clockHandle);//Call the start here!
      
    
    • Call the function to end the connection and restart the advertisement for a later use, in the Peripheral_AppEventHandler() function.

      void Peripheral_AppEventHandler()
      {
        GAP_TerminateLinkReq(peripheralAdvHandle_1,0x13);
        BLEAppUtil_advStart(peripheralAdvHandle_1, &advSetStartParamsSet_1);
      }
    

Hint

Flash your code on your SimpleLink™ CC2340R5 LaunchPad™. You should be disconnected 5s after you established the connection!

Task 6 - Customize your Project#

Further Reading#

In this SimpleLink Academy lab, we have talked a lot about what a Bluetooth LE connection is, but very little about its purpose. Usually, we want to exchange specific information between the two devices. This can be accomplished with Bluetooth Services and Characteristics. If you want to learn about this, you should move on to the SimpleLink Academy module.

References#

Code Composer Studio
Bluetooth Core Specification Version 5.3
BLE Scanning and Advertising
TI SimpleLink Connect App
SimpleLink CC2340R5 LaunchPad
SIMPLELINK-LOWPOWER-F3-SDK
SDK User’s Guide