60
ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This document demonstrates how to use the ATSAMB11 Bluetooth ® Low Energy SoC by building a custom specific profile using the Microchip BluSDK Smart Software Development Kit. This document covers: Technical overview of the ATSAMB11 board from hardware architecture to software design Description of the required process for developing the Bluetooth Low Energy peripheral application with the ATSAMB11 Handling of Bluetooth Low Energy custom services and characteristics Figure 1. Bluetooth Low Energy System Solution with ATSAMB11 © 2018 Microchip Technology Inc. Application Note DS00002715A-page 1

ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

ATSAMB11 ATSAMB11 Custom Service Implementation

Introduction

This document demonstrates how to use the ATSAMB11 Bluetoothreg Low Energy SoC by building acustom specific profile using the Microchip BluSDK Smart Software Development Kit This documentcovers

bull Technical overview of the ATSAMB11 board from hardware architecture to software designbull Description of the required process for developing the Bluetooth Low Energy peripheral application

with the ATSAMB11bull Handling of Bluetooth Low Energy custom services and characteristics

Figure 1 Bluetooth Low Energy System Solution with ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 1

Table of Contents

Introduction1

1 Getting Started 311 Software Prerequisites 312 ATSAMB11 Embedded Firmware513 ATSAMB11 Software API 614 Hardware Prerequisites815 Hardware Setup 9

2 Creating and Initializing the Project 1121 Creating Project from ASF1122 Compiling and Testing the Project14

3 Establishing Connection with Central Device 1731 Configuring and Starting the Advertisement Process1832 Managing GAP events 25

4 SetupHandling of Pre-Defined Service from ASF3041 Adding Device Info Service Component from ASF Wizard to Project 3142 Configuring and Loading Device Information Service 33

5 Setting up and Handling Custom Service3851 Configuring and Loading the Custom Environment Service3952 Updating the Temperature Characteristic44

6 Appendix A Pre-defined Service Software Solution 50

7 Appendix B Custom Service Software Solution52

8 Document Revision History 56

The Microchip Web Site 57

Customer Change Notification Service57

Customer Support 57

Microchip Devices Code Protection Feature 57

Legal Notice58

Trademarks 58

Quality Management System Certified by DNV59

Worldwide Sales and Service60

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 2

1 Getting StartedThis chapter describes the setup and basic software and hardware requirements

11 Software Prerequisites

111 Installation Steps of Atmel Studio 71 Download and install the Atmel Studio software2 Install the Advanced Software Framework (ASF) package

Note bull The software for ATSAMB11ZR module is supported with ASF 3362 and abovebull If DFP version is not 23190 or above update the DFP version to 23190 For more details

on installing the ATSAMB11 Device Pack see Installing ATSAMB11 Device Pack usingDevice Pack Manager

Note  For more information on the previous releases refer to the Atmel Studio Release Notes (42685J)available on the Microchip web page

112 Installing Microchip Bluetooth Data Application on a Mobile Device1 Open the App Store (iPhoneregiOS) or Google Playtrade Store (Android) on the mobile device2 Search for ldquoMicrochip Bluetooth Datardquo3 Click Install to install the application on the device The following figure shows the dashboard of the

Microchip Bluetooth Data appFigure 1-1 Microchip Bluetooth Data Dashboard

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 3

113 Installing ATSAMB11 Device Pack using Device Pack Manager1 Open Atmel Studio2 Choose Tools gt Device Pack Manager

Figure 1-2 Start Page AtmelStudio Window

3 Click Check for Updates to check new pack of the ATSAMB11 and then click Install selectedpacksFigure 1-3 Device Pack Manager Window

4 Click Install By clicking install the user agrees to the license terms mentioned

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 4

Figure 1-4 End User License Agreement

5 After a successful update Close the Pack Manager and restart Atmel StudioFigure 1-5 Device Pack Manager Dialog Box

12 ATSAMB11 Embedded FirmwareThe Bluetooth Low Energy communication is based on the network stack stored in the ATSAMB11 ReadOnly Memory (ROM) This stack requires Generic Access Profile (GAP) parameters and attributes to befunctional which are pushed from the application into the ATSAMB11 internal SRAM using internalmessages

The ROM coded firmware embeds the layers of the Bluetooth Low Energy stack that runs on top of theperipheral drivers and RTOS scheduler

bull Generic Access Profile (GAP)

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 5

GAP controls the Bluetooth Low Energy connection advertising makes the device visible to theoutside world and determines how two devices interact with each other GAP defines two mainroles for the Bluetooth Low Energy device Central and Peripheral

bull Generic Attribute Profile (GATT) and Attribute Protocol (ATT)GATT defines how the Bluetooth Low Energy device transfers the data The GATT process isbased on services and characteristics stored in Attribute Protocol (ATT) ATT is a simple look uptable stored in the ATSAMB11 SRAM

bull Security Manager (SM)The SM defines the procedure for pairing authentication and encryption between Bluetooth LowEnergy devices This layer is mainly used if security is requested on that particular connection

bull Logical Link Control and Adaptation Protocol (L2CAP)L2CAP supports high level protocol multiplexing packet segmentationreassembly and conveyingthe quality of service information L2CAP permits applications to transmit and receive the datapackets with channel flow control and retransmission

bull Direct Test Mode (DTM)DTM allows testing of the radios Physical Layer (PHY) by transmitting and receiving the test packetsequences This is often used in compliance and production line testing without the need to gothrough the complete Bluetooth Low Energy Protocol Stack

13 ATSAMB11 Software APIThe ATSAMB11 is provided with a dedicated host software API layer This API layer provides an easyand reliable solution to add Bluetooth Low Energy capabilities to any user application The API provides aset of high level Bluetooth functions with abstraction of the transport protocol used between the userapplication and the ATSAMB11

Figure 1-6 ATSAMB11 Software API

The API operation relies on a request-response mechanism The specific requests are sent to theATSAMB11 through a corresponding API function call The event messages are then returned by theATSAMB11 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the application according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flow

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 6

Figure 1-7 Bluetooth Low Energy Peripheral Application Flow

CAUTION The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time

The following figure describes the BluSDK Smart file architecture

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 7

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 2: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Table of Contents

Introduction1

1 Getting Started 311 Software Prerequisites 312 ATSAMB11 Embedded Firmware513 ATSAMB11 Software API 614 Hardware Prerequisites815 Hardware Setup 9

2 Creating and Initializing the Project 1121 Creating Project from ASF1122 Compiling and Testing the Project14

3 Establishing Connection with Central Device 1731 Configuring and Starting the Advertisement Process1832 Managing GAP events 25

4 SetupHandling of Pre-Defined Service from ASF3041 Adding Device Info Service Component from ASF Wizard to Project 3142 Configuring and Loading Device Information Service 33

5 Setting up and Handling Custom Service3851 Configuring and Loading the Custom Environment Service3952 Updating the Temperature Characteristic44

6 Appendix A Pre-defined Service Software Solution 50

7 Appendix B Custom Service Software Solution52

8 Document Revision History 56

The Microchip Web Site 57

Customer Change Notification Service57

Customer Support 57

Microchip Devices Code Protection Feature 57

Legal Notice58

Trademarks 58

Quality Management System Certified by DNV59

Worldwide Sales and Service60

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 2

1 Getting StartedThis chapter describes the setup and basic software and hardware requirements

11 Software Prerequisites

111 Installation Steps of Atmel Studio 71 Download and install the Atmel Studio software2 Install the Advanced Software Framework (ASF) package

Note bull The software for ATSAMB11ZR module is supported with ASF 3362 and abovebull If DFP version is not 23190 or above update the DFP version to 23190 For more details

on installing the ATSAMB11 Device Pack see Installing ATSAMB11 Device Pack usingDevice Pack Manager

Note  For more information on the previous releases refer to the Atmel Studio Release Notes (42685J)available on the Microchip web page

112 Installing Microchip Bluetooth Data Application on a Mobile Device1 Open the App Store (iPhoneregiOS) or Google Playtrade Store (Android) on the mobile device2 Search for ldquoMicrochip Bluetooth Datardquo3 Click Install to install the application on the device The following figure shows the dashboard of the

Microchip Bluetooth Data appFigure 1-1 Microchip Bluetooth Data Dashboard

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 3

113 Installing ATSAMB11 Device Pack using Device Pack Manager1 Open Atmel Studio2 Choose Tools gt Device Pack Manager

Figure 1-2 Start Page AtmelStudio Window

3 Click Check for Updates to check new pack of the ATSAMB11 and then click Install selectedpacksFigure 1-3 Device Pack Manager Window

4 Click Install By clicking install the user agrees to the license terms mentioned

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 4

Figure 1-4 End User License Agreement

5 After a successful update Close the Pack Manager and restart Atmel StudioFigure 1-5 Device Pack Manager Dialog Box

12 ATSAMB11 Embedded FirmwareThe Bluetooth Low Energy communication is based on the network stack stored in the ATSAMB11 ReadOnly Memory (ROM) This stack requires Generic Access Profile (GAP) parameters and attributes to befunctional which are pushed from the application into the ATSAMB11 internal SRAM using internalmessages

The ROM coded firmware embeds the layers of the Bluetooth Low Energy stack that runs on top of theperipheral drivers and RTOS scheduler

bull Generic Access Profile (GAP)

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 5

GAP controls the Bluetooth Low Energy connection advertising makes the device visible to theoutside world and determines how two devices interact with each other GAP defines two mainroles for the Bluetooth Low Energy device Central and Peripheral

bull Generic Attribute Profile (GATT) and Attribute Protocol (ATT)GATT defines how the Bluetooth Low Energy device transfers the data The GATT process isbased on services and characteristics stored in Attribute Protocol (ATT) ATT is a simple look uptable stored in the ATSAMB11 SRAM

