4.1.2.7 BLE Transparent UART with External Flash OTA

Getting Started

Getting Started with Peripheral Building Blocks

BLE Connection --> BLE Transparent UART with External Flash OTA

Introduction

This document will help users 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 of this document can choose to just run the precompiled Application Example hex file on the WBZ351 Curiosity board and experience the demo or can go through the steps involved in developing this application from scratch.

These examples each build on top of one another. We strongly recommend that you follow the examples in order, by learning the basic concepts first before progressing to the more advanced topics.

Hardware Required

Tool Qty
WBZ351 Curiosity Board1
Micro USB cable1
Android/iOS Smartphone1

SDK Setup

Getting Started with Software Development

Software

Tera Term

Smartphone App

Light Blue iOS/Android app available in stores

Programming the precompiled hex file or Application Example

Programming the hex file using MPLABX IPE

  1. Import and program the Precompiled Hex file: <Harmony Content 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 more details on the steps, go to Programming A Device

Caution: Ensure to choose the correct Device and Tool information

Programming the Application using MPLABX IDE

  1. Follow the steps mentioned in Running a Precompiled Example

  2. Open and program the Application: <Harmony Content Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\peripheral_trp_uart\firmware\peripheral_trp_uart.X

For more details on how to find the Harmony Content Path, refer to Installing a MCC Plugin

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 and set the “Serial Port” to USB Serial Device and “Speed” to 921600.

    For more details on how to set the “Serial Port” and “Speed”, refer to COM Port Setup

  4. Press the Reset Switch on the Curiosity board. "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 WBZ451 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 should 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 should be displayed in Tera Term.
    Note: In iOS, click on the “Hex” tab at the top right corner and select “UTF-8 String”

    Users can use another WBZ351 Curiosity board configured as BLE Transparent UART (central) as a central device instead of using a mobile app

Developing this Application from scratch using MPLAB Code Configurator

This section explains the steps required by a user to develop this application example from scratch using the MPLAB Code Configurator

Note: It is recommended that new users of the MPLAB Code Configurator to go through this overview
  1. Create a new MCC Harmony Project

  2. To setup the basic components and configuration required to develop this application, import component configuration: <Harmony Content Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\peripheral_trp_uart\firmware\peripheral_trp_uart.X\peripheral_trp_uart.mc3 For more details, refer to Import existing App Example Configuration
    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. To accept dependencies or satisfiers, select "Yes"

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

Verify Advertisement,Connection and Transparent UART Profile Configuration

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

  2. Select the 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.

The OSAL, RF System and BLE System initialization routine executed during program initialization can be found in the project file. This initialization routine is automatically generated by the MCC.

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 4-112. .

Autogenerated, advertisement data format

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

  • User Action is required

  • 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 4-113. .
  • 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 4-114. .
Figure 4-115. .
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 4-116. .

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 exercise other various BLE functionalities by using the BLE Stack APIs

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 should 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. Generate code by MCC Instructions on how to Generate Code

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

OTA Application Devevelopment

  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 procedues, 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 should 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 curiocity board should 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 with Touch – this app utilizes the Transparent UART building block