5.1.1.5 BLE Transparent UART

This section enables users create a central device and send/receive characters between two connected BLE devices over Microchip proprietary Transparent UART profile. The central and peripheral devices in this tutorial are two WBZ351 devices. The following instructions are applicable for a BLE central device.

Users can choose to either run the precompiled Application Example hex file provided on the WBZ351 Curiosity Board or follow the steps to develop the application from scratch.

It is recommended to follow the examples in sequence to understand the basic concepts before progressing to the advanced topics.

Hardware Requirement

Table 5-7. Hardware Prerequisites
S. No. Tool Quantity
1WBZ351 Curiosity Board2
2Micro USB cable2

SDK Setup

Refer to Getting Started with Software Development from Related Links.

Software Requirement

To install Tera Term tool, refer to the Tera Term web page in Reference Documentation from Related Links.

Smartphone Application

None

Programming the Precompiled Hex File or Application Example

Using MPLAB® X IPE:

  1. Central Device – Import and program the precompiled hex file: <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\central\profiles_services\central_trp_uart\hex.
  2. Peripheral Device – Import and program the precompiled hex file: <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\peripheral_trp_uart\hex
  3. For detailed steps, refer to Programming a Device in MPLAB® IPE in Reference Documentation from Related Links.
    Note: Ensure to choose the correct Device and Tool information.

Using MPLAB® X IDE:

  1. Perform the following the steps mentioned in Running a Precompiled Example. For more information, refer to Running a Precompiled Application Example from Related Links.
  2. Central Device – Open and program the application central_trp_uart.X located in <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\central\profiles_services\central_trp_uart\firmware.
  3. Peripheral Device – Open and program the application peripheral_trp_uart.X located in <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\peripheral_trp_uart\firmware.
  4. For more details on how to find the Discover path, refer to Download Application Example from Discover in Running a Precompiled Application Example from Related Links.

Demo Description

Upon programming the demo application, the central device (WBZ351) starts scanning for near by peripheral devices to connect. Once it establishes a connection, the two connected devices can exchange data over UART. The demo application prints the following status messages:
  • Scanning – At the initiation of the scan process.
  • Connected! – Upon successful connection.
  • Disconnected – When the connection is lost, within a terminal emulator interface.
Tera Term Configuration
  • Baud Rate/Speed – 115200 (as configured in SERCOM configuration)
  • Parity – None
  • Data Bits – 8
  • Stop Bits – 1
  • Flow Control – None

Enter application data in the terminal emulator to send it to the connected peripheral device.

Testing

Users must use another WBZ351 Curiosity Board configured as BLE Transparent UART with External Flash OTA. For more details, refer to the BLE Transparent UART with External Flash OTA from Related Links.

Configure two WBZ351 Curiosity boards as peripheral and central devices to experience the demo.

This section assumes that a user has already programmed the peripheral_trp_uart and central_trp_uart application on two WBZ351 Curiosity Boards.

  1. Board 1 – WBZ351 Curiosity Board programmed with peripheral_trp_uart.
    1. Open Tera Term and configure as mentioned below:
      Terminal Settings
      • Baud Rate/Speed – 115200 (as configured in SERCOM configuration)
      • Parity – None
      • Data Bits – 8
      • Stop Bits – 1
      • Flow Control – None
      Figure 5-40. Board 1 Tera Term Settings
    2. For terminal setup configuration, go to Setup>Terminal.
    3. For serial port setup and connection, go to Setup>Serial Port.
    4. Reset the board. Upon reset, the Advertising message appears on the Tera Term.
  2. Board 2 – WBZ351 Curiosity Board Programmed with central_trp_uart.
    1. Open TeraTerm and configure as mentioned below:
      Terminal Settings
      • Baud Rate/Speed – 115200 (as configured in SERCOM configuration)
      • Parity – None
      • Data Bits – 8
      • Stop Bits – 1
      • Flow Control – None
      Figure 5-41. Board 2 Tera Term Settings
    2. For terminal setup configuration, go to Setup>Terminal.
    3. For serial port setup and connection, go to Setup>Serial Port.
    4. Reset the board. Upon reset, the Scanning message appears on the Tera Term.
    5. Upon finding peripheral device with public address {0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6} message Found Peer Node will be displayed and a connection request will be initiated Initiating Connection.