bull Security Manager (SM)The SM defines the procedure for pairing authentication and encryption between Bluetooth LowEnergy devices This layer is mainly used if security is requested on that particular connection

bull Logical Link Control and Adaptation Protocol (L2CAP)L2CAP supports high level protocol multiplexing packet segmentationreassembly and conveyingthe quality of service information L2CAP permits applications to transmit and receive the datapackets with channel flow control and retransmission

bull Direct Test Mode (DTM)DTM allows testing of the radios Physical Layer (PHY) by transmitting and receiving the test packetsequences This is often used in compliance and production line testing without the need to gothrough the complete Bluetooth Low Energy Protocol Stack

13 ATSAMB11 Software APIThe ATSAMB11 is provided with a dedicated host software API layer This API layer provides an easyand reliable solution to add Bluetooth Low Energy capabilities to any user application The API provides aset of high level Bluetooth functions with abstraction of the transport protocol used between the userapplication and the ATSAMB11

Figure 1-6 ATSAMB11 Software API

The API operation relies on a request-response mechanism The specific requests are sent to theATSAMB11 through a corresponding API function call The event messages are then returned by theATSAMB11 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the application according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flow

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 6

Figure 1-7 Bluetooth Low Energy Peripheral Application Flow

CAUTION The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time

The following figure describes the BluSDK Smart file architecture

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 7

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 3: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

1 Getting StartedThis chapter describes the setup and basic software and hardware requirements

11 Software Prerequisites

111 Installation Steps of Atmel Studio 71 Download and install the Atmel Studio software2 Install the Advanced Software Framework (ASF) package

Note bull The software for ATSAMB11ZR module is supported with ASF 3362 and abovebull If DFP version is not 23190 or above update the DFP version to 23190 For more details

on installing the ATSAMB11 Device Pack see Installing ATSAMB11 Device Pack usingDevice Pack Manager

Note  For more information on the previous releases refer to the Atmel Studio Release Notes (42685J)available on the Microchip web page

112 Installing Microchip Bluetooth Data Application on a Mobile Device1 Open the App Store (iPhoneregiOS) or Google Playtrade Store (Android) on the mobile device2 Search for ldquoMicrochip Bluetooth Datardquo3 Click Install to install the application on the device The following figure shows the dashboard of the

Microchip Bluetooth Data appFigure 1-1 Microchip Bluetooth Data Dashboard

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 3

113 Installing ATSAMB11 Device Pack using Device Pack Manager1 Open Atmel Studio2 Choose Tools gt Device Pack Manager

Figure 1-2 Start Page AtmelStudio Window

3 Click Check for Updates to check new pack of the ATSAMB11 and then click Install selectedpacksFigure 1-3 Device Pack Manager Window

4 Click Install By clicking install the user agrees to the license terms mentioned

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 4

Figure 1-4 End User License Agreement

5 After a successful update Close the Pack Manager and restart Atmel StudioFigure 1-5 Device Pack Manager Dialog Box

12 ATSAMB11 Embedded FirmwareThe Bluetooth Low Energy communication is based on the network stack stored in the ATSAMB11 ReadOnly Memory (ROM) This stack requires Generic Access Profile (GAP) parameters and attributes to befunctional which are pushed from the application into the ATSAMB11 internal SRAM using internalmessages

The ROM coded firmware embeds the layers of the Bluetooth Low Energy stack that runs on top of theperipheral drivers and RTOS scheduler

bull Generic Access Profile (GAP)

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 5

GAP controls the Bluetooth Low Energy connection advertising makes the device visible to theoutside world and determines how two devices interact with each other GAP defines two mainroles for the Bluetooth Low Energy device Central and Peripheral

bull Generic Attribute Profile (GATT) and Attribute Protocol (ATT)GATT defines how the Bluetooth Low Energy device transfers the data The GATT process isbased on services and characteristics stored in Attribute Protocol (ATT) ATT is a simple look uptable stored in the ATSAMB11 SRAM

bull Security Manager (SM)The SM defines the procedure for pairing authentication and encryption between Bluetooth LowEnergy devices This layer is mainly used if security is requested on that particular connection

bull Logical Link Control and Adaptation Protocol (L2CAP)L2CAP supports high level protocol multiplexing packet segmentationreassembly and conveyingthe quality of service information L2CAP permits applications to transmit and receive the datapackets with channel flow control and retransmission

bull Direct Test Mode (DTM)DTM allows testing of the radios Physical Layer (PHY) by transmitting and receiving the test packetsequences This is often used in compliance and production line testing without the need to gothrough the complete Bluetooth Low Energy Protocol Stack

13 ATSAMB11 Software APIThe ATSAMB11 is provided with a dedicated host software API layer This API layer provides an easyand reliable solution to add Bluetooth Low Energy capabilities to any user application The API provides aset of high level Bluetooth functions with abstraction of the transport protocol used between the userapplication and the ATSAMB11

Figure 1-6 ATSAMB11 Software API

The API operation relies on a request-response mechanism The specific requests are sent to theATSAMB11 through a corresponding API function call The event messages are then returned by theATSAMB11 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the application according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flow

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 6

Figure 1-7 Bluetooth Low Energy Peripheral Application Flow

CAUTION The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time

The following figure describes the BluSDK Smart file architecture

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 7

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 4: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

113 Installing ATSAMB11 Device Pack using Device Pack Manager1 Open Atmel Studio2 Choose Tools gt Device Pack Manager

Figure 1-2 Start Page AtmelStudio Window

3 Click Check for Updates to check new pack of the ATSAMB11 and then click Install selectedpacksFigure 1-3 Device Pack Manager Window

4 Click Install By clicking install the user agrees to the license terms mentioned

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 4

Figure 1-4 End User License Agreement

5 After a successful update Close the Pack Manager and restart Atmel StudioFigure 1-5 Device Pack Manager Dialog Box

12 ATSAMB11 Embedded FirmwareThe Bluetooth Low Energy communication is based on the network stack stored in the ATSAMB11 ReadOnly Memory (ROM) This stack requires Generic Access Profile (GAP) parameters and attributes to befunctional which are pushed from the application into the ATSAMB11 internal SRAM using internalmessages

The ROM coded firmware embeds the layers of the Bluetooth Low Energy stack that runs on top of theperipheral drivers and RTOS scheduler

bull Generic Access Profile (GAP)

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 5

GAP controls the Bluetooth Low Energy connection advertising makes the device visible to theoutside world and determines how two devices interact with each other GAP defines two mainroles for the Bluetooth Low Energy device Central and Peripheral

bull Generic Attribute Profile (GATT) and Attribute Protocol (ATT)GATT defines how the Bluetooth Low Energy device transfers the data The GATT process isbased on services and characteristics stored in Attribute Protocol (ATT) ATT is a simple look uptable stored in the ATSAMB11 SRAM

bull Security Manager (SM)The SM defines the procedure for pairing authentication and encryption between Bluetooth LowEnergy devices This layer is mainly used if security is requested on that particular connection

bull Logical Link Control and Adaptation Protocol (L2CAP)L2CAP supports high level protocol multiplexing packet segmentationreassembly and conveyingthe quality of service information L2CAP permits applications to transmit and receive the datapackets with channel flow control and retransmission

bull Direct Test Mode (DTM)DTM allows testing of the radios Physical Layer (PHY) by transmitting and receiving the test packetsequences This is often used in compliance and production line testing without the need to gothrough the complete Bluetooth Low Energy Protocol Stack

13 ATSAMB11 Software APIThe ATSAMB11 is provided with a dedicated host software API layer This API layer provides an easyand reliable solution to add Bluetooth Low Energy capabilities to any user application The API provides aset of high level Bluetooth functions with abstraction of the transport protocol used between the userapplication and the ATSAMB11

Figure 1-6 ATSAMB11 Software API

The API operation relies on a request-response mechanism The specific requests are sent to theATSAMB11 through a corresponding API function call The event messages are then returned by theATSAMB11 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the application according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flow

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 6

Figure 1-7 Bluetooth Low Energy Peripheral Application Flow

CAUTION The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time

The following figure describes the BluSDK Smart file architecture

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 7

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 5: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 1-4 End User License Agreement

5 After a successful update Close the Pack Manager and restart Atmel StudioFigure 1-5 Device Pack Manager Dialog Box

12 ATSAMB11 Embedded FirmwareThe Bluetooth Low Energy communication is based on the network stack stored in the ATSAMB11 ReadOnly Memory (ROM) This stack requires Generic Access Profile (GAP) parameters and attributes to befunctional which are pushed from the application into the ATSAMB11 internal SRAM using internalmessages

The ROM coded firmware embeds the layers of the Bluetooth Low Energy stack that runs on top of theperipheral drivers and RTOS scheduler

bull Generic Access Profile (GAP)

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 5

GAP controls the Bluetooth Low Energy connection advertising makes the device visible to theoutside world and determines how two devices interact with each other GAP defines two mainroles for the Bluetooth Low Energy device Central and Peripheral

bull Generic Attribute Profile (GATT) and Attribute Protocol (ATT)GATT defines how the Bluetooth Low Energy device transfers the data The GATT process isbased on services and characteristics stored in Attribute Protocol (ATT) ATT is a simple look uptable stored in the ATSAMB11 SRAM

bull Security Manager (SM)The SM defines the procedure for pairing authentication and encryption between Bluetooth LowEnergy devices This layer is mainly used if security is requested on that particular connection

bull Logical Link Control and Adaptation Protocol (L2CAP)L2CAP supports high level protocol multiplexing packet segmentationreassembly and conveyingthe quality of service information L2CAP permits applications to transmit and receive the datapackets with channel flow control and retransmission

bull Direct Test Mode (DTM)DTM allows testing of the radios Physical Layer (PHY) by transmitting and receiving the test packetsequences This is often used in compliance and production line testing without the need to gothrough the complete Bluetooth Low Energy Protocol Stack

