5.1.2.7 BLE Transparent UART with External Flash OTA

This section explains how to create a peripheral device and send/receive characters between two connected BLE devices over the Microchip Proprietary Transparent UART Profile with the External Flash OTA feature enabled. The peripheral device will be the WBZ351 Curiosity board and the central device can either be a smartphone with a Light Blue app or another WBZ351 Curiosity board. To demo the external flash OTA feature, the Microchip MBD App should be used. The instructions mentioned below are applicable for a BLE Peripheral 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-24. Hardware Prerequisites
S. No. Tool Quantity
1WBZ351 Curiosity Board1
2Micro USB cable1
3Android/iOS Smartphone1

SDK Setup

Refer to Getting Started with Software Development from Related Links.

Software

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

Smartphone App

Light Blue iOS/Android app available in stores

Programming the Precompiled Hex File or Application Example

Using MPLAB® X IPE:

  1. Import and program the precompiled hex file: <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\peripheral_trp_uart\hex\peripheral_trp_uart.X.production.signed.unified.1.0.0.0.hex.
  2. 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. Open and program the application: <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\peripheral_trp_uart\firmware\peripheral_trp_uart.X.
  3. 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

This application enables users to send data back and forth over UART between two connected BLE devices. On Reset, demo will print “Advertising” which denotes the start of advertisements and then “Connected” when connection is established. Application data to be sent to the connected central device (smartphone or another WBZ351 Curiosity board) is entered in a terminal emulator like Tera Term and the application data to be sent to the peripheral device is entered in the app.

Testing

  1. Using a micro USB cable, connect the Debug USB on the Curiosity board to a PC.
  2. Program the precompiled hex file or application example as mentioned.
  3. Open Tera Term:
    • Set the “Serial Port” to USB Serial Device.
    • Speed to 115200.
    For more details on how to set the “Serial Port” and “Speed”, refer to COM Port Setup in Running a Precompiled Application Example from Related Links.
  4. Press the Reset Switch on the Curiosity board. “Firmware Revision:1.0.0.0.0” and“Advertising” must be displayed in Tera Term.
  5. Launch the Light Blue mobile app and search for the device name “pic32cx-bz” and press Connect.
    Note: The following screen shots captured are for the Light Blue app on the android platform. The Light Blue app usage in the iOS platform will be same. The noticeable differences in terms of user interfaces are captured in the later sections.
  6. To receive data from the WBZ351 Curiosity board (peripheral device) to the mobile app (central device), select UUID: 49535343-1E4D-4BD9-BA61-23C647249616 then select Subscribe.
    Note: In iOS, select Listen for notifications instead of Subscribe.
  7. Now change the “Data format” to “UTF-8 String” in the Light Blue mobile app then enter “test” on Tera Term. The same data must be displayed in the app.
    Note: In iOS, click on the “Hex” tab at the top right corner and select “UTF-8 String”.
    Note: You may not be able to see “test” on your Tera Term as you type.
  8. To send data from the mobile app (central device) to the WBZ351 Curiosity Board (peripheral device), select UUID: 49535343-8841-43F4-A8D4-ECBE34729BB3
  9. Change the “Data format” to “UTF-8 String” then enter “trp uart” and click Write. The same data must be displayed in Tera Term.
    Note: In iOS, click on the “Hex” tab at the top right corner and select “UTF-8 String”.

    Note: Users can use another WBZ351 Curiosity board configured as BLE Transparent UART (central) instead of using a mobile app. For more information, refer to BLE Transparent UART from Related Links.

Developing this Application from scratch using MPLAB Code Configurator

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.

  2. Setup the basic components and configuration required to develop this application, import component configuration: <Discover Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\peripheral_trp_uart\firmware\peripheral_trp_uart.X\peripheral_trp_uart.mc4. For more details on importing the component configuration, refer to Importing Existing App Example Configuration from Related Links.
    Note: Import and Export functionality of the Harmony component configuration will help users to start from a known working setup of the MCC configuration.
  3. Accept dependencies or satisfiers when prompted.

  4. Verify if the Project Graph window has all the expected configuration.

Verify Advertisement,Connection and Transparent UART Profile Configuration

  1. Select BLE Stack component in the Project Graph and configure the following in the Configuration Options panel.

  2. Select Transparent Profile component in the project graph and configure the following.

Files and Routines Automatically Generated by the MCC

After generating the program source from the MCC interface by clicking Generate Code, the BLE configuration source and header files can then be found in the following project directories.

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. Initialization routine executed during program initialization can be found in the project files.

The BLE stack initialization routine executed during Application Initialization can be found in project files. This initialization routine is automatically generated by the MCC. This call initializes and configures the GAP, GATT, SMP, L2CAP and BLE middleware layers.