Note: Scanner is configured to scan only for 100s. The user must ensure the peer device is advertising.
After connection establishment, both the peripheral device (Board1) and central device (Board2) displays Connected! message on respective terminal windows.
Figure 5-42. Tera Term Logs
Users can now start sending data back and forth between the central and peripheral devices using the terminal emulator. Characters entered on either terminals will immediately be sent to the peer devices.
Figure 5-43. Tera Term Logs
Note: Demo application is designed to validate the basic data exchange process only. For bulk data transfer, application buffers and flow needs to be updated.

Developing the Application from Scratch using MCC

Follow the steps below to build the application manually:
Note: It is recommended for the new users of the MPLAB Code Configurator to refer MPLAB® Code Configurator (MCC) User’s Guide in Reference Documentation from Related Links.
  1. Create a new harmony project. For more details, see Creating a New MCC Harmony Project from Related Links.
  1. Import Component Configuration
    1. This step helps users to setup the basic components and configuration required to develop this application. The imported file is of format .mc4 and is located in the path <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\central\profiles_services\central_trp_uart\firmware\central_trp_uart.X..
    2. For more details on importing the component configuration, refer to Importing Existing App Example Configuration .
    Note: Import and export functionality of component configuration helps users to start from a known working setup of MCC configuration.
  2. Accept Dependencies or Satisfiers
    1. If prompted to resolve dependencies or add required modules. Click Yes.
    2. MPLAB® MCC automatically adds any required drivers or middleware.
  3. Verify Project Graph
    In Project Graph window, confirm that all expected components are present. For more details, see the following figure.
    Figure 5-44. Project Graph

Verifying Scan and Connection Configuration

  1. Open the Project Graph
    1. In MPLAB® X IDE, with MCC open, locate the Project Graph tab. In the Project Graph tab, the user can see all the components and their relationships to the project.
  2. Select the BLE Stack Component
    1. Click on the BLE Stack component in project graph. This opens the “BLE Stack” component Configuration Options tab.
    2. In the “BLE Stack” Configuration Options tab, the user can set the parameters as per the requirement as illustrated in the following figure.
      Figure 5-45. BLE Stack Configuration
  3. Click Transparent Profile component in the project graph. This opens the “Transparent Profile” component Configuration Options tab.
    1. Check Enable Client Role.
    Figure 5-46. Transparent Profile Configuration

Files and Routines Automatically generated by the MCC

After generating the program source from MCC interface by clicking Generate Code, the user can find the BLE configuration in the following project directories.
Figure 5-47. Project File
Initialization routines for OSAL, RF System, and BLE System are auto-generated by the MCC. See OSAL Libraries Help in Reference Documentation from Related Links.
Figure 5-48. initialization.c
The user can find the BLE stack initialization routine executed during Application Initialization in the project files. The MCC automatically generates this initialization routine. This call initializes and configures the GAP, GATT, SMP, L2CAP and BLE middleware layers.
Figure 5-49. app_ble.c
Auto generated, Advertisement Data Format
Figure 5-50. AD Structures and Types
Table 5-8. Source Files
Source Files Usage
app.cApplication State machine, includes calls for Initialization of all BLE stack (GAP,GATT, SMP and L2CAP) related component configurations

app_ble\app_ble.c

Source Code for the BLE stack related component configurations, code related to function calls from app.c
app_ble\app_ble_handler.cAll GAP, GATT, SMP and L2CAP Event handlers
app_ble\app_trspc_handler.cAll Transparent UART Client related Event handlers
ble_trspc.cAll Transparent Client Functions for user application
Note: app.c is autogenerated and has a state machine based Application code sample. The users can use this template to develop their application.
Header Files
  • ble_gap.h: This header file contains BLE GAP functions and is automatically included in the app.c file.
  • ble_trspc.h: This header file associated with API’s and structures related to BLE Transparent Client functions for application user.
Function Calls
  • MCC generates and adds the code to initialize the BLE Stack GAP, GATT, L2CAP and SMP in APP_BleStackInit() function.
  • APP_BleStackInit() is the API that will be called inside the application’s Initial state APP_STATE_INIT in app.c.