13 ATSAMB11 Software APIThe ATSAMB11 is provided with a dedicated host software API layer This API layer provides an easyand reliable solution to add Bluetooth Low Energy capabilities to any user application The API provides aset of high level Bluetooth functions with abstraction of the transport protocol used between the userapplication and the ATSAMB11

Figure 1-6 ATSAMB11 Software API

The API operation relies on a request-response mechanism The specific requests are sent to theATSAMB11 through a corresponding API function call The event messages are then returned by theATSAMB11 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the application according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flow

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 6

Figure 1-7 Bluetooth Low Energy Peripheral Application Flow

CAUTION The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time

The following figure describes the BluSDK Smart file architecture

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 7

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 6: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

GAP controls the Bluetooth Low Energy connection advertising makes the device visible to theoutside world and determines how two devices interact with each other GAP defines two mainroles for the Bluetooth Low Energy device Central and Peripheral

bull Generic Attribute Profile (GATT) and Attribute Protocol (ATT)GATT defines how the Bluetooth Low Energy device transfers the data The GATT process isbased on services and characteristics stored in Attribute Protocol (ATT) ATT is a simple look uptable stored in the ATSAMB11 SRAM

bull Security Manager (SM)The SM defines the procedure for pairing authentication and encryption between Bluetooth LowEnergy devices This layer is mainly used if security is requested on that particular connection

bull Logical Link Control and Adaptation Protocol (L2CAP)L2CAP supports high level protocol multiplexing packet segmentationreassembly and conveyingthe quality of service information L2CAP permits applications to transmit and receive the datapackets with channel flow control and retransmission

bull Direct Test Mode (DTM)DTM allows testing of the radios Physical Layer (PHY) by transmitting and receiving the test packetsequences This is often used in compliance and production line testing without the need to gothrough the complete Bluetooth Low Energy Protocol Stack

13 ATSAMB11 Software APIThe ATSAMB11 is provided with a dedicated host software API layer This API layer provides an easyand reliable solution to add Bluetooth Low Energy capabilities to any user application The API provides aset of high level Bluetooth functions with abstraction of the transport protocol used between the userapplication and the ATSAMB11

Figure 1-6 ATSAMB11 Software API

The API operation relies on a request-response mechanism The specific requests are sent to theATSAMB11 through a corresponding API function call The event messages are then returned by theATSAMB11 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the application according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flow

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 6

Figure 1-7 Bluetooth Low Energy Peripheral Application Flow

CAUTION The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time

The following figure describes the BluSDK Smart file architecture

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 7

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 7: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 1-7 Bluetooth Low Energy Peripheral Application Flow

CAUTION The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time

The following figure describes the BluSDK Smart file architecture

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 7

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 8: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 1-8 BluSDK Smart File Architecture

14 Hardware PrerequisitesThis Custom Service Implementation application note details the code implementation procedures whichuse the ATSAMB11ZR-XPRO kit The SAMB11-ZR Xplained Pro evaluation kit is a hardware platformused to evaluate the ATSAMB11-ZR210CA module

141 SAMB11-ZR Xplained Pro BoardThe SAMB11-ZR Xplained Pro evaluation kit is a hardware platform used to evaluate the ATSAMB11-ZR210CA module Supported by the Atmel Studio integrated development platform the kit provides easyaccess to the features of the ATSAMB11ZR and explains how to integrate the device in a custom design

The Xplained Pro MCU series evaluation kits include an on-board embedded debugger and no externaltools are necessary to program or debug the ATSAMB11ZR The Xplained Pro extension kits offeradditional peripherals to extend the features of the board and ease the development of custom designs

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 8

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 9: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 1-9 SAMB11-ZR Xplained Pro Board

The SAMB11-ZR Xplained Pro board contains

bull ATSAMB11-ZR210CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy

bull Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatile registers and serialEEPROM Compatible with two-wire (I2C) and SMBus serial interfaces

bull Current Measurement Header ndash Embedded current measurement circuitry with support for datavisualization

15 Hardware Setupbull Connect the board to PC using the Debug USB Connector

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 9

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 10: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 1-10 SAMB11 XPRO Connection to PC

The hardware is ready for development

ATSAMB11Getting Started

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 10

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 11: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

2 Creating and Initializing the ProjectThis chapter details the process of creating an application startup project using Atmel Studio Prior tocreating a project the user must know hardware architecture and software requirements to configuredrivers

21 Creating Project from ASFAdvanced Software Framework has a pre-configured startup template project that includes Bluetooth LowEnergy software API for the ATSAMB11 and their peripheral driver dependencies This is used as astarting project for any Bluetooth Low Energy project development

To create the project follow the steps below

1 Navigate to File gt New gt Example Project in Atmel Studio2 From Device Family drop-down list choose SAMB113 Select BLE-Startup Template - SAMB11 ZR Xplained Board

Note  The ATSAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter the projectin the dialog box

Figure 2-1 Advanced Software Framework - New Example Project

4 Click OK and accept the license agreement by checking ldquoI accept the license agreementrdquo checkbox

5 Click FinishThe BLE startup project is now created and loaded in Atmel Studio

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 11

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 12: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 2-2 Startup_Template Project

Note  The main project routine of ldquostartup template projectrdquo already includes the SAMB11CortexM0 MCU low level initialization Bluetooth Low Energy initialization The added ASFcomponents in project can be viewed from ldquoASFgtASF Wizardrdquo Select the created project from theProject drop down box

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 12

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 13: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 2-3 ASF Wizard Window

6 The main routine contains the ATSAMB11 low level initialization and BLE initialization Thefollowing figure illustrates the flow of the main routineFigure 2-4 Main Routine Flow

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 13

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 14: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

22 Compiling and Testing the Project

1 Click or press F7 button to compile the project2 Verify that no build error appears in Atmel Studio output window

Figure 2-5 Atmel Studio Output Window

3 To access the project properties go to Project gtSTARTUP_TEMPLATE_SAMB11ZR_XPLAINED_PRO1 PropertiesFigure 2-6 Compiling the Project

4 In project properties click the Tool tab and select the EDBG of SAMB11ZR Xplained Pro boardas debuggerprogrammer

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 14

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 15: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 2-7 Selection of DebuggerProgrammer

5 Open any Terminal application (for example TeraTerm) Click Serial radio button and click OK6 In TeraTerm choose Setup gt Serial port and set the following parameters

ndash Set Baudrate as 115200ndash Set Parity as nonendash Set Stop bit as 1

Also check if EDBG associated COM Port is listed in Windows Device Manager

7 Click or press F7 to save the project

8 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro9 The initialization of the ATSAMB11ZR module must return the Bluetooth Device Address and

Address type as shown in the following figure

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 15

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 16: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 2-8 Console Log Window

Note 1 The initialization of ATSAMB11ZR takes few seconds due to application code and patch

code bootloading from internal SPI Flash to RAM

ATSAMB11Creating and Initializing the Project

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 16

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 17: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

3 Establishing Connection with Central DeviceThe Bluetooth Low Energy connectivity is added to the application that is used to connect with theBluetooth Low Energy central The first step is about the management of the Bluetooth connection with acentral device When using the ATSAMB11 device this process is managed by the corresponding APIfunction calls associated with ATSAMB11 events handling

The interaction between the ATSAMB11 internal stack application layer and Bluetooth Low Energycentral during connection establishment is as follows

Figure 3-1 Establishing Connection with Central Device

On the application layer side the management of the Bluetooth connection is performed through threemain steps

1 GAP callback registration2 Advertisement configuration3 ATSAMB11 event handling

In the existing project main routine the integration of these steps is highlighted in red in the followingflowchart

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 17

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 18: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 3-2 Main Routine Flow Chart

31 Configuring and Starting the Advertisement ProcessThe Bluetooth Low Energy devices transmit advertisement packets to show their presence to nearbydevices The advertisement packet is sent periodically at a time interval defined by variableldquoadvintervalrdquo defined in the Bluetooth SIG specification To avoid any collision with other wirelessnetworks such as Wi-Fireg a channel change is performed for each advertisement packet sent (datafrequency hopping) as illustrated in the following figureFigure 3-3 Advertisement Process