Figure 5-147. .
Autogenerated, Advertisement Data Format
Figure 5-148. AD Structures and Types
Table 5-25. Source Files
Source Files Usage
app.cApplication State machine, includes calls for Initialization of all BLE stack (GAP,GATT, SMP, L2CAP) related component configurations
app_ble\app_ble.cSource 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_trsps_handler.cAll Transparent UART Server related Event handlers
ble_trsps.cAll Transparent Server Functions for user application
Note:

app.c is autogenerated and has a state machine-based application code sample. Users can use this template to develop their own application.

Header Files

  • ble_gap.h contains BLE GAP functions and is automatically included in app.c

  • ble_trsps.h is associated with APIs and structures related to the BLE Transparent Client functions for the application user

Function Calls

  • MCC generates and adds the code to initialize the BLE Stack GAP, GATT, SMP and L2CAP in APP_BleStackInit()
  • APP_BleStackInit() is the API that will be called inside the Applications 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.

  • ble_trsps.h in app.c contains BLE Transparent UART Server related APIs
  • osal/osal_freertos_extend.h in app_trsps_handler.c contain OSAL related APIs
  • definitions.h must be included in all the files where UART will be used to print debug information

Set PUBLIC Device Address in app_ble.c

  • BLE_GAP_SetDeviceAddr(&devAddr);

     BLE_GAP_Addr_T devAddr;
    devAddr.addrType = BLE_GAP_ADDR_TYPE_PUBLIC;
    devAddr.addr[5] = 0xA3;
    devAddr.addr[4] = 0xB2;
    devAddr.addr[3] = 0xC3;
    devAddr.addr[2] = 0xD4;
    devAddr.addr[1] = 0xA2;
    devAddr.addr[0] = 0xA1; 

// Configure device address
    BLE_GAP_SetDeviceAddr(&devAddr);

Start Advertisement in app.c

  • BLE_GAP_SetAdvEnable(0x01, 0x00);

Connected & Disconnected Events

  • In app_ble_handler.c, BLE_GAP_EVT_CONNECTED event will be generated when a BLE connection is completed

Connection Handler

  • Connection handle associated with the peer peripheral device needs to be saved for data exchange after a BLE connection
  • p_event->eventField.evtConnect.connHandle has this information

Transmit Data

  • Add APP_MSG_UART_C to the generated APP_MsgId_T
    Figure 5-149. .
  • BLE_TRSPS_SendData(conn_hdl, 1, &data); is the API to be used for sending data to the central device
    Note: The precompiled application example uses a UART callback to initiate the data transmission upon receiving a character in UART.
  • Example for transmitting over UART using the BLE_TRSPS_SendData() API
uint16_t conn_hdl;// connection handle info captured @BLE_GAP_EVT_CONNECTED event
uint16_t ret;
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_TRSPS_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);
Figure 5-150. .
Figure 5-151. .
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)
{
   // Pass BLE UART Data transmission target BLE UART Device handling
   APP_UartCBHandler();
}
Figure 5-152. .

Receive Data

  • BLE_TRSPS_EVT_RECEIVE_DATA is the event generated when data is sent from the central device
  • Use the BLE_TRSPS_GetDataLength(p_event->eventField.onReceiveData.connHandle, &data_len); API to extract the length of the application data received
  • BLE_TRSPS_GetData(p_event->eventField.onReceiveData.connHandle, data); API is used to retrieve the data
    Note: BLE_TRSPS_Event_T p_event structure stores the information about the BLE transparent UART callback functions.
  • Example for printing the received data from the central device over UART
Note: Users can explore more BLE Advertisement functionalities using the BLE Stack APIs. For more information, refer to BLE Stack in Reference Documentation from Related Links.

External Flash OTA DFU Feature Addition

This feature is using SST26VF064B External flash. WBZ351 Curiosity Board is built with SST26VF064B External flash. If the other external flash is in use, extra code modification in the middleware is required to replace the SST26VF064B flash driver.

Copy below items from the buckland 2nd bootloader project to path of peripheral_trp_uart\firmware\peripheral_trp_uart.X:

  • java_256r1_key.pem
  • java_384r1_key.pem
  • autoload.py
  • buckland2ndBootloader.X.production.signed.hex

    the prebuilt hex of the buckland bootloader

Open the project and check if “autoload.py” exists in the Script Files folder in MPLAB project setting.

Add the 2nd bootloader hex file as a loadable file from the project property page.