User Application Development

  • Include
    • Include the user action. For more information, refer to User Action from Related Links.
    • The user must include the header file ble_trspc.h in app.c, BLE Transparent UART Server related API’s are available in this file.
    • The user must include the header file osal/osal_freertos_extend.h in app_trsps_handler.c, OSAL related API’s are available in this file.
    • definitions.h in all the files where UART will be used to print debug information.
      Note: definitions.h is not specific to just UART peripheral, instead it must be included in all application source files where peripheral functionality will be exercised.
  • Start Scanning
    // Scanning Enabled
    BLE_GAP_SetScanningEnable(true, BLE_GAP_SCAN_FD_ENABLE, BLE_GAP_SCAN_MODE_OBSERVER, 1000); //
    Output the state string to UART
    SERCOM0_USART_Write((uint8_t *)"Scanning \r\n", 11);
    Figure 5-51. Start Scanning
    • This API is called in the application’s initial state, APP_STATE_INIT, in app.c. The scan duration is 100 seconds.
  • Scan Results and initiating a BLE Connection
    • BLE_GAP_EVT_ADV_REPORT event is generated upon finding Advertisements on legacy channels.
    • The user can initiate a BLE connection by using the BLE_GAP_CreateConnection(&createConnParam_t; API.
      // code snippet to filter scan results and initiate connection
      if (p_event->eventField.evtAdvReport.addr.addr[0] == 0xA1 && p_event->eventField.evtAdvReport.addr.addr[1] == 0xA2)
      {
          SERCOM0_USART_Write((uint8_t *)"Found Peer Node\r\n", 17);
          BLE_GAP_CreateConnParams_T createConnParam_t;
          createConnParam_t.scanInterval = 0x3C; // 37.5 ms
          createConnParam_t.scanWindow = 0x1E; // 18.75 ms
          createConnParam_t.filterPolicy = BLE_GAP_SCAN_FP_ACCEPT_ALL;
          createConnParam_t.peerAddr.addrType = p_event->eventField.evtAdvReport.addr.addrType;
          memcpy(createConnParam_t.peerAddr.addr, p_event->eventField.evtAdvReport.addr.addr, GAP_MAX_BD_ADDRESS_LEN);
          createConnParam_t.connParams.intervalMin = 0x10; // 20ms
          createConnParam_t.connParams.intervalMax = 0x10; // 20ms
          createConnParam_t.connParams.latency = 0;
          createConnParam_t.connParams.supervisionTimeout = 0x48; // 720ms
          SERCOM0_USART_Write((uint8_t *)"Initiating Connection\r\n", 23);
          BLE_GAP_CreateConnection(&createConnParam_t);
      }
    
    Figure 5-52. app_ble_handler.c
  • Connected and Disconnected Events
    • In app_ble_handler.c "BLE_GAP_EVT_CONNECTED" event will be generated when a BLE connection is completed
  • Connection Handler
    • The user needs to save the connection handle associated with the peer peripheral device for data exchange after a BLE connection.
    • This information is available in the p_event->eventField.evtConnect.connHandle.
      // Global variable
      extern uint16_t conn_hdl;
      
      // Connected event
      SERCOM0_USART_Write((uint8_t *)"Connected\r\n", 11);
      conn_hdl = p_event->eventField.evtConnect.connHandle;
      
      // Disconnected event
      SERCOM0_USART_Write((uint8_t *)"Disconnected\r\n", 14);
      
      Figure 5-53. app_ble_handler.c
  • Scan Timeout Event
    • In app_ble_handler.c BLE_GAP_EVT_SCAN_TIMEOUT event is generated when BLE Scan duration expires.
    SERCOM0_USART_Write((uint8_t *)"Scan Completed! \r\n", 18);
    Figure 5-54. Scan Timeout Event
  • Scan Timeout Event
    • In app_ble_handler.c BLE_GAP_EVT_SCAN_TIMEOUT event is generated when BLE Scan duration expires.
    SERCOM0_USART_Write((uint8_t *)"Scan Completed! \r\n", 18);
    Figure 5-55. Scan Timeout Event
  • Transmit Data
    • Add APP_MSG_UART_CB to the generated APP_MsgId_T in app.h.
      Figure 5-56. Transmit Data
    • Use the BLE_TRSPC_SendData(conn_hdl , 1, &data); API for sending data towards the central device.
      Note: The precompiled application example uses a UART callback to initiate the data transmission upon receiving a character on UART.

    Here is an example implementation for transmitting the received data over UART using the BLE_TRSPC_SendData API.

    uint16_t conn_hdl;// connection handle info captured @BLE_GAP_EVT_CONNECTED event
    uint8_t uart_data;
    void uart_cb(SERCOM_USART_EVENT event, uintptr_t context)
    {
      APP_Msg_T   appMsg;   
      // If RX data from UART reached threshold (previously set to 1)
      if( event == SERCOM_USART_EVENT_READ_THRESHOLD_REACHED )
      {
        // Read 1 byte data from UART
        SERCOM0_USART_Read(&uart_data, 1);
    
        appMsg.msgId = APP_MSG_UART_CB;
        OSAL_QUEUE_Send(&appData.appQueue, &appMsg, 0);     
      }
    }
    void APP_UartCBHandler()
    {
        // Send the data from UART to connected device through Transparent service
        BLE_TRSPC_SendData(conn_hdl, 1, &uart_data);     
    }
    
    ////////////////////////////////////////////////////////////////////////////////////
    
      // Register call back when data is available on UART for Peripheral Device to send
      // Enable UART Read
      SERCOM0_USART_ReadNotificationEnable(true, true);
      // Set UART RX notification threshold to be 1
      SERCOM0_USART_ReadThresholdSet(1);
      // Register the UART RX callback function
      SERCOM0_USART_ReadCallbackRegister(uart_cb, (uintptr_t)NULL);
    
    ////////////////////////////////////////////////////////////////////////////////////
    
    //If msg received in Queue, handle the Queue message based on msgID
    if (OSAL_QUEUE_Receive(&appData.appQueue, &appMsg, OSAL_WAIT_FOREVER))
      {
        if(p_appMsg->msgId==APP_MSG_BLE_STACK_EVT)
        {
         // Pass BLE Stack Event Message to User Application for handling
         APP_BleStackEvtHandler((STACK_Event_T *)p_appMsg->msgData);
         }
         else if(p_appMsg->msgId==APP_MSG_BLE_STACK_LOG)
         {
         // Pass BLE LOG Event Message to User Application for handling
         APP_BleStackLogHandler((BT_SYS_LogEvent_T *)p_appMsg->msgData);
          }
          else if(p_appMsg->msgId==APP_MSG_UART_CB)
          {
           // Transparent UART Client Data transfer Event
           APP_UartCBHandler();
           }                
      }
    
    Figure 5-57. app.c
    Figure 5-58. app.c
    Figure 5-59. app.c
  • Receive Data
    • The system generates the BLE_TRSPC_EVT_RECEIVE_DATA event when the central device sends data.
    • Users need to use the BLE_TRSPC_GetDataLength(&data_len) API to extract the length of application data received.
    • To retrieve the data, use the BLE_TRSPC_GetData(&conn_hdl, data); API, where conn_hdl is the value obtained from the Connection Handler section.
    Note: BLE_TRSPC_Event_T p_event structure stores the information about BLE transparent UART callback functions.

    Example Implementation for printing the received data from peripheral device over UART

      /* TODO: implement your application code.*/
        uint16_t data_len;
        uint8_t *data;
        // Retrieve received data length
        BLE_TRSPC_GetDataLength(p_event->eventField.onReceiveData.connHandle, &data_len);
        // Allocate memory according to data length
        data = OSAL_Malloc(data_len);
        if(data == NULL)
        break;
        // Retrieve received data
        BLE_TRSPC_GetData(p_event->eventField.onReceiveData.connHandle, data);
        // Output received data to UART
        SERCOM0_USART_Write(data, data_len);
        // Free memory
        OSAL_Free(data);
    Figure 5-60. app_trspc_handler.c

The users can exercise various other BLE Advertisement functionalities. For more information, refer to MPLAB Harmony Wireless BLE in Reference Documentation from Related Links.

Next Steps

See BLE Multilink Transparent UART from Related Links.