During advertisement the payload structure to be sent differs from application to application and is set byusing encapsulated packet data unit type information (PDU_TYPE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 18

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 19: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 3-4 PDU Advertising

Prea

mbl

e10

1010

10b

1 Byte 4 Bytes

Access Address0x8E89BED6

Packet Data Unit (PDU)Advertising Data

CRC

3 BytesAdvertising Channel PDU

Header Payload

2 Bytes 6-37 Bytes

RFU LengthRxAddTxAdd RFUPDU Type4 Bits 1 Bit2 Bits 6 Bits1 Bit 2 Bits

The following table lists the different PDU types used according to device role

Table 3-1 Device Roles for Advertising Event Types

Advertising Event Types (PDU_TYPE) Broadcaster Observer Peripheral Central

Connectible undirected event (ADV_IND) Excluded Excluded Mandatory Excluded

Connectible directed event(ADV_DIRECT_IND) Excluded Excluded Optional Excluded

Non-connectible undirected event(ADV_NONCONN_IND) Mandatory Excluded Optional Excluded

Scannable undirected event (ADV_SCAN_IND) Optional Excluded Optional Excluded

As the device acts as a Bluetooth Low Energy peripheral the connectable undirected event (ADV_IND)advertising type is used See the following description about the ADV_IND advertisement packet

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 19

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 20: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 3-5 ADV_IND Advertisement Packet

The ADV_IND payload contains different Advertisement Data types (AD 0 - AD n) which provide specificinformation to the central device such as device short name Tx power level and list of availableservices UUIDs The number of advertisement data types that can be added to the advertisementpayload are limited by the advertisement payload size of 31 octets

Following is a list of advertisement data types that are commonly found in ADV_IND payload

311 Flags (AD Type 0x00)The flags describe the basic device capability such as BLE support BLE discoverable mode BREDRsupport and simultaneous BRED

312 Available Service UUID (AD Types 0x02 to 0x07)The Bluetooth Low Energy advertisement payloads are limited to 31 bytes Therefore only two 128-bitUUID values can be added to the payload For this purpose the specific AD types describe the length ofthe advertised UUID and provide information as to whether the payload contains a incompletecompletelist of UUID supported by the GATT server

bull 0x02 ndash incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 ndash complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 ndash incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 ndash complete list of 128-bit UUIDs (custom GATT services)

Note  When a 16-bit UUID is transmitted only the unique 2-byte value is sent The client knows that it isrequired to be injected into the base UUID For example the Health Thermometer Service is assigned as0x1809 so its equivalent UUID is 00001809-0000-1000-8000-00805F9B34FB

313 Device Name (AD Types 0x08 to 0x09)This AD type field is used to advertise the local name of the device in the network The local name datatype value indicates if the name is complete or shortened If the name is shortened the complete namecan be read after the connection is established

bull 0x08 ndash shortened local namebull 0x09 ndash complete local name

Note 1 A shortened name contains only continuous characters from the beginning of the full name For

example if the device name is BT_Device_Name then the shortened name can beBT_Device or BT_Dev

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 20

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 21: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

2 Complete GAP data type list is available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile

For management of the advertisement process and covering the different configurations specified byBluetooth SIG the ATSAMB11 interface driver provides the two functions (at_ble_adv_data_set andat_ble_adv_start) elaborated in the following sections

In the application use these two functions to set up the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process

3131 Setting the Advertisement Payload (at_ble_adv_data_set)Prototypeat_ble_status_t at_ble_adv_data_set (uint8_t const const adv_datauint8_t adv_data_lenuint8_t const const scan_resp_datauint8_t scan_response_data_len)

Description ndash set clear or update the advertisement and scan response data

Parameters

bull adv_data ndash raw data to be placed in advertisement packetbull adv_data_len ndash data length for adv_data Max size 28 bytes (3 bytes are reserved to set

advertising AD type flags based on the selected Advertising mode and the user is not required toconfigure AD type flags in the advertisement payload)

bull scan_resp_data ndash raw data to be placed in the scan response packet If NULL no changes aremade to the current scan response packet data

bull scan_response_data_len ndash data length for scan_resp_data Max size 31 bytes

Return ndash Execution Status

This function requires a parameter raw adv_data to be passed Following is an example of adv_datadefinition

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

3132 Starting the Advertisement Process (at_ble_adv_start)Prototypeat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 21

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 22: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

at_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)

Description ndash start advertisement process

Parameters

bull type ndash advertising type to be used can bendash AT_BLE_ADV_TYPE_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTEDndash AT_BLE_ADV_TYPE_SCANNABLE_UNDIRECTEDndash AT_BLE_ADV_TYPE_NONCONN_UNDIRECTEDndash AT_BLE_ADV_TYPE_DIRECTED_LDCndash AT_BLE_ADV_TYPE_SCAN_RESPONSE

bull mode ndash Advertising mode to be used can bendash AT_BLE_ADV_NON_DISCOVERABLEndash AT_BLE_ADV_GEN_DISCOVERABLEndash AT_BLE_ADV_LIM_DISCOVERABLEndash AT_BLE_ADV_BROADCASTER_MODE

bull peer_addr ndash specify peer address when advertising type is AT_BLE_ADV_TYPE_DIRECTEDbull filtered

ndash AT_BLE_ADV_FP_ANY ndash allow scan and connection requests from anyonendash AT_BLE_ADV_FP_FILTER_SCANREQ ndash allow scan request from White List devices onlyndash AT_BLE_ADV_FP_FILTER_CONNREQ ndash allow connection request from White List devices

onlyndash AT_BLE_ADV_FP_FILTER_BOTH ndash allow scan and connection requests from White List

devices onlybull interval ndash advertisement interval (in 0625 ms units)bull timeout ndash advertising timeout between 0x0001 and 0x028F in scale of seconds This parameter

must be set to 0 if type equals AT_BLE_ADV_TYPE_DIRECTEDbull disable_randomness ndash when disabled advertisements are performed at the exact interval

without adding random 10 ms tempo

Return ndash execution status

314 Advertisement ProcessIn this assignment the advertisement process includes the following configuration

bull Undirected (Type AT_BLE_ADV_TYPE_UNDIRECTED)bull Discoverable (Mode AT_BLE_ADV_GEN_DISCOVERABLE)bull No peer address (peer_addr = NULL)bull No filtering (filtered = AT_BLE_ADV_FP_ANY)bull Advertisement interval 1s (interval = 1600)bull Maximum timeout 655 seconds (timeout 655)bull Randomness enabled (disable_randomness = FALSE)

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 22

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 23: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

3141 Starting the Advertisement Process1 Open startup_template_appc file2 Declare the following ble_status global variable in startup_template_appc as volatile

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphvolatile at_ble_status_t ble_status

3 Declare the following adv_data global variable in startup_template_appc as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquo

Note 1 The name of the device is to be changed (AD2 field)2 According to the new name AD2 length must be adapted to new AD2 content

4 Add the following start_advertisement function in startup_template_appc and definethe function prototype void start_advertisement (void) to avoid warningsvoid start_advertisement (void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement)

5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 23

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 24: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

6 Click or press Ctrl+S to save the project

7 Click or press F7 button to compile the project8 Verify that no build error appears in Atmel Studio output window

Figure 3-7 Atmel Studio Output Window

9 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro10 Open the Microchip Bluetooth Data Application on Android or iOS mobile device

ndash Press the Bluetooth Smart buttonndash Press the START SCAN button

Note  The device must appear in the Microchip Bluetooth Data Application

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 24

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 25: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 3-8 Microchip Bluetooth Data Application

11 The terminal must display the following log outputFigure 3-9 Log Output Window

32 Managing GAP eventsThe management of the Bluetooth connection at the application level is done through reception andhandling of events reported by the ATSAMB11 internal stack These events are generated by ATSAMB11GAP GATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with otherdevices in its vicinity

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 25

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 26: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

To manage events coming from the ATSAMB11 module the host driver must provide able_mgr_events_callback_handler function that allows registration of application callback functionto be executed on each event reported by the ATSAMB11 module

Prototypebool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst void ble_event_handler)

Description ndash used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquo callbacks

Parametersbull event_cb_type ndash types of actions to perform on callbacks can be either

REGISTER_CALL_BACK or

UNREGISTER_CALL_BACKbull event_type ndash any one of the event types can be used

BLE_GAP_EVENT_TYPEBLE_GATT_CLIENT_EVENT_TYPEBLE_GATT_SERVER_EVENT_TYPEBLE_L2CAP_EVENT_TYPEBLE_GATT_HTPT_EVENT_TYPEBLE_DTM_EVENT_TYPEBLE_CUSTOM_EVENT_TYPE

bull ble_event_handler ndash pointer to handler list

Structure ble_gap_event_cb_t defines the GAP callbacks Similarly structuresble_gatt_client_event_cb_t and ble_gatt_server_event_cb_t define the callbacks of GATTevents

typedef struct ble_gap_event_cb BLE Undefined events received from SAMB11 which is not handled in Library ble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_t ble_event_callback_t scan_info Once the BLE scan timeout or scan stop will trigger the scan report event Refer ref at_ble_scan_report_t ble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_t ble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_t ble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_t ble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_t ble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_t ble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_t ble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_t

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 26

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 27: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

ble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_t ble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_t ble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_t ble_event_callback_t pair_key_request encryption request comes from the peer device Needs to supply the bonding information which is stored earlier ref at_ble_encryption_request_t ble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_t ble_event_callback_t encryption_status_changed Event triggered once the Resolve random address is resolved using supplied IRKs ref at_ble_resolv_rand_addr_status_t ble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_t ble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_t ble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_t ble_event_callback_t con_channel_map_indble_gap_event_cb_t

Note  Callback definition is application-specific If the application layer requires a specific event callbackthen the specific member of the structure is to be assigned with the address of the callback function

In this assignment two callback functions on Connected and Disconnected GAP events are usedThis allows the application to restart the advertising process on Disconnect manage connectioninformation and startstop sensor data update

321 Handling of Connected and Disconnected GAP Events1 Open the startup_template_appc file2 Define the following software flags as global variables in startup_template_appc file for

Connect callback functionvolatile bool timer_flag = falsevolatile bool connected_flag = false

3 Declare and implement the following ble_connected_cb function in thestartup_template_appc file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(rn Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS

4 Declare and implement the following ble_disconnected_cb function instartup_template_appc file for Disconnect callback function Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(rn Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS

5 Declare the following static GAP callback structure in startup_template_appc filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 27

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 28: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

6 Add the following register_samb11_callbacks function in startup_template_appcvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

7 Add the register_samb11_callbacks function call prior to start advertisement in theapplication main routineint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn) DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

8 Press or the F7 button to compile the project and verify that no build errors appear in the AtmelStudio output windowFigure 3-10 Atmel Studio Output Window

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 28

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 29: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

9 Click or press Ctrl+S to save the project

10 Click or press Ctrl + Alt + F5 to program the project binary on the SAMB11-ZR Xplained Proand check correct initialization of the ATSAMB11

11 Open the ldquoMicrochip Bluetooth Datardquo application on Android or iOS device12 Press Bluetooth Smart13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key

123456) (See the following figure)Note 

1 Pairing event handling is carried out by ble_managerc Refer toble_pair_key_request_handler() for code implementation The default pass key of123456 is also fixed inside this function The pass key can be changed

Figure 3-11 Console Log Window

Note  After peripheral pairing no services information is displayed in the Microchip BluetoothData application as no service is currently defined and started on peripheral side