Adding the external flash OTA feature via MCC:

  1. Add OTA profile and OTA service(see circle 1).

    Enable Server Role.

  2. Add the external flash and QSPI driver(see circle 4)

    Set QSPI_BAUD_RATE from 0 to 32,000,000.

  3. Uncheck the option of “PDS_USES_BOOT_FLASH”.

    So the PDS will not occupy boot flash, which is then occupied by the 2nd bootloader.

  4. Add “BLE OTA APP SERVICE” component(see circle 2).

    Adding “BLE OTA APP SERVICE” will automatically include the dependencies like RCON, APP_TIMER_SERVICE and “Device Information Serive”. The firmware revision must be set correctly.

  5. Configure “BLE OTA APP SERVICE”.

    Enable  Flash Image ID and set to 0x9E000003 which is the same as the one set in project setting(see link below)

    Enable Image Decryption and set the AES Key and Init Vector to the same values set in project setting (see link).

    This will automatically add dependencies of  wolfCrypt Library and LIB_WOLFCRYPT' (see circle 3). Make sure to enable  AES-CBC mode.

  6. BLE_Stack component setting- DFU module enabling external flash.

    This module generates the code needed for device firmware upgrade middleware for writing the OTA image into external flash.

  7. For more details on code generation, refer to MPLAB Code Configurator (MCC) Code Generation from Related Links.

    After generating the code from MCC tool by clicking Generate button, below is the project folder structure.

OTA Application Development

  1. Compile MCC auto generated project.
    • Compile the MCC auto generated project as below.
    • Addressing the mandatory error (if not already done): User action required in app_user_edits.c. Follow the steps mentioned in the note and do the necessary changes. Then comment the #error message as below.
  2. Call BLE OTA Init function in “app.c” and add the include file.

    APP_OTA_HDL_Init(); (see line 155)

    #include “app_ota/app_ota_handler.h

  3. Call BLE OTA event handler function in “app_ble/app_otaps_handler.c”.

    APP_OTA_EvtHandler(p_event);

    #include “../app_ota/app_ota_handler.h”.

  4. Uncomment timer message ID's in “app_timer/app_timer.c” needed for OTA error handling and reboot timer. When the timer is fired, the related message is posted in freeRTOS application task queue.
  5. Define the timer message ID's in APP_MsgId_T structure in “app.h”.

    APP_TIMER_OTA_TIMEOUT_MSG,

    APP_TIMER_OTA_REBOOT_MSG,

  6. Call OTA timer handlers in APP_Tasks() in “app.c”.

  7. Call DIS service Init function in “app.c” and add the include file.

    BLE_DIS_Add();

    #include “ble_dis/ble_dis.h

  8. Call BLE gap connected/disconnected event handler in “app_ble/app_ble_handler.c” . app_ble_conn_handler.c handles the events and also restarts the advertising when disconnected.

    APP_BleGapConnEvtHandler(p_event);

    #include “../app_ble_conn_handler.h

  9. If the “Standby Sleep mode” low power functionality is enabled in the application, during the OTA upgrade procedure, it is required to disable the device entering into sleep mode. Add the below check in app_idle_task() when the BT_SYS_EnterSleepMode() is called.
    if (APP_OTA_HDL_GetOTAMode() != APP_OTA_MODE_OTA)
        BT_SYS_EnterSleepMode(RTC_Timer32FrequencyGet(), RTC_Timer32CounterGet()); 
    
  10. Compile the project for no errors.

    No error must be found in this step.

Create a bin File for OTA DFU

  1. Open the MPLAB project properties.
  2. Make sure the FW version is consistent between ble_dis.h and FW_IMG_REV in Header of project properties.

    Check “Header” settings tab:

  3. Set OTA setting.

    Make sure the setting items are consistent with the MCC component of “BLE OTA APP SERVICE”  in the above step.

  4. Click “Create OTA File” to generate the OTA bin file.

OTA DFU Demo

The below BLE OTA demo steps are common for any application implementing OTA functionality.

  1. Program the precompiled Hex as step above.
  2. Power up and the output of curiosity board must be:

    The string of “Recreated hash, Jump to App” is the output from the 2nd bootloader during booting.
    The string of “Firmware Revision...” is output from the application firmware.

  3. Open MBD APP.

    Click “OTA DFU” icon.

  4. Connect the curiosity board.

    Pairing is required during connection.

  5. Select the image for the OTA.

    The images here are created in the above step.

  6. OTA Firmware revision confirmation.
  7. OTA done.
  8. The DFU is conducted by the 2nd bootloader after curiosity board reset.

    The string of “Found Unauthenticated … Jump to App” is the output from the 2nd bootloader during DFU and booting.
    The new 1.0.0.1 revision Application firmware is booted successfully.

Where to Go from Here

  • BLE Sensor App – This application utilizes the Transparent UART building block, see BLE Sensor with Touch from Related Links.