ATSAMB11Establishing Connection with Central Device

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 29

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 30: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

4 SetupHandling of Pre-Defined Service from ASFThe management of services is done in the GATT layer of the ATSAMB11 ROM coded Bluetooth LowEnergy stack The GATT transactions are based on high level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of the ATSAMB11 device This assignment adds the pre-defined service of information service from ASF library

Figure 4-1 ATSAMB11 GATT Layers

bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral these profiles are simply a pre-defined collection of services that have been compiled by either the Bluetooth SIG (adopted GATTbased profile) or by the application developer (custom profiles) For example the Heart Rate Profilecombines the Heart Rate Service and the Device Information Service

Note  The complete list of officially adopted GATT-based profiles is available on the BluetoothDeveloper Portal

bull ServicesA service is a collection of data and associated behaviors which accomplish a particular function orfeature of a device or portions of a device A service may reference other primary or secondaryservices andor a set of characteristics that make up the service Each service distinguishes itselffrom other services by means of a unique numeric ID called as UUID which can be either 16-bit(for officially adopted Bluetooth Low Energy Services) or 128-bit (for custom services)

Note  A full list of officially adopted services and their UUIDs is available on the BluetoothDeveloper Portal

bull CharacteristicsA characteristic is the lowest level concept in GATT transactions It contains a single data point withdifferent attributes such as notify read or write capabilities Similar to Services each characteristiccan be distinguished by a SIG-defined adopted UUID (16-bit) or custom (128-bit) UUID This UUIDensures interoperability across Bluetooth Low Energy devices The characteristics are important tointeract with in a Bluetooth Low Energy network In addition to standard UUID the custom UUID isused in case of specific application When characteristics with custom UUID are used in a devicethen it will be interoperable only with those devices that support these characteristics with customUUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 30

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 31: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

In this assignment the following steps are added to the application to set up and handle a deviceinformation service within the ATSAMB11 module The following steps are added to the startup project

bull Adding device info service component from ASF (refer the following figure)bull Configuring and loading the service

Figure 4-2 Device Information Service

41 Adding Device Info Service Component from ASF Wizard to ProjectTo use the ldquoofficially adopted GATT-based profilesrdquo from SIG ASF provides Bluetooth Low Energy servicecomponents such as init functions that pre-define services

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Services(component)rdquo in the Available Modules (refer following

figure) and click Addgtgt

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 31

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 32: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 4-3 Available Modules

ndash Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected Modulesrdquo area asshown in the following figureFigure 4-4 Selected Modules

3 Click Apply to add the component to the project4 Click OK to confirm the addition of BLE-Device Information Services (component) to the project in

the Atmel Software Framework pop-up window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 32

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 33: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 4-5 Atmel Software Framework

5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution ExplorerFigure 4-6 Device Information Service Added to Project

42 Configuring and Loading Device Information ServiceThe ATSAMB11 interface driver provides a set of GATT functions that allows storing and updating theservices in the ATSAMB11 memories

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics inATSAMB11

Parameters

bull Uuid [In] ndash primary service UUID

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 33

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 34: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

bull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash an array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service this array

is updated with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

This function requires an argument as GATT description structure of the service that is implemented Thepreviously added device info service component provides Bluetooth Low Energy service middlewareincluding the init functions that predefine the services See below ldquodis_init_servicerdquo from device infoBLE service (device_infohc)

Prototype ndash void dis_init_service(dis_gatt_service_handler_t device_info_serv)Description ndash initialize the device information service handler in the application

Parameters ndash

bull device_info_serv [Inout] ndash pointer to device info GATT description handler to beupdated

Return ndash none

the following is the sample code of GATT device info service descriptor definition in the application

device_info_serv-gtserv_handle = 0device_info_serv-gtserv_uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_uuiduuid[0] = (uint8_t) DIS_SERVICE_UUIDdevice_info_serv-gtserv_uuiduuid[1] = (uint8_t) (DIS_SERVICE_UUID gtgt 8)Characteristic Info for Manufacturer Name Stringdevice_info_serv-gtserv_chars[0]char_val_handle = 0 handle stored here device_info_serv-gtserv_chars[0]uuidtype = AT_BLE_UUID_16device_info_serv-gtserv_chars[0]uuiduuid[0] = (uint8_t) IS_CHAR_MANUFACTURER_NAME_UUID UUID Manufacturer Name String device_info_serv-gtserv_chars[0]uuiduuid[1] = (uint8_t) (DIS_CHAR_MANUFACTURER_NAME_UUID gtgt 8) UUID Manufacturer Name String device_info_serv-gtserv_chars[0]properties = AT_BLE_CHAR_READ Properties memcpy(char_valuemanufacturer_nameDEFAULT_MANUFACTURER_NAMEDIS_CHAR_MANUFACTURER_NAME_INIT_LEN)device_info_serv-gtserv_chars[0]init_value = char_valuemanufacturer_namedevice_info_serv-gtserv_chars[0]value_init_len = DIS_CHAR_MANUFACTURER_NAME_INIT_LENdevice_info_serv-gtserv_chars[0]value_max_len = DIS_CHAR_MANUFACTURER_NAME_MAX_LENif BLE_PAIR_ENABLEdevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_REQ_AUTHN_NO_AUTHR permissions elsedevice_info_serv-gtserv_chars[0]value_permissions = AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR permissions endifdevice_info_serv-gtserv_chars[0]user_desc = NULL user defined name device_info_serv-gtserv_chars[0]user_desc_len = 0device_info_serv-gtserv_chars[0]user_desc_max_len = 0device_info_serv-gtserv_chars[0]user_desc_permissions = AT_BLE_ATTR_NO_PERMISSIONS user description permissionsdevice_info_serv-gtserv_chars[0]client_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS client config permissionsdevice_info_serm hdsv-gtserv_chars[0]server_config_permissions = AT_BLE_ATTR_NO_PERMISSIONS server config permissionsdevice_info_serv-gtserv_chars[0]user_desc_handle = 0 user desc handlesdevice_info_serv-gtserv_chars[0]client_config_handle = 0 client config handlesdevice_info_serv-gtserv_chars[0]server_config_handle = 0 server config handlesdevice_info_serv-gtserv_chars[0]presentation_format = NULL presentation format

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 34

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 35: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Note  In case of custom service the above definition initialization must be taken care of by thedeveloper

421 Procedure to Configure and Load Device Info Service1 Include device info service header file (device_infoh) at the beginning of

startup_template_appc fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infoh

2 Define a device info service handler as global in startup_template_appc file Services handlers dis_gatt_service_handler_t dis_service_handler

3 Add dis_init_service and at_ble_primary_service_define functions above theadvertisement start in main routine Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed)

4 Click or press Ctrl + S to save the project and compile the project by pressing or F7 button5 Verify that no build error appears in Atmel Studio output window

Figure 4-7 Atmel Studio Output Window

6 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro7 Open ldquoMicrochip Bluetooth Datardquo application on Android or iOS device and press Bluetooth Smart

option8 Press Start Scan button and connect to peripheral

Note  The device name is a characteristic and contains the name of the device This device namecan be read by the central device to know the name of the device in order to differentiate thedevices This is being set using at_ble_device_name_set()API The device name is set bydefault when ble_device_init is called and the value is pre-defined using BLE_DEVICE_NAMEThe device name can also be sent as part of advertisement payload to be same as the oneconfigured in at_ble_adv_data_set() API It is the responsibility of users to keep the devicename set in advertisement payload the same as that configured inat_ble_device_name_set()

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 35

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 36: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

9 Now the device info service must be visible after pairing with peripheral under Microchip BluetoothData applicationFigure 4-8 Service List in Microchip Bluetooth Data Application

Note  The device must be removed using the Forget Device option from mobile settings in caseof unsuccessful pairing between the ATSAMB11 and the app This happens due to previouslystored paring information in mobile However the ATSAMB11 cannot store pairing due to RESEToption as it was stored in temporary storage (RAM)

10 The serial terminal must display the following log output window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 36

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 37: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 4-9 Console Log Window

ATSAMB11SetupHandling of Pre-Defined Service from

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 37

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 38: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

5 Setting up and Handling Custom ServiceThe previous assignment describes the handling of Bluetooth Low Energy SIG-defined device infoservice which is the predefined service available in ASF component This assignment describes thecustom service wherein the service initialization needs to be implemented by the user In the context ofcustomized environment service the following service description is pushed in the ATSAMB11 memory

Figure 5-1 Custom Service

Custom Environment Service Description

bull UUID type ndash Custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639c1ba5af0

Characteristic 0 (Temperature)

bull User description ndash temperaturebull UUID type ndash custom UUID (128-bit)bull UUID ndash 1bc5d5a5-0200-a687-e511-3639d8ba5af0bull Properties ndash read notifybull Value permission ndash no authorization requiredbull Client config permission ndash no permissionbull Server config permission ndash no permission

Note  In this definition UUIDs are generated randomly Custom servicescharacteristics are free to useany 128-bit UUID less than the base UUID There is no reserved space for vendors to use 16-bit or 32-bitUUIDs

With this definition any temperature change is notified to the central through notification mechanismWhen notify property of the Client Characteristic Configuration Descriptor is enabled by the central andthe device writes the new value then this updated value is automatically sent to the central through anotification The central is not required to send read characteristic commands explicitly to the peripheral(GATT server)

To set up and handle the custom environment service in the ATSAMB11 module the following steps areadded to the application

bull Configure and load the custom servicebull Update temperature characteristic and notify to the central devicebull Receive and handle notification in the application

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 38

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 39: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 5-2 Custom Service Flowchart

51 Configuring and Loading the Custom Environment ServiceThe ATSAMB11 interface driver provides the following set of GATT functions that allow it to push andupdate the service descriptions in the ATSAMB11 SRAM memory

Note  Before starting this assignment be sure to follow the steps mentioned in Creating the Project andInitializing ATSAMB11 and Establishing Connection with Central Device

Prototypeat_ble_status_t at_ble_primary_service_define(at_ble_uuid_t uuidat_ble_handle_t service_handleat_ble_included_service_t included_service_listuint16_t included_service_countat_ble_characteristic_t charactristic_listuint16_t charactristic_count)

Description ndash defines a new primary service along with its included services and characteristics in theATSAMB11

Parameters

bull Uuid [In] ndash primary service UUIDbull service_handle [Out] ndash service handle is returned herebull included_service_list [In] ndash array of included service referencesbull included_service_count [In] ndash number of elements in included_service_listbull charactristic_list [InOut] ndash an array of characteristics included in the service updated

with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list

Return ndash execution status

bull Characteristics ndash

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 39

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 40: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

ndash Characteristics definition is done through specific array of followingldquoat_ble_characteristic_trdquo structure instancestypedef struct at_ble_handle_t char_val_handle lt Here the stack will store the char value handle for future use at_ble_uuid_t uuid lt Characteristic UUID at_ble_char_properties_t properties lt Characteristic properties values for Client Characteristic Configuration Descriptor and Server Characteristic Configuration Descriptor will be decided from this value

uint8_t init_value lt initial value of this characteristic uint16_t value_init_len lt initial value length uint16_t value_max_len lt maximum possible length of the char value at_ble_attr_permissions_t value_permissions lt Value permissions TODO can this value be deduced from properties field

uint8_t user_desc lt a user friendly description this value will be stored in the relevant descriptor if no user description is desired set to NULL uint16_t user_desc_len lt the user friendly description length this value will be stored in the relevant descriptor if no user description is desired set to 0 uint16_t user_desc_max_len lt Maximum possible length for the user friendly description this value will be stored in the relevant descriptor if no user description is desired set to 0

at_ble_char_presentation_t presentation_format lt Characteristic presentation format this value will be stored in the relevant descriptor if no presentation format is necessary set to NULL at_ble_attr_permissions_t user_desc_permissions at_ble_attr_permissions_t client_config_permissions at_ble_attr_permissions_t server_config_permissions at_ble_handle_t user_desc_handle at_ble_handle_t client_config_handle at_ble_handle_t server_config_handle

at_ble_characteristic_t

511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_template_appc file

define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0

2 Define the following environment service handler and characteristics variable as global instartup_template_appc file Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

3 Add the following service initialization function custom_environment_service_init instartup_template_appcvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 40

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 41: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service)

4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_template_appc file If a client (central)enables notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event and this event callback is called Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(rn Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_template_appc file Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param)at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )paramif (event_param-gtstatus == AT_BLE_SUCCESS)printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS

6 Declare the following GATT server callback structure in startup_template_appc file Thisassignment uses two GATT callbacksstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handlercharacteristic_changed = custom_char_changed_app_event

7 Add the following register_gatt_server_callbacks function instartup_template_appc to register GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle)if (ble_status = true)printf(rnError when Registering SAMB11 callbacks)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 41

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 42: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

8 Add custom_environment_service_init and register_gatt_server_callbacksfunction calls prior to start advertisement in the application main routine to initialize custom serviceand to register the GATT server callbacksint main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

9 Click or press Ctrl+S to save the project

10 Compile the project by pressing or F7 button11 Verify that no build error appears in the Atmel Studio output window

Figure 5-3 Atmel Studio Output Window

12 Click or press Ctrl+Alt+F5 to program the project binary on the SAMB11-ZR Xplained Pro

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 42

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 43: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

13 Open the ldquoMicrochip Bluetooth Datardquo application and press Bluetooth Smart on Android or iOSdevice

14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip Bluetooth Data

applicationFigure 5-4 Service List in Microchip Bluetooth Data Application

Note  If the pairing of ATSAMB11 with Microchip Bluetooth Data is not successful then removethe pairing information from mobile by selecting ldquoForget Devicerdquo from the mobile settings Thereason for this is that the mobile app stores the previous pairing information but the ATSAMB11device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)Custom service is displayed as unknown service as shown in the preceding figure as this service isnot a SIG-defined service

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 43

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 44: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 5-5 Generic Information

16 Serial terminal client must display the following log outputFigure 5-6 Log Output Window

52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thisattributes notify the central when a new characteristic value is available The update of any ldquonotifyrdquocharacteristic value is based on following interaction between the application layer and the ATSAMB11internal stack

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 44

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 45: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

Figure 5-7 Characteristic Notification

521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototypeat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)

Description ndash sets a characteristic value in the ATSAMB11 memory

Parameters

bull handle [inout] ndash pointer to characteristic handle to be changedbull value [in] ndash new valuebull len [in] ndash value length in bytes

Return ndash execution status

522 Sending a Notification (at_ble_notification_send)Prototype ndashat_ble_status_t at_ble_notification_send(at_ble_handle_t conn_handleat_ble_handle_t attr_handle)

Description ndash Sends a Notification

Parameters ndash

bull conn_handle[in] ndash handle of the connection to be notifiedbull attr_handle [in] ndash handle of the attribute originating the notification

Return ndash Execution Status

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 45

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 46: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following timer_callback_fn callback function from the

startup_template_appc filestatic void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

hw_timer_init() in main routine of startup_template_appc initializes the hardware dualtimer

send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEXTIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0) function posts the platform event TheATSAMB11 driver offers simple APIs to manage interrupts generated by the set of available GPIOsand peripherals on the ATSAMB11 For these interrupts the developer is allowed to register aninterrupt callback that is to be executed upon triggering the configured interrupt source Callbacksare executed from ISR context and then this interrupt event is messaged to the application taskNote  Callbacks are executed from ISR context therefore it is important not to execute longroutines add delays or print trace messages inside the interrupt callback functions as it impactsthe timing of firmware task Instead post a platform event to the main event handling loop and addany routines inside the platform event handler These interrupts are sent as a platform event to theapplication task to handle it in task context For more details on interrupt handling in ATSAMB11see ATSAMB11 BluSDK SMART Interrupts and ULP - Architecture and Usage Users Guide

2 The platform event is posted on dual timer expiry in the above step It is required to register theplatform event with the platform event callback This callback gets called by ATSAMB11 BLE stackwhen the platform event is posted in Steps 2 3 and 4 does this operation Declare the followingplatform event callback structure in startup_template_appc file Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLEManager

3 Add the following register_platform_event_callbacks() function instartup_template_appc to register the platform event callback for user-defined events Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

4 Add register_platform_event_callbacks() function call prior to start advertisement in theapplication main routine to register the ATSAMB11 platform callbacks As this exercise uses dualtimer for sending notification and dual timer is not active in the ULP mode stop ATSAMB11entering to the ULP mode This is done by changing ble_set_ulp_mode(BLE_ULP_MODE_SET)to ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) as highlighted below For more details oninterrupt handling in ATSAMB11 see ATSAMB11 BluSDK SMART Interrupts and ULP -Architecture and Usage Users Guideint main(void)

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 46

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 47: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Clear ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

5 If a client (central) enables the notifications for a server the server (peripheral) receives anAT_BLE_CHARACTERISTIC_CHANGED event callback then start the periodic 10 second timer forsending the notification Add the following code in previously definedcustom_char_changed_app_event function Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param)at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )paramif((environment_service_characs[0]client_config_handle == char_changed_param_handle-gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))timer_flag = falsehw_timer_start(10)printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 47

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 48: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

6 Declare the following Temperature_value global variable as static instartup_template_appcstatic uint8_t Temperature_value = 25

7 Add the following send_temperature_notification function in startup_template_appcto send temperature every 10 seconds Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(n Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++if(Temperature_value gt 75)Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set(environment_service_characs[0]char_val_handle(uint8_t )ampTemperature_valuesizeof(Temperature_value))ble_status = at_ble_notification_send(0environment_service_characs[0]char_val_handle)if(ble_status = AT_BLE_SUCCESS)printf(rnfail to send temperature update notification )

8 The platform event registered in steps 2 3 and 4 passes a callback which will be called when thespecific platform event is posted in step 1 Add the following code to add AT_PLATFORM_EVENTcallback function When this callback is called it initiates sending of temperature notification Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status

9 Click to save the project ltCtrl+Sgt

10 Compile the project by pressing the button ltF7gt11 Verify that no build error appears in Atmel Studio output window

Figure 5-8 Atmel Studio Output Window

12 Click to program the project binary on the SAMB11-ZR Xplained Pro13 Open the ldquoMicrochip Bluetooth Datardquo Application on Android or iOS device

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 48

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 49: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

14 Connect and pair to the peripheral (pass key 123456)15 Click NOTIFY to start the notification16 Temperature information in HEX values must be displayed in the Microchip Bluetooth Data

applicationFigure 5-9 Notification Window

17 Serial terminal must display the following log outputFigure 5-10 Log Output Window

ATSAMB11Setting up and Handling Custom Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 49

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 50: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

6 Appendix A Pre-defined Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling of Pre-Defined Service from ASF

- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphinclude device_infohvolatile at_ble_status_t ble_statusvolatile bool timer_flag = false volatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handlervoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)

timer callback function static void timer_callback_fn(void) Add timer callback functionality here static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local NameMy_SENS AD2 = ldquoMy_SENSrdquovoid start_advertisement(void)printf(rn Assignment 21 Start Advertisement)Set advertisement datable_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0)Start Advertisementble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTEDAT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550)if(ble_status = AT_BLE_SUCCESS)printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESSstatic const ble_gap_event_cb_t app_gap_handle =

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 50

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 51: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

int main(void) platform_driver_init() acquire_sleep_lock()

Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Initialize Device Info service in GATT printf(rn Assignment 32 Start Device Info Service) dis_init_service (ampdis_service_handler) Define the primary service in the GATT server database if ((dis_primary_service_define (ampdis_service_handler)) = AT_BLE_SUCCESS) printf(rn Device Information Service definition failed) Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_SET) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix A Pre-defined Service Software Solutio

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 51

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 52: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

7 Appendix B Custom Service Software SolutionThe following is the code implementation for handling of pre-defined service done in Setting up andHandling Custom Service

- Includes ---------------------------------------------------------------

include ltasfhgtinclude platformhinclude at_ble_apihinclude console_serialhinclude timer_hwhinclude ble_managerhinclude ble_utilshinclude buttonhinclude startup_template_apphdefine ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = falsevoid platform_resume_cb(void)void start_advertisement(void)void register_samb11_callbacks(void)void register_gatt_server_callbacks(void)void custom_environment_service_init(void)static uint8_t Temperature_value = 25void send_temperature_notification(void)void register_platform_event_callbacks(void)

Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]

timer callback function static void timer_callback_fn(void) timer_flag = true send_plf_int_msg_ind(RAM_ISR_TABLE_TIMER0_INDEX TIMER_EXPIRED_CALLBACK_TYPE_DETECT NULL 0)

static void button_cb(void) Add button callback functionality here void platform_resume_cb(void) init_port_list() serial_console_init()

static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo

void start_advertisement(void) printf(rn Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data)NULL0) Start Advertisement ble_status = at_ble_adv_start(AT_BLE_ADV_TYPE_UNDIRECTED AT_BLE_ADV_GEN_DISCOVERABLENULLAT_BLE_ADV_FP_ANY16006550) if(ble_status = AT_BLE_SUCCESS) printf(rn Failed to start advertisement) Callback registered for AT_BLE_CONNECTED event

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 52

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 53: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

static at_ble_status_t ble_connected_cb (void param) printf(rn Assignment 22 Application connected) connected_flag = true ALL_UNUSED(param) return AT_BLE_SUCCESS Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param) printf(rn Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS

Callback registered for AT_PLATFORM_EVENT event from stack static at_ble_status_t platform_interrupt_app_event(void param) at_ble_status_t status = AT_BLE_SUCCESS platform_isr_event_t plf_isr_event = (platform_isr_event_t )param Flag to start temperature notification if ((plf_isr_event-gtevent_type == ((TIMER_EXPIRED_CALLBACK_TYPE_DETECT ltlt 8) | RAM_ISR_TABLE_TIMER0_INDEX))) if(connected_flag == true ampamp timer_flag == true) send_temperature_notification() timer_flag = false return status static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED

Platform event callback handlers static const ble_custom_event_cb_t app_platform_event_handle = platform_event_ready = platform_interrupt_app_event This event not handled in BLE Manager

Register GAP callbacks at BLE manager levelvoid register_samb11_callbacks(void) Register GAP Callbacks printf(rn Assignment 22 Register SAMB11 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)void custom_environment_service_init(void) at_ble_uuid_t environment_service_uuid uint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUID uint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128 memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperature environment_service_characs[0]user_desc_len = 10 environment_service_characs[0]user_desc_max_len = 10 environment_service_characs[0]uuidtype = AT_BLE_UUID_128 memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16) environment_service_characs[0]properties = AT_BLE_CHAR_READ | AT_BLE_CHAR_NOTIFY environment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature value environment_service_characs[0]value_permissions = (AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in SAMB11 if(at_ble_primary_service_define(ampenvironment_service_uuid

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 53

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 54: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(rn Assignment 41 Failed to Initialize custom environment service) else printf(rn Assignment 41 Initialize custom environment service) Callback registered for char changed eventstatic at_ble_status_t custom_char_changed_app_event (void param) at_ble_characteristic_changed_t char_changed_param_handle = (at_ble_characteristic_changed_t )param if((environment_service_characs[0]client_config_handle == char_changed_param_handle -gtchar_handle) ampamp (char_changed_param_handle-gtchar_new_value[0])) timer_flag = false hw_timer_start(10) printf(rn Assignment 41Characteristic changed event) return AT_BLE_SUCCESS

Callback registered for notification confirmed eventstatic at_ble_status_t custom_notification_confirmation_handler (void param) at_ble_cmd_complete_event_t event_param = (at_ble_cmd_complete_event_t )param if (event_param-gtstatus == AT_BLE_SUCCESS) printf(rn Assignment 41Notification Successfully sent over the air) else printf(rn Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESSstatic const ble_gatt_server_event_cb_t app_gatt_server_handle = notification_confirmed= custom_notification_confirmation_handler characteristic_changed = custom_char_changed_app_event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(rn Assignment 41 Register GATT Server callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GATT_SERVER_EVENT_TYPEampapp_gatt_server_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register platform event callback for user defined eventsvoid register_platform_event_callbacks(void) Register callbacks for user defined custom events printf(rn Assignment 42 Register Platform callback) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_CUSTOM_EVENT_TYPEampapp_platform_event_handle) if (ble_status = true) printf(rnError when Registering SAMB11 callbacks)

Register GATT callbacks at BLE manager levelvoid send_temperature_notification(void) Register GAP Callbacks printf(rn Assignment 42 Send temperature update notification) Dummy temperature value Temperature_value++ if(Temperature_value gt 75) Temperature_value = 25 Update attribute data base ble_status = at_ble_characteristic_value_set( environment_service_characs[0]char_val_handle (uint8_t )ampTemperature_value sizeof(Temperature_value)) ble_status = at_ble_notification_send(0 environment_service_characs[0]char_val_handle) if(ble_status = AT_BLE_SUCCESS) printf(rn fail to send temperature update notification )

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 54

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 55: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

int main(void) platform_driver_init() acquire_sleep_lock() Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization gpio_init() button_init() button_register_callback(button_cb) hw_timer_register_callback(timer_callback_fn)

DBG_LOG(Initializing BLE Application) initialize the BLE chip and Set the Device Address ble_device_init(NULL) Register SAMB11 Gap Callbacks register_samb11_callbacks () Custom service init custom_environment_service_init ( )

Register Gatt server callbacks register_gatt_server_callbacks ( ) Register SAMB11 Platform Callbacks register_platform_event_callbacks() Start Advertising process start_advertisement() register_resume_callback(platform_resume_cb) Set ULP mode ble_set_ulp_mode(BLE_ULP_MODE_CLEAR) while(true) BLE Event task ble_event_task(BLE_EVENT_TIMEOUT) Write application task

ATSAMB11Appendix B Custom Service Software Solution

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 55

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 56: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

8 Document Revision HistoryRev A - 062018Table 8-1 Document Revision History - Rev A

Section Changes

Document Initial release

ATSAMB11Document Revision History

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 56

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 57: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

The Microchip Web Site

Microchip provides online support via our web site at httpwwwmicrochipcom This web site is used asa means to make files and information easily available to customers Accessible by using your favoriteInternet browser the web site contains the following information

bull Product Support ndash Data sheets and errata application notes and sample programs designresources userrsquos guides and hardware support documents latest software releases and archivedsoftware

bull General Technical Support ndash Frequently Asked Questions (FAQ) technical support requestsonline discussion groups Microchip consultant program member listing

bull Business of Microchip ndash Product selector and ordering guides latest Microchip press releaseslisting of seminars and events listings of Microchip sales offices distributors and factoryrepresentatives

Customer Change Notification Service

Microchiprsquos customer notification service helps keep customers current on Microchip productsSubscribers will receive e-mail notification whenever there are changes updates revisions or erratarelated to a specified product family or development tool of interest

To register access the Microchip web site at httpwwwmicrochipcom Under ldquoSupportrdquo click onldquoCustomer Change Notificationrdquo and follow the registration instructions

Customer Support

Users of Microchip products can receive assistance through several channels

bull Distributor or Representativebull Local Sales Officebull Field Application Engineer (FAE)bull Technical Support

Customers should contact their distributor representative or Field Application Engineer (FAE) for supportLocal sales offices are also available to help customers A listing of sales offices and locations is includedin the back of this document

Technical support is available through the web site at httpwwwmicrochipcomsupport

Microchip Devices Code Protection Feature

Note the following details of the code protection feature on Microchip devices

bull Microchip products meet the specification contained in their particular Microchip Data Sheetbull Microchip believes that its family of products is one of the most secure families of its kind on the

market today when used in the intended manner and under normal conditionsbull There are dishonest and possibly illegal methods used to breach the code protection feature All of

these methods to our knowledge require using the Microchip products in a manner outside theoperating specifications contained in Microchiprsquos Data Sheets Most likely the person doing so isengaged in theft of intellectual property

bull Microchip is willing to work with the customer who is concerned about the integrity of their code

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 57

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 58: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

bull Neither Microchip nor any other semiconductor manufacturer can guarantee the security of theircode Code protection does not mean that we are guaranteeing the product as ldquounbreakablerdquo

Code protection is constantly evolving We at Microchip are committed to continuously improving thecode protection features of our products Attempts to break Microchiprsquos code protection feature may be aviolation of the Digital Millennium Copyright Act If such acts allow unauthorized access to your softwareor other copyrighted work you may have a right to sue for relief under that Act

Legal Notice

Information contained in this publication regarding device applications and the like is provided only foryour convenience and may be superseded by updates It is your responsibility to ensure that yourapplication meets with your specifications MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED WRITTEN OR ORAL STATUTORYOR OTHERWISE RELATED TO THE INFORMATION INCLUDING BUT NOT LIMITED TO ITSCONDITION QUALITY PERFORMANCE MERCHANTABILITY OR FITNESS FOR PURPOSEMicrochip disclaims all liability arising from this information and its use Use of Microchip devices in lifesupport andor safety applications is entirely at the buyerrsquos risk and the buyer agrees to defendindemnify and hold harmless Microchip from any and all damages claims suits or expenses resultingfrom such use No licenses are conveyed implicitly or otherwise under any Microchip intellectualproperty rights unless otherwise stated

Trademarks

The Microchip name and logo the Microchip logo AnyRate AVR AVR logo AVR Freaks BeaconThingsBitCloud CryptoMemory CryptoRF dsPIC FlashFlex flexPWR Heldo JukeBlox KeeLoq KeeLoq logoKleer LANCheck LINK MD maXStylus maXTouch MediaLB megaAVR MOST MOST logo MPLABOptoLyzer PIC picoPower PICSTART PIC32 logo Prochip Designer QTouch RightTouch SAM-BASpyNIC SST SST Logo SuperFlash tinyAVR UNIO and XMEGA are registered trademarks ofMicrochip Technology Incorporated in the USA and other countries

ClockWorks The Embedded Control Solutions Company EtherSynch Hyper Speed Control HyperLightLoad IntelliMOS mTouch Precision Edge and Quiet-Wire are registered trademarks of MicrochipTechnology Incorporated in the USA

Adjacent Key Suppression AKS Analog-for-the-Digital Age Any Capacitor AnyIn AnyOut BodyComchipKIT chipKIT logo CodeGuard CryptoAuthentication CryptoCompanion CryptoControllerdsPICDEM dsPICDEMnet Dynamic Average Matching DAM ECAN EtherGREEN In-Circuit SerialProgramming ICSP Inter-Chip Connectivity JitterBlocker KleerNet KleerNet logo Mindi MiWimotorBench MPASM MPF MPLAB Certified logo MPLIB MPLINK MultiTRAK NetDetach OmniscientCode Generation PICDEM PICDEMnet PICkit PICtail PureSilicon QMatrix RightTouch logo REALICE Ripple Blocker SAM-ICE Serial Quad IO SMART-IS SQI SuperSwitcher SuperSwitcher II TotalEndurance TSHARC USBCheck VariSense ViewSpan WiperLock Wireless DNA and ZENA aretrademarks of Microchip Technology Incorporated in the USA and other countries

SQTP is a service mark of Microchip Technology Incorporated in the USA

Silicon Storage Technology is a registered trademark of Microchip Technology Inc in other countries

GestIC is a registered trademark of Microchip Technology Germany II GmbH amp Co KG a subsidiary ofMicrochip Technology Inc in other countries

All other trademarks mentioned herein are property of their respective companies

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 58

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 59: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved

ISBN 978-1-5224-3174-9

Quality Management System Certified by DNV

ISOTS 16949Microchip received ISOTS-169492009 certification for its worldwide headquarters design and waferfabrication facilities in Chandler and Tempe Arizona Gresham Oregon and design centers in Californiaand India The Companyrsquos quality system processes and procedures are for its PICreg MCUs and dsPICreg

DSCs KEELOQreg code hopping devices Serial EEPROMs microperipherals nonvolatile memory andanalog products In addition Microchiprsquos quality system for the design and manufacture of developmentsystems is ISO 90012000 certified

ATSAMB11

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 59

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service
Page 60: ATSAMB11 Custom Service Implementationww1.microchip.com/downloads/en/AppNotes/ATSAMB11-Custom... · 2018-06-05 · ATSAMB11 ATSAMB11 Custom Service Implementation Introduction This

AMERICAS ASIAPACIFIC ASIAPACIFIC EUROPECorporate Office2355 West Chandler BlvdChandler AZ 85224-6199Tel 480-792-7200Fax 480-792-7277Technical SupporthttpwwwmicrochipcomsupportWeb AddresswwwmicrochipcomAtlantaDuluth GATel 678-957-9614Fax 678-957-1455Austin TXTel 512-257-3370BostonWestborough MATel 774-760-0087Fax 774-760-0088ChicagoItasca ILTel 630-285-0071Fax 630-285-0075DallasAddison TXTel 972-818-7423Fax 972-818-2924DetroitNovi MITel 248-848-4000Houston TXTel 281-894-5983IndianapolisNoblesville INTel 317-773-8323Fax 317-773-5453Tel 317-536-2380Los AngelesMission Viejo CATel 949-462-9523Fax 949-462-9608Tel 951-273-7800Raleigh NCTel 919-844-7510New York NYTel 631-435-6000San Jose CATel 408-735-9110Tel 408-436-4270Canada - TorontoTel 905-695-1980Fax 905-695-2078

Australia - SydneyTel 61-2-9868-6733China - BeijingTel 86-10-8569-7000China - ChengduTel 86-28-8665-5511China - ChongqingTel 86-23-8980-9588China - DongguanTel 86-769-8702-9880China - GuangzhouTel 86-20-8755-8029China - HangzhouTel 86-571-8792-8115China - Hong Kong SARTel 852-2943-5100China - NanjingTel 86-25-8473-2460China - QingdaoTel 86-532-8502-7355China - ShanghaiTel 86-21-3326-8000China - ShenyangTel 86-24-2334-2829China - ShenzhenTel 86-755-8864-2200China - SuzhouTel 86-186-6233-1526China - WuhanTel 86-27-5980-5300China - XianTel 86-29-8833-7252China - XiamenTel 86-592-2388138China - ZhuhaiTel 86-756-3210040

India - BangaloreTel 91-80-3090-4444India - New DelhiTel 91-11-4160-8631India - PuneTel 91-20-4121-0141Japan - OsakaTel 81-6-6152-7160Japan - TokyoTel 81-3-6880- 3770Korea - DaeguTel 82-53-744-4301Korea - SeoulTel 82-2-554-7200Malaysia - Kuala LumpurTel 60-3-7651-7906Malaysia - PenangTel 60-4-227-8870Philippines - ManilaTel 63-2-634-9065SingaporeTel 65-6334-8870Taiwan - Hsin ChuTel 886-3-577-8366Taiwan - KaohsiungTel 886-7-213-7830Taiwan - TaipeiTel 886-2-2508-8600Thailand - BangkokTel 66-2-694-1351Vietnam - Ho Chi MinhTel 84-28-5448-2100

Austria - WelsTel 43-7242-2244-39Fax 43-7242-2244-393Denmark - CopenhagenTel 45-4450-2828Fax 45-4485-2829Finland - EspooTel 358-9-4520-820France - ParisTel 33-1-69-53-63-20Fax 33-1-69-30-90-79Germany - GarchingTel 49-8931-9700Germany - HaanTel 49-2129-3766400Germany - HeilbronnTel 49-7131-67-3636Germany - KarlsruheTel 49-721-625370Germany - MunichTel 49-89-627-144-0Fax 49-89-627-144-44Germany - RosenheimTel 49-8031-354-560Israel - RarsquoananaTel 972-9-744-7705Italy - MilanTel 39-0331-742611Fax 39-0331-466781Italy - PadovaTel 39-049-7625286Netherlands - DrunenTel 31-416-690399Fax 31-416-690340Norway - TrondheimTel 47-7289-7561Poland - WarsawTel 48-22-3325737Romania - BucharestTel 40-21-407-87-50Spain - MadridTel 34-91-708-08-90Fax 34-91-708-08-91Sweden - GothenbergTel 46-31-704-60-40Sweden - StockholmTel 46-8-5090-4654UK - WokinghamTel 44-118-921-5800Fax 44-118-921-5820

Worldwide Sales and Service

copy 2018 Microchip Technology Inc Application Note DS00002715A-page 60

  • Introduction
  • Table of Contents
  • 1 Getting Started
    • 11 Software Prerequisites
      • 111 Installation Steps of Atmel Studio 7
      • 112 Installing Microchip Bluetooth Data Application on a Mobile Device
      • 113 Installing ATSAMB11 Device Pack using Device Pack Manager
        • 12 ATSAMB11 Embedded Firmware
        • 13 ATSAMB11 Software API
        • 14 Hardware Prerequisites
          • 141 SAMB11-ZR Xplained Pro Board
            • 15 Hardware Setup
              • 2 Creating and Initializing the Project
                • 21 Creating Project from ASF
                • 22 Compiling and Testing the Project
                  • 3 Establishing Connection with Central Device
                    • 31 Configuring and Starting the Advertisement Process
                      • 311 Flags (AD Type 0x00)
                      • 312 Available Service UUID (AD Types 0x02 to 0x07)
                      • 313 Device Name (AD Types 0x08 to 0x09)
                        • 3131 Setting the Advertisement Payload (at_ble_adv_data_set)
                        • 3132 Starting the Advertisement Process (at_ble_adv_start)
                          • 314 Advertisement Process
                            • 3141 Starting the Advertisement Process
                                • 32 Managing GAP events
                                  • 321 Handling of Connected and Disconnected GAP Events
                                      • 4 SetupHandling of Pre-Defined Service from ASF
                                        • 41 Adding Device Info Service Component from ASF Wizard to Project
                                        • 42 Configuring and Loading Device Information Service
                                          • 421 Procedure to Configure and Load Device Info Service
                                              • 5 Setting up and Handling Custom Service
                                                • 51 Configuring and Loading the Custom Environment Service
                                                  • 511 Procedure to Configure and Load Custom Environment Service
                                                    • 52 Updating the Temperature Characteristic
                                                      • 521 Setting a Characteristic Value ( at_ble_characteristic_value_set)
                                                      • 522 Sending a Notification (at_ble_notification_send)
                                                      • 523 Sending Temperature Information Once in Every 10 Seconds to Central
                                                          • 6 Appendix A Pre-defined Service Software Solution
                                                          • 7 Appendix B Custom Service Software Solution
                                                          • 8 Document Revision History
                                                          • The Microchip Web Site
                                                          • Customer Change Notification Service
                                                          • Customer Support
                                                          • Microchip Devices Code Protection Feature
                                                          • Legal Notice
                                                          • Trademarks
                                                          • Quality Management System Certified by DNV
                                                          • Worldwide Sales and Service