ATBTLC1000 Bluetoothreg Low Energy Custom Service Implementation
Introduction
This document demonstrates how to use the ATBTLC1000 Bluetoothreg Low Energy SoC by building acustom specific profile using the Microchip BluSDK This document includes the following topics
bull Technical overview of the ATBTLC1000 board from hardware architecture to software designbull Description of the required process for developing the Bluetooth Low Energy peripheral application
with the ATBTLC1000bull Handling of Bluetooth Low Energy custom services and characteristics
Note The custom service implementation procedure uses the ATBTLC1000ZR-XSTK kit Thisprocedure is also applicable for other supported platforms as mentioned in BluSDK Release Notes
Figure 1 Bluetooth Low Energy System Solution with ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 1
Table of Contents
Introduction1
1 Getting Started 411 Software Prerequisites 412 Software Setup413 ATBTLC1000 Embedded Firmware 514 ATBTLC1000 Host Software API 515 Hardware Prerequisites716 Hardware Setup 9
2 Creating the Project and Initializing 1221 Creating Project from ASF 1222 Configuring ASF for ATBTLC1000-ZR 1523 Compiling and Testing the Project16
3 Establishing Connection with Central Device 1831 Configuring and Starting the Advertisement Process1932 Managing GAP events 25
4 SettingHandling of Pre-Defined Service 3041 Adding Device Info Service Component from ASF Wizard to Project 3142 Configuring and Loading Device Information Service 33
5 Setting up and Handling Custom Service3751 Configuring and Loading the Custom Environment Service3852 Updating the Temperature Characteristic43
6 Appendix A Software Solution - Pre-Defined Svc 47
7 Appendix B Software Solution - Custom Service 49
8 Document Revision History 53
The Microchip Web Site 54
Customer Change Notification Service54
Customer Support 54
Microchip Devices Code Protection Feature 54
Legal Notice55
Trademarks 55
Quality Management System Certified by DNV56
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 2
Worldwide Sales and Service57
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 3
1 Getting StartedThis chapter describes the basic software and hardware requirements and setup
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 The software for ATBTLC1000-ZR is supported with ASF 3351 and above
Note For more information on the previous releases refer to the Atmel Studio Release Notes availableon the Microchip web page
12 Software Setup
121 Installation of Microchip SmartConnect application on a Mobile device1 Open the Apple Storereg (iPhoneiOS) or Google Playtrade Store (Android) on the mobile device2 Search for ldquoMicrochip SmartConnectrdquo3 Click Install to install application on the device The Microchip SmartConnect application is now
installed on the mobile deviceFigure 1-1 Microchip SmartConnect Dashboard
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 4
13 ATBTLC1000 Embedded FirmwareThe management of Bluetooth Low Energy communication is based on the network stack stored inATBTLC1000 ROM This stack requires parameters such as GAP parameters and attributes to befunctional which are pushed from Host controller into ATBTLC1000 internal SRAM using GenericTransport Layer (GTL)
The ROM coded firmware embeds the layers of Bluetooth Low Energy stack that runs on top of theinternal hardcoded peripheral drivers and RTOS scheduler
bull Generic Access Profile (GAP)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 lookuptable stored in device SRAM
bull Security Manager (SM)The Security Manager defines the procedure for pairing authentication and encryption betweenBLE 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 of goingthrough the complete Bluetooth Low Energy Protocol Stack
14 ATBTLC1000 Host Software APIThe ATBTLC1000 is provided with a dedicated Host software API layer The purpose of this API layer isto provide an easy and reliable solution to add Bluetooth Low Energy capabilities to any user applicationThe API provides a set of high level Bluetooth function with abstraction of the transport protocol usedbetween the host MCU and the ATBTLC1000
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 5
Figure 1-2 Host Software API
Figure 1-3 BluSDK File Architecture
The API operation relies on a request-response mechanism The specific requests are sent toATBTLC1000 through dedicated API function call The event messages are then returned by theATBTLC1000 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the host device according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flowchart
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 6
Figure 1-4 Bluetooth Low Energy Peripheral Application Flowchart
WARNING The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time
15 Hardware PrerequisitesThis document uses the ATBTLC1000ZR-XSTK kit The ATBTLC1000ZR-XSTK kit is comprised of theSAM L21 Xplained Pro (XPRO) and ATBTLC1000ZR XPRO extension board The following sectionsprovide an overview of these kits and their features
151 SMARTtrade SAM L21 Xplained ProThe SMARTtrade SAM L21 Xplained Pro evaluation kit is used to evaluate the ATSAML21J18Bmicrocontroller This kit includes an on-board embedded debugger to program and debugATSAML21J18B The kit also contains an on-board current measurement circuitry which enables theuser to measure current profile over time without any external tools The connection with any XplainedPro modules or external component is possible through available external connectors which makes theboard perfect for prototyping the low-power applications
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 7
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Table of Contents
Introduction1
1 Getting Started 411 Software Prerequisites 412 Software Setup413 ATBTLC1000 Embedded Firmware 514 ATBTLC1000 Host Software API 515 Hardware Prerequisites716 Hardware Setup 9
2 Creating the Project and Initializing 1221 Creating Project from ASF 1222 Configuring ASF for ATBTLC1000-ZR 1523 Compiling and Testing the Project16
3 Establishing Connection with Central Device 1831 Configuring and Starting the Advertisement Process1932 Managing GAP events 25
4 SettingHandling of Pre-Defined Service 3041 Adding Device Info Service Component from ASF Wizard to Project 3142 Configuring and Loading Device Information Service 33
5 Setting up and Handling Custom Service3751 Configuring and Loading the Custom Environment Service3852 Updating the Temperature Characteristic43
6 Appendix A Software Solution - Pre-Defined Svc 47
7 Appendix B Software Solution - Custom Service 49
8 Document Revision History 53
The Microchip Web Site 54
Customer Change Notification Service54
Customer Support 54
Microchip Devices Code Protection Feature 54
Legal Notice55
Trademarks 55
Quality Management System Certified by DNV56
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 2
Worldwide Sales and Service57
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 3
1 Getting StartedThis chapter describes the basic software and hardware requirements and setup
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 The software for ATBTLC1000-ZR is supported with ASF 3351 and above
Note For more information on the previous releases refer to the Atmel Studio Release Notes availableon the Microchip web page
12 Software Setup
121 Installation of Microchip SmartConnect application on a Mobile device1 Open the Apple Storereg (iPhoneiOS) or Google Playtrade Store (Android) on the mobile device2 Search for ldquoMicrochip SmartConnectrdquo3 Click Install to install application on the device The Microchip SmartConnect application is now
installed on the mobile deviceFigure 1-1 Microchip SmartConnect Dashboard
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 4
13 ATBTLC1000 Embedded FirmwareThe management of Bluetooth Low Energy communication is based on the network stack stored inATBTLC1000 ROM This stack requires parameters such as GAP parameters and attributes to befunctional which are pushed from Host controller into ATBTLC1000 internal SRAM using GenericTransport Layer (GTL)
The ROM coded firmware embeds the layers of Bluetooth Low Energy stack that runs on top of theinternal hardcoded peripheral drivers and RTOS scheduler
bull Generic Access Profile (GAP)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 lookuptable stored in device SRAM
bull Security Manager (SM)The Security Manager defines the procedure for pairing authentication and encryption betweenBLE 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 of goingthrough the complete Bluetooth Low Energy Protocol Stack
14 ATBTLC1000 Host Software APIThe ATBTLC1000 is provided with a dedicated Host software API layer The purpose of this API layer isto provide an easy and reliable solution to add Bluetooth Low Energy capabilities to any user applicationThe API provides a set of high level Bluetooth function with abstraction of the transport protocol usedbetween the host MCU and the ATBTLC1000
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 5
Figure 1-2 Host Software API
Figure 1-3 BluSDK File Architecture
The API operation relies on a request-response mechanism The specific requests are sent toATBTLC1000 through dedicated API function call The event messages are then returned by theATBTLC1000 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the host device according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flowchart
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 6
Figure 1-4 Bluetooth Low Energy Peripheral Application Flowchart
WARNING The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time
15 Hardware PrerequisitesThis document uses the ATBTLC1000ZR-XSTK kit The ATBTLC1000ZR-XSTK kit is comprised of theSAM L21 Xplained Pro (XPRO) and ATBTLC1000ZR XPRO extension board The following sectionsprovide an overview of these kits and their features
151 SMARTtrade SAM L21 Xplained ProThe SMARTtrade SAM L21 Xplained Pro evaluation kit is used to evaluate the ATSAML21J18Bmicrocontroller This kit includes an on-board embedded debugger to program and debugATSAML21J18B The kit also contains an on-board current measurement circuitry which enables theuser to measure current profile over time without any external tools The connection with any XplainedPro modules or external component is possible through available external connectors which makes theboard perfect for prototyping the low-power applications
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 7
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Worldwide Sales and Service57
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 3
1 Getting StartedThis chapter describes the basic software and hardware requirements and setup
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 The software for ATBTLC1000-ZR is supported with ASF 3351 and above
Note For more information on the previous releases refer to the Atmel Studio Release Notes availableon the Microchip web page
12 Software Setup
121 Installation of Microchip SmartConnect application on a Mobile device1 Open the Apple Storereg (iPhoneiOS) or Google Playtrade Store (Android) on the mobile device2 Search for ldquoMicrochip SmartConnectrdquo3 Click Install to install application on the device The Microchip SmartConnect application is now
installed on the mobile deviceFigure 1-1 Microchip SmartConnect Dashboard
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 4
13 ATBTLC1000 Embedded FirmwareThe management of Bluetooth Low Energy communication is based on the network stack stored inATBTLC1000 ROM This stack requires parameters such as GAP parameters and attributes to befunctional which are pushed from Host controller into ATBTLC1000 internal SRAM using GenericTransport Layer (GTL)
The ROM coded firmware embeds the layers of Bluetooth Low Energy stack that runs on top of theinternal hardcoded peripheral drivers and RTOS scheduler
bull Generic Access Profile (GAP)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 lookuptable stored in device SRAM
bull Security Manager (SM)The Security Manager defines the procedure for pairing authentication and encryption betweenBLE 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 of goingthrough the complete Bluetooth Low Energy Protocol Stack
14 ATBTLC1000 Host Software APIThe ATBTLC1000 is provided with a dedicated Host software API layer The purpose of this API layer isto provide an easy and reliable solution to add Bluetooth Low Energy capabilities to any user applicationThe API provides a set of high level Bluetooth function with abstraction of the transport protocol usedbetween the host MCU and the ATBTLC1000
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 5
Figure 1-2 Host Software API
Figure 1-3 BluSDK File Architecture
The API operation relies on a request-response mechanism The specific requests are sent toATBTLC1000 through dedicated API function call The event messages are then returned by theATBTLC1000 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the host device according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flowchart
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 6
Figure 1-4 Bluetooth Low Energy Peripheral Application Flowchart
WARNING The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time
15 Hardware PrerequisitesThis document uses the ATBTLC1000ZR-XSTK kit The ATBTLC1000ZR-XSTK kit is comprised of theSAM L21 Xplained Pro (XPRO) and ATBTLC1000ZR XPRO extension board The following sectionsprovide an overview of these kits and their features
151 SMARTtrade SAM L21 Xplained ProThe SMARTtrade SAM L21 Xplained Pro evaluation kit is used to evaluate the ATSAML21J18Bmicrocontroller This kit includes an on-board embedded debugger to program and debugATSAML21J18B The kit also contains an on-board current measurement circuitry which enables theuser to measure current profile over time without any external tools The connection with any XplainedPro modules or external component is possible through available external connectors which makes theboard perfect for prototyping the low-power applications
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 7
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
1 Getting StartedThis chapter describes the basic software and hardware requirements and setup
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 The software for ATBTLC1000-ZR is supported with ASF 3351 and above
Note For more information on the previous releases refer to the Atmel Studio Release Notes availableon the Microchip web page
12 Software Setup
121 Installation of Microchip SmartConnect application on a Mobile device1 Open the Apple Storereg (iPhoneiOS) or Google Playtrade Store (Android) on the mobile device2 Search for ldquoMicrochip SmartConnectrdquo3 Click Install to install application on the device The Microchip SmartConnect application is now
installed on the mobile deviceFigure 1-1 Microchip SmartConnect Dashboard
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 4
13 ATBTLC1000 Embedded FirmwareThe management of Bluetooth Low Energy communication is based on the network stack stored inATBTLC1000 ROM This stack requires parameters such as GAP parameters and attributes to befunctional which are pushed from Host controller into ATBTLC1000 internal SRAM using GenericTransport Layer (GTL)
The ROM coded firmware embeds the layers of Bluetooth Low Energy stack that runs on top of theinternal hardcoded peripheral drivers and RTOS scheduler
bull Generic Access Profile (GAP)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 lookuptable stored in device SRAM
bull Security Manager (SM)The Security Manager defines the procedure for pairing authentication and encryption betweenBLE 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 of goingthrough the complete Bluetooth Low Energy Protocol Stack
14 ATBTLC1000 Host Software APIThe ATBTLC1000 is provided with a dedicated Host software API layer The purpose of this API layer isto provide an easy and reliable solution to add Bluetooth Low Energy capabilities to any user applicationThe API provides a set of high level Bluetooth function with abstraction of the transport protocol usedbetween the host MCU and the ATBTLC1000
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 5
Figure 1-2 Host Software API
Figure 1-3 BluSDK File Architecture
The API operation relies on a request-response mechanism The specific requests are sent toATBTLC1000 through dedicated API function call The event messages are then returned by theATBTLC1000 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the host device according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flowchart
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 6
Figure 1-4 Bluetooth Low Energy Peripheral Application Flowchart
WARNING The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time
15 Hardware PrerequisitesThis document uses the ATBTLC1000ZR-XSTK kit The ATBTLC1000ZR-XSTK kit is comprised of theSAM L21 Xplained Pro (XPRO) and ATBTLC1000ZR XPRO extension board The following sectionsprovide an overview of these kits and their features
151 SMARTtrade SAM L21 Xplained ProThe SMARTtrade SAM L21 Xplained Pro evaluation kit is used to evaluate the ATSAML21J18Bmicrocontroller This kit includes an on-board embedded debugger to program and debugATSAML21J18B The kit also contains an on-board current measurement circuitry which enables theuser to measure current profile over time without any external tools The connection with any XplainedPro modules or external component is possible through available external connectors which makes theboard perfect for prototyping the low-power applications
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 7
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
13 ATBTLC1000 Embedded FirmwareThe management of Bluetooth Low Energy communication is based on the network stack stored inATBTLC1000 ROM This stack requires parameters such as GAP parameters and attributes to befunctional which are pushed from Host controller into ATBTLC1000 internal SRAM using GenericTransport Layer (GTL)
The ROM coded firmware embeds the layers of Bluetooth Low Energy stack that runs on top of theinternal hardcoded peripheral drivers and RTOS scheduler
bull Generic Access Profile (GAP)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 lookuptable stored in device SRAM
bull Security Manager (SM)The Security Manager defines the procedure for pairing authentication and encryption betweenBLE 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 of goingthrough the complete Bluetooth Low Energy Protocol Stack
14 ATBTLC1000 Host Software APIThe ATBTLC1000 is provided with a dedicated Host software API layer The purpose of this API layer isto provide an easy and reliable solution to add Bluetooth Low Energy capabilities to any user applicationThe API provides a set of high level Bluetooth function with abstraction of the transport protocol usedbetween the host MCU and the ATBTLC1000
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 5
Figure 1-2 Host Software API
Figure 1-3 BluSDK File Architecture
The API operation relies on a request-response mechanism The specific requests are sent toATBTLC1000 through dedicated API function call The event messages are then returned by theATBTLC1000 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the host device according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flowchart
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 6
Figure 1-4 Bluetooth Low Energy Peripheral Application Flowchart
WARNING The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time
15 Hardware PrerequisitesThis document uses the ATBTLC1000ZR-XSTK kit The ATBTLC1000ZR-XSTK kit is comprised of theSAM L21 Xplained Pro (XPRO) and ATBTLC1000ZR XPRO extension board The following sectionsprovide an overview of these kits and their features
151 SMARTtrade SAM L21 Xplained ProThe SMARTtrade SAM L21 Xplained Pro evaluation kit is used to evaluate the ATSAML21J18Bmicrocontroller This kit includes an on-board embedded debugger to program and debugATSAML21J18B The kit also contains an on-board current measurement circuitry which enables theuser to measure current profile over time without any external tools The connection with any XplainedPro modules or external component is possible through available external connectors which makes theboard perfect for prototyping the low-power applications
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 7
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 1-2 Host Software API
Figure 1-3 BluSDK File Architecture
The API operation relies on a request-response mechanism The specific requests are sent toATBTLC1000 through dedicated API function call The event messages are then returned by theATBTLC1000 on request processing or on specific Bluetooth Low Energy events These event messagesare to be handled by the host device according to the user application requirements The following figureillustrates a typical Bluetooth Low Energy peripheral application flowchart
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 6
Figure 1-4 Bluetooth Low Energy Peripheral Application Flowchart
WARNING The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time
15 Hardware PrerequisitesThis document uses the ATBTLC1000ZR-XSTK kit The ATBTLC1000ZR-XSTK kit is comprised of theSAM L21 Xplained Pro (XPRO) and ATBTLC1000ZR XPRO extension board The following sectionsprovide an overview of these kits and their features
151 SMARTtrade SAM L21 Xplained ProThe SMARTtrade SAM L21 Xplained Pro evaluation kit is used to evaluate the ATSAML21J18Bmicrocontroller This kit includes an on-board embedded debugger to program and debugATSAML21J18B The kit also contains an on-board current measurement circuitry which enables theuser to measure current profile over time without any external tools The connection with any XplainedPro modules or external component is possible through available external connectors which makes theboard perfect for prototyping the low-power applications
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 7
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 1-4 Bluetooth Low Energy Peripheral Application Flowchart
WARNING The user application must be non-blocking to ensure that the Bluetooth Low Energy events arehandled in time
15 Hardware PrerequisitesThis document uses the ATBTLC1000ZR-XSTK kit The ATBTLC1000ZR-XSTK kit is comprised of theSAM L21 Xplained Pro (XPRO) and ATBTLC1000ZR XPRO extension board The following sectionsprovide an overview of these kits and their features
151 SMARTtrade SAM L21 Xplained ProThe SMARTtrade SAM L21 Xplained Pro evaluation kit is used to evaluate the ATSAML21J18Bmicrocontroller This kit includes an on-board embedded debugger to program and debugATSAML21J18B The kit also contains an on-board current measurement circuitry which enables theuser to measure current profile over time without any external tools The connection with any XplainedPro modules or external component is possible through available external connectors which makes theboard perfect for prototyping the low-power applications
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 7
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 1-5 SAM L21 Xplained Pro Module
152 ATBTLC1000ZR Xplained Pro Extension boardThe ATBTLC1000ZR Xplained Pro extension evaluation kit is Bluetooth Low Energy SoC ATBTLC1000-ZR110CA module This extension is plugged to any of the supported host MCU Xplained Pro evaluationboards to quickly add Bluetooth Low Energy connectivity to the platform This kit provides easy access tothe features of the ATBTLC1000-ZR110CA Bluetooth Low Energy module and illustrates how to integratethe device in a custom design which is supported by the Atmel Studio integrated development platform
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 8
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 1-6 ATBTLC1000ZR Xpro Board
The ATBTLC1000ZR Xplained Pro extension board contains
bull ATBLTC1000-ZR110CA Module ndash Bluetooth Low Energy module with 24 GHz Bluetooth LowEnergy ATBTLC1000-XR1100A SiP
bull AT30TSE758A Digital Temperature Sensor ndash Integrated temperature sensor with nonvolatileregisters and serial EEPROM Compatible with two-wire (I2C) and SMBus serial interfaces
bull Current Measurement Header ndash Allows measurement of the current consumption of the board Itmust be closed to enable power to the ATBTLC1000-ZR110CA module
16 Hardware Setup1 Ensure that ATBTLC1000ZR-XPRO power consumption header is closed and that jumpers are
placed on pins 2 to 3 of headers J105 J106 J107 and J108 as shown in the following figure
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 9
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 1-7 ATBTLC1000ZR-XPRO Extension
2 Connect the ATBTLC1000ZR-XPRO extension to EXT1 of SAM L21 XPRO as illustrated in thefollowing figureFigure 1-8 ATBTLC1000ZR-XPRO Extension connected with SAM L21 XPRO
3 Connect the board to PC using the ldquoDebug USB ConnectorrdquoFigure 1-9 SAM L21 XPRO Connection to PC
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 10
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
4 Now the Hardware is ready for development
ATBTLC1000Getting Started
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 11
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
2 Creating the Project and InitializingThis chapter provides 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
The hardware connection between the SAM L21 XPRO and the ATBTLC1000ZR XPRO board isillustrated in following figure This SAM L21 board is used as host MCUFigure 2-1 ATBTLC1000ZR Xpro Board Connection with SAM L21
Note For more details refer to module datasheet and XPRO board design documentation
21 Creating Project from ASFAdvanced Software Framework has a pre-configured Bluetooth Low Energy Startup template project thatincludes Bluetooth Low Energy software API for Host and ATBTLC1000 and their peripheral driverdependencies This is used as starting project for any Bluetooth Low Energy project development
To create the project follow the steps below
1 Search for the ldquoBLE-Startup Templaterdquo from the File gt New gt Example Project menu in AtmelStudio
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 12
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 2-2 Advanced Software Framework_New Example Project
Note ATBTLC1000SAMB11 related projects are prefixed with ldquoBLErdquo making it easier to filter theproject in the dialogue box
2 Select the appropriate ldquoBLE-Startup Templaterdquo project corresponding to the intended Host MCUXplained Pro board and then press OK button to import the BLE startup template project SelectldquoBLE-Startup Template ndash SAM L21 Xplained Pro SAML21J18Brdquo for this hands-onNote Rev B XPRO boards can be identified by SAML21J18B silk screen marking below SAML21MCU
3 The BLE startup project is now created and loaded in Atmel StudioFigure 2-3 Startup_Template Project
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 13
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Note The main project routine of ldquoStartup Template projectrdquo already includes host MCU low levelinitialization BLE and ATBTLC1000 initialization The added ASF components in project can beviewed from ldquoASFgtASF Wizardrdquo Select the created project from Project drop down box
Figure 2-4 ASF Wizard Window
ndash BLE_STACK Platform Interface ndash Core manager of Bluetooth Low Energy Host API Itmanages ATBTLC1000 device initialization GAP and GATT events
ndash Timer Driver ndash Task timer functionality by using a Timer Counter (TC) or Timer Counter forControl (TCC) peripheral
ndash Console UART ndash Universal Asynchronous ReceiverTransmitter (UART) communication insynchronousblocking mode
ndash Generic Board Support ndash Host MCU Board specific initializationndash System Drivers ndash Select MCUrsquos System peripheral drivers These drivers are included by
default in ASF projects and manage the clocks and oscillator of the system4 The main routine contains the MCU low level initialization and ATBTLC1000 initialization The
following figure illustrates the flowchart of the main routine
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 14
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 2-5 Main Routine Flowchart
22 Configuring ASF for ATBTLC1000-ZR1 The default ldquoStartup Template Projectrdquo is configured for ATBTLC1000-MR module with 6-Wire
mode2 Navigate to Project properties Project gt Project properties gt Toolchain gt ARMGNU C Compiler gt
Symbols3 The ATBTLC1000ZR-XSTK kit uses the ATBTLC1000-ZR110CA module Change symbol
BLE_MODULE to BTLC1000_ZR and enable UART_FLOWCONTROL_4WIRE_MODE forATBTLC1000-ZR module as shown in the figure belowFigure 2-6 Startup Template Project Window
Note This configuration change is not required for ATBTLC1000-MR module
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 15
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
23 Compiling and Testing the Project
1 Click the ldquo rdquo button ltF7gt to compile the project2 Verify that no build error appears in Atmel Studio output window
Figure 2-7 Atmel Studio Output Window
3 Connect the SAM L21 XPRO to PC (if not already done)4 To access the project properties go to Project gt
STARTUP_TEMPLATE_SAML21_XPLAINED_PRO_B1 PropertiesFigure 2-8 Compiling the Project
5 In project properties click the Tool tab and select the EDBG of SAM L21 Xplained Pro board asdebuggerprogrammerFigure 2-9 Selection of DebuggerProgrammer
6 Open any Terminal application (for example TeraTerm) Select the COM port enumerated on thePC and set the following parameters
ndash EDBG associated COM Port (Check Windows Device Manager)
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 16
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
ndash Baudrate 115200ndash Parity Nonendash One Stop bitndash Enable Hardware Flow Control
7 Click to save the project ltCtrl+Sgt
8 Click rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt9 The initialization of the ATBTLC1000ZR module must return the Bluetooth Device Address and
Address typeFigure 2-10 Console Log Window
Note 1 If initialization fails make sure to verify the hardware configuration is aligned with the
description refer to 16 Hardware Setup2 The initialization of ATBTLC1000 takes few seconds due to patch download process
ATBTLC1000Creating the Project and Initializing
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 17
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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 Bluetooth connection with acentral device When using ATBTLC1000 device this process is managed by dedicated API function callsassociated with ATBTLC1000 events handling
The interaction between Host MCU ATBTLC1000 and Bluetooth Low Energy central during connectionestablishment is as follows
Figure 3-1 Establishing Connection with Central Device
On host MCU side the management of the Bluetooth connection is performed through three main steps1 GAP callback registration2 Advertisement configuration3 ATBTLC1000 event handling
In the existing project main routine the integration of these steps are highlighted in red in the followingflowchart
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 18
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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 Bluetooth SIG specification To avoid any collision with other wireless networksuch as Wi-Fireg a channel change is performed for each advertisement packet sent (data frequencyhopping) 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)
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 19
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 3-4 PDU Advertising
The following table lists the different PDU types used according to device role
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 our 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 packetFigure 3-5 ADV_IND Advertisement Packet
The ADV_IND payload contains different Advertisement Data types (AD0 - ADn) 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
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 20
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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 - Incomplete list of 16-bit UUIDs (adopted GATT services)bull 0x03 - Complete list of 16-bit UUIDs (adopted GATT services)bull 0x06 - Incomplete list of 128-bit UUIDs (custom GATT services)bull 0x07 - 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 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 - Shortened Local Namebull 0x09 - 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
2 Complete data type list are available at httpswwwbluetoothcomspecificationsassigned-numbersgeneric-access-profile
For management of advertisement process and cover the different configurations specified by SIG theATBTLC1000 Host driver provides the two functions elaborated in the following sections
In the application use these two functions to setup the following ADV_IN type payloadFigure 3-6 ADV_IN Type Payload Process
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 21
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
3131 Setting the Advertisement Payload (ble_advertisement_data_set)Prototype ndashat_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 ndash
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 sent to central Following is an example of itsdefinition
static uint8_t adv_data[] = 0x11 AD1 length = 170x03 AD1 Type = Complete list of 128-bit UUIDs0x1b0xc50xd50xa50x020x000xa60x87 AD1 = UUID MSBs0xe50x110x360x390xc00xba0x5a0xf00x0A AD2 Length = 100x09 AD2 Type = Complete local NamelsquoMrsquorsquoyrsquorsquo_rsquorsquoDrsquorsquoErsquorsquoVrsquo AD2 = ldquoMy_DEVrdquo
3132 Starting the Advertisement Process (at_ble_adv_start)Prototype ndashat_ble_status_t at_ble_adv_start (at_ble_adv_type_t typeat_ble_adv_mode_t modeat_ble_addr_t peer_addrat_ble_filter_type_t filtereduint16_t intervaluint16_t timeoutbool disable_randomness)
Description ndash Start advertisement process
Parameters ndash
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 be
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 22
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
ndash 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
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 is performed in 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 (timeout 655)bull Randomness enabled (disable_randomness = FALSE)
3141 Starting the Advertisement Process1 Open startup_templatec file2 Declare the following ble_status global variable in startup_templatec as volatile
include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehvolatile at_ble_status_t ble_status
3 Declare the following adv_data global variable in startup_templatec as staticstatic uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD)0x09 AD2 Type = Complete local Name
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 23
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
My_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_templatec prototype for thefunction void start_advertisement (void) also this can be added to avoid warningsvoid start_advertisement (void)printf(n 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(n Failed to start advertisement)
5 Start the advertisement process by adding the following highlighted code to the application mainroutineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 PrimaryIncluded service in case of GATT Server while(true) Write application task
6 Click to save the project ltCtrl+Sgt
7 Click button to compile the project ltF7gt8 Verify that no build error appears in Atmel Studio output window
Figure 3-7 Atmel Studio Output Window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 24
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
9 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt10 Open Microchip SmartConnect Application on Android or iOS device and tap START SCAN button
Note The device must appear in Microchip SmartConnect Application
Figure 3-8 Microchip SmartConnect Application
11 Terminal must display the following Log outputFigure 3-9 Log Output Window
32 Managing GAP eventsThe management of the Bluetooth connection at the host MCU level is done through reception andhandling of events reported by the ATBTLC1000 These events are generated by ATBTLC1000 GAPGATT and L2CAP layers to notify the host about the ongoing Bluetooth interaction with other devices inits vicinity
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 25
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
To manage events coming from the ATBTLC1000 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 ATBTLC1000 module
Prototype ndashbool ble_mgr_events_callback_handler(ble_mgr_event_cb_t event_cb_typeble_mgr_event_t event_typeconst voidble_event_handler)
Description ndash Used by ProfileServiceApplication to register the Bluetooth Low Energy eventsrsquocallbacks
Parameters ndash
event_cb_type ndash types of actions to perform on callbacks can be either
REGISTER_CALL_BACK or
UNREGISTER_CALL_BACKevent_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_TYPEble_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 ATBTLC1000 which is not handled in Libraryble_event_callback_t undefined BLE scan information contains the peer device scan information Refer ref at_ble_scan_info_tble_event_callback_t scan_info Once the BLE scan timeout or scan stop triggers the scan report event Refer ref at_ble_scan_report_tble_event_callback_t scan_report Advertisement complete event Refer ref at_ble_adv_cmp_evt_tble_event_callback_t advt_cmp Advertisement report in case of advertisement stopped due to advertisement timeout Refer ref at_ble_adv_report_tble_event_callback_t adv_report BLE device own random address changed event Refer ref at_ble_rand_addr_changed_tble_event_callback_t rand_addr_changed BLE connected event device connected to peer device Refer ref at_ble_connected_tble_event_callback_t connected BLE disconnected event device disconnected from peer device Refer ref at_ble_disconnected_tble_event_callback_t disconnected Connection parameter update done on peer device and own device Refer ref at_ble_conn_param_update_done_t
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 26
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
ble_event_callback_t conn_parameter_update_done Connection parameter update request from peer device Refer ref at_ble_conn_param_update_request_tble_event_callback_t conn_param_update_request Pair complete event as part of end of pairing process Refer ref at_ble_pair_done_tble_event_callback_t pair_done Pair request event from Central device Refer ref at_ble_pair_request_tble_event_callback_t pair_request Slave security request received from peer Peripheral device Refer ref at_ble_slave_sec_request_tble_event_callback_t slave_sec_request Pair Key request event from Peer central device Refer ref at_ble_pair_key_request_tble_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_tble_event_callback_t encryption_request encryption status changed event received from SMP once the encryption is started ref at_ble_encryption_status_changed_tble_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_tble_event_callback_t resolv_rand_addr_status Event is triggered once the connection signature information indication received ref at_ble_sign_counter_tble_event_callback_t sign_counters_ind Peer attribute information indication received Event ref at_ble_peer_att_info_ind_tble_event_callback_t peer_att_info_ind Peer device channel map received indication ref at_ble_channel_map_tble_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 of sensor data update
321 Handling of Connected and Disconnected GAP Events1 Open the startup_templatec file2 Define the following software flags as global variables in startup_templatec file volatile
bool timer_flag = false and volatile bool connected_flag = false3 Declare and implement the following ble_connected_cb function in the
startup_templatec file Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param)printf(n Assignment 22 Application connected )connected_flag = trueALL_UNUSED(param)return AT_BLE_SUCCESS
4 Declare and implement the following ble_disconnected_cb function instartup_templatec file Callback registered for AT_BLE_DISCONNECTED event static at_ble_status_t ble_disconnected_cb (void param)printf(n Assignment 22 Application disconnected )connected_flag = falsestart_advertisement()ALL_UNUSED(param)return AT_BLE_SUCCESS
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 27
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
5 Declare the following static GAP callback structure in ldquostartup_templatecrdquo filestatic const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTEDdisconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
6 Add the following register_btlc1000_callbacks function in startup_templatec Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACKBLE_GAP_EVENT_TYPEampapp_gap_handle)if (ble_status = true)printf(nError when Registering ATBTLC1000 callbacks)
7 Add the register_btlc1000_callbacks function call prior to start advertisement in theapplication main routineint main(void)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Gap Callbacks register_btlc1000_callbacks ( ) Start Advertising process start_advertisement() Register PrimaryIncluded service in case of GATT Server while(true) Write application task
8 Add the ble_event_task function call in the project main loop to handle the different incomingevents from ATBTLC1000while(true)ble_event_task()
9 Press button ltF7gt to compile the project and verify that no build error appear in the AtmelStudio output window
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 28
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 3-10 Atmel Studio Output Window
10 Click ldquo rdquo to save the project ltCtrl+Sgt
11 Click ldquo rdquo to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt and checkcorrect initialization of the ATBTLC1000
12 Open the Microchip SmartConnect application on Androidtrade or iOS device13 Press the ltStart Scangt button and pair peripherals by selecting them in the device list (pass key
123456)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 This can be changed here
Figure 3-11 Console Log Window
Note After peripheral pairing no services information are displayed in Microchip SmartConnectapplication as no service is currently defined and started on peripheral side
ATBTLC1000Establishing Connection with Central Device
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 29
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
4 SettingHandling of Pre-Defined ServiceThe management of services are done in the GATT layer of the ATBTLC1000 ROM coded Bluetooth LowEnergy Stack The GATT transactions are based on high-level nested objects called Profiles Servicesand Characteristics stored in SRAM memory of ATBTLC1000 device This assignment adds the pre-defined service of information service from ASF library
Figure 4-1 ATBTLC1000 GATT Layers
bull ProfilesProfiles are not available in the Bluetooth Low Energy peripheral they are simply a pre-definedcollection of services that have been compiled by either the Bluetooth SIG (adopted GATT basedprofile) 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 UUID are seen on the Bluetooth DeveloperPortal
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
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 30
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
In this assignment the following steps are added to the Host MCU application to set up and handle adevice information service within the ATBTLC1000 module The following steps are added to the startupproject
bull Adding device info service component from ASFbull 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 including init functions that pre-define services in Host memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
1 Click ASF gt ASF Wizard2 Search for ldquoBLE-Device Information Servicesrdquo and then click Add
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 31
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 4-3 Available Modules
3 Now ldquoBLE-Device Information Servicesrdquo (component) appears in ldquoSelected ModulesrdquoFigure 4-4 Selected Modules
4 Click Apply to add the component to the projectFigure 4-5 Adding the Modules to Project
5 The ldquoDevice Information Servicerdquo component is added to the project and is confirmed bydevice_information folder added in Solution Explorer
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 32
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 4-6 Device Information Service Added to Project
42 Configuring and Loading Device Information ServiceThe ATBTLC1000 Host driver provides a set of GATT functions that allows storing and updating theservices in ATBTLC1000 memories
Prototype at_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 Defines a new primary service along with its included services and characteristics inATBTLC1000
Parameters
bull Uuid [In] ndash primary service UUIDbull 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 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 host MCU memory
Parameters ndash
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 33
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
bull device_info_serv [Inout] pointer to device info GATT description handler to beupdated
Return None
Here is a picture of GATT device info service descriptor definition in Host memory
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
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_templatec fileinclude ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
2 Define a device info service handler as global in startup_templatec file Serviceshandlers dis_gatt_service_handler_t dis_service_handler
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 34
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
3 Add dis_init_service and at_ble_primary_service_define functions as called abovethe advertisement start in main routine Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed) Start Advertising process start_advertisement()
4 Click to save the project ltCtrl+Sgt and compile the project by pressing button ltF7gt5 Verify that no build error appears in Atmel Studio output window
Figure 4-7 Atmel Studio Output Window
6 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt7 Open ldquoMicrochip SmartConnectrdquo application on Android or iOS device8 Press ltStart Scangt 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()
9 The Service must now be visible after pairing with peripheral under Microchip SmartConnectapplication
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 35
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 4-8 Service List in Microchip SmartConnect Application
Note If the pairing of ATBTLC1000 with Microchip Smart connect 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 ATBTLC1000device lost the previous pairing information due to RESET since it was stored on temporary storage(RAM)
10 The serial terminal must display the following log output windowFigure 4-9 Console Log Window
ATBTLC1000SettingHandling of Pre-Defined Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 36
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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 So the service initialization needs to be implemented In the context of customizedenvironment service the following service description is pushed in ATBTLC1000 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 The notify mechanism allows thecentral to know when the data changes When notify property of the Client Characteristic ConfigurationDescriptor is enabled by the central and the device writes the new value then this updated value isautomatically sent to the central through a notification The central is not required to send readcharacteristic commands explicitly to the peripheral (GATT server)
To setup and handle the custom environment service in ATBTLC1000 module the following steps areadded to the Host MCU application
bull Configure and load the custom servicebull Update Temperature characteristic and notify to the central devicebull Receive and handle notification from the Host device
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 37
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 5-2 Custom Service Flowchart
51 Configuring and Loading the Custom Environment ServiceThe ATBTLC1000 Host driver provides the following set of GATT functions that allows it to push andupdate the service descriptions in the ATBTLC1000 SRAM memory
Note Before starting this assignment be sure to follow the steps mentioned in 2 Creating the Projectand Initializing and 3 Establishing Connection with Central Device
Prototype ndashat_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 inATBTLC1000 module
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 this array
is update with respective characteristics handlesbull charactristic_count[In] ndash number of elements in charactristic_list
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 38
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Return ndash Execution Status
bull Characteristics ndashndash Characteristics definition is done through specific array of following
ldquoat_ble_characteristic_trdquo structure instancestypedef structat_ble_handle_t char_val_handle Handler (returned during service initialisation)at_ble_uuid_t uuid Characteristic UUID (type and value)at_ble_char_properties_t propertiesCharac Properties (read write notify)uint8_t init_value initial valueuint16_t value_init_len initial value lengthuint16_t value_max_len value max lengthat_ble_attr_permissions_t value_permissions access authorization and authenticationuint8_t user_desc User descriptionuint16_t user_desc_len User description lengthuint16_t user_desc_max_len User description max lengthat_ble_char_presentation_t presentation_format Presentation formatat_ble_attr_permissions_t user_desc_permissions User description permissionat_ble_attr_permissions_t client_config_permissions client permissionat_ble_attr_permissions_t server_config_permissions server permissionat_ble_handle_t user_desc_handle description handlerat_ble_handle_t client_config_handle Client config handlerat_ble_handle_t server_config_handle Server config handler at_ble_characteristic_t
511 Procedure to Configure and Load Custom Environment Service1 Define the following service UUID and characteristic UUID in startup_templatec file
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
2 Define the following environment service handler and characteristics variable as global instartup_templatec 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_templatecvoid custom_environment_service_init(void) at_ble_uuid_t environment_service_uuiduint8_t serv_uuid[] = ENVIRONMENT_SERVICE_UUIDuint8_t charac0_uuid[] = TEMPERATURE_CHAR_UUID Set service UUID environment_service_uuidtype = AT_BLE_UUID_128memcpy(environment_service_uuiduuid serv_uuid16) Define temperature characteristic environment_service_characs[0]user_desc = (uint8_t )Temperatureenvironment_service_characs[0]user_desc_len = 10environment_service_characs[0]user_desc_max_len = 10environment_service_characs[0]uuidtype = AT_BLE_UUID_128memcpy(environment_service_characs[0]uuiduuidcharac0_uuid16)environment_service_characs[0]properties = AT_BLE_CHAR_READ |AT_BLE_CHAR_NOTIFYenvironment_service_characs[0]value_max_len = sizeof(uint8_t) length of temperature valueenvironment_service_characs[0]value_permissions =(AT_BLE_ATTR_READABLE_NO_AUTHN_NO_AUTHR) Push service configuration in ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuidampenvironment_service_handlerNULL0environment_service_characs1)=AT_BLE_SUCCESS)printf(n Assignment 41 Failed to Initialize custom environment service)
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 39
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
elseprintf(n Assignment 41 Initialize custom environment service)
4 Declare and implement the following GATT event callback functioncustom_char_changed_app_event in startup_templatec file If a client (central) enablesnotifications for a server the server (peripheral) receives an AT_BLE_CHARACTERISTIC_CHANGEDevent 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 -gt char_handle) ampamp (char_changed_param_handle-gtchar_new_value[0]))printf(n Assignment 41Characteristic changed event)return AT_BLE_SUCCESS
5 Declare and implement the following custom_notification_confirmation_handlerfunction in startup_templatec 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(n Assignment 41Notification Successfully sent over the air) else printf(n Assignment 41Sending Notification over the air failed)return AT_BLE_SUCCESS
6 Declare the following GATT server callback structure in startup_templatec 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 in startup_templatec toregister GATT server callback for notification confirmation event Register GATT callbacks at BLE manager levelvoid register_gatt_server_callbacks(void) Register GAP Callbacks printf(n 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(nError when Registering ATBTLC1000 callbacks)
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)if SAMG55 || SAM4S Initialize the SAM system sysclk_init()board_init()elif SAM0system_init()
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 40
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
endif Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init()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 ATBTLC1000 Callbacks register_btlc1000_callbacks() Custom service init custom_environment_service_init ( ) Register Gatt server callbacks register_gatt_server_callbacks ( ) Start Advertising process start_advertisement()while(true)ble_event_task()
9 Click to save the project ltCtrl+Sgt
10 Compile the project by pressing button ltF7gt11 Verify that no build error appears in the Atmel Studio output window
Figure 5-3 Atmel Studio Output Window
12 Click to program the project binary on the SAM L21 Xplained Pro ltCtrl+Alt+F5gt13 Open the ldquoMicrochip SmartConnectrdquo application on Android or iOS device14 Connect and pair to the peripheral (pass key 123456)15 Custom service must now be visible after pairing with peripheral under Microchip SmartConnect
application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 41
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 5-4 Service List in Microchip SmartConnect Application
Note Custom service is displayed as unknown service in the above figure as this service is not aSIG-defined service
Figure 5-5 General Information
16 Serial terminal client must display the following Log output
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 42
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 5-6 Log Output Window
52 Updating the Temperature CharacteristicIn the previous assignment the custom Temperature characteristic is defined with a notify attribute Thistype of attribute requires notification to be sent to central when a new characteristic value is availableThe update of any ldquonotifyrdquo characteristic value is based on following interaction between the Host MCUand the ATBTLC1000Figure 5-7 Characteristic Notification
521 Setting a Characteristic Value ( at_ble_characteristic_value_set)Prototype ndashat_ble_status_t at_ble_characteristic_value_setat_ble_handle_t handleuint8_t valueuint16_t len)
Description ndash Sets a characteristic value in ATBTLC1000 memory
Parameters ndash
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 43
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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
523 Sending Temperature Information Once in Every 10 Seconds to Central1 Modify the following ldquotimer_callback_fnrdquo callback function from the startup_templatec
filestatic void timer_callback_fn(void)timer_flag = true
2 hw_timer_init()in main routine of startup_templatec initializes the hardware timer3 If a client (Central) enables the notifications for a server the server (Peripheral) receives an
AT_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 -gt char_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
4 Declare the following Temperature_value global variable in startup_templatec staticuint8_t Temperature_value = 25 as static
5 Add the following send_temperature_notification function in startup_templatec tosend 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++
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 44
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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(fail to send temperature update notification )
6 Add the following code in main routine to send temperature data every 10 secondswhile (1) ble_event_task()if(connected_flag == true ampamp timer_flag == truetimer_flag = falsesend_temperature_notification()
7 Click to save the project ltCtrl+Sgt
8 Compile the project by pressing the button ltF7gt9 Verify that no build error appears in Atmel Studio output window
Figure 5-8 Atmel Studio Output Window
10 Click to program the project binary on the L21 Xplained XSTK11 Open ldquoMicrochip SmartConnectrdquo Application on Android or iOS device12 Connect and pair to the peripheral (pass key 123456)13 Click NOTIFY to start the notification14 Temperature information in HEX values must be displayed in Microchip SmartConnect application
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 45
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Figure 5-9 Notification Window
15 Serial terminal must display the following log outputFigure 5-10 Log Output Window
ATBTLC1000Setting up and Handling Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 46
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
6 Appendix A Software Solution - Pre-Defined SvcThe following is the code implementation for handling of pre-defined service done in 4 SettingHandlingof Pre-Defined Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templatehinclude device_infoh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false Services handlers dis_gatt_service_handler_t dis_service_handler
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(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void) Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks)
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 47
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here
void button_cb(void) Add button callback functionality here
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 ATBTLC1000 Callbacks register_btlc1000_callbacks()
Initialize Device Info service in GATT printf(n 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(Device Information Service definition failed)
Start Advertising process start_advertisement() while(true) ble_event_task()
ATBTLC1000Appendix A Software Solution - Pre-Defined Svc
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 48
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
7 Appendix B Software Solution - Custom ServiceThe following is the code implementation for handling of pre-defined service done in 5 Setting up andHandling Custom Service
- Includes ---------------------------------------------------------------include ltasfhgtinclude platformhinclude at_ble_apihinclude profileshinclude console_serialhinclude timer_hwhinclude conf_extinthinclude ble_managerhinclude ble_utilshinclude conf_serialdrvhinclude startup_templateh
volatile at_ble_status_t ble_statusvolatile bool timer_flag = falsevolatile bool connected_flag = false
static uint8_t adv_data[] = 0x08 AD2 Length = 8 (AD_TYPE + AD) 0x09 AD2 Type = Complete local Name My_SENS AD2 = ldquoMy_SENSrdquo
define ENVIRONMENT_SERVICE_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xc00xba0x5a0xf0
define TEMPERATURE_CHAR_UUID 0x1b0xc50xd50xa50x020x000xa60x870xe50x110x360x390xd80xba0x5a0xf0
Services handlers at_ble_handle_t environment_service_handlerat_ble_characteristic_t environment_service_characs[1]
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 ATBTLC1000 if(at_ble_primary_service_define(ampenvironment_service_uuid ampenvironment_service_handlerNULL0 environment_service_characs1)=AT_BLE_SUCCESS) printf(n Assignment 41 Failed to Initialize custom environment service) else printf(n Assignment 41 Initialize custom environment service)
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(n Assignment 41Notification Successfully sent over the air)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 49
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
else printf(n Assignment 41Sending Notification over the air failed) return AT_BLE_SUCCESS
static 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 -gt char_handle) ampamp (char_changed_param_handle -gt char_new_value[0])) timer_flag = false hw_timer_start(10) printf(n Assignment 41Characteristic changed event) return AT_BLE_SUCCESS
static 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(n 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(nError when Registering ATBTLC1000 callbacks)
void start_advertisement (void) printf(n Assignment 21 Start Advertisement) Set advertisement data ble_status = at_ble_adv_data_set(adv_datasizeof(adv_data) NULL 0) 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(n Failed to start advertisement)
Callback registered for AT_BLE_CONNECTED eventstatic at_ble_status_t ble_connected_cb (void param) printf(n 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(n Assignment 22 Application disconnected ) connected_flag = false start_advertisement() ALL_UNUSED(param)return AT_BLE_SUCCESS
static const ble_gap_event_cb_t app_gap_handle = connected = ble_connected_cb AT_BLE_CONNECTED disconnected = ble_disconnected_cb AT_BLE_DISCONNECTED
Register GAP callbacks at BLE manager levelvoid register_btlc1000_callbacks(void)
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 50
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Register GAP Callbacks printf(n Assignment 22 Register ATBTLC1000 callbacks) ble_status = ble_mgr_events_callback_handler(REGISTER_CALL_BACK BLE_GAP_EVENT_TYPEampapp_gap_handle) if (ble_status = true) printf(nError when Registering ATBTLC1000 callbacks)
timer callback function static void timer_callback_fn(void) Add timer callback functionality here timer_flag = true
void button_cb(void) Add button callback functionality here
static uint8_t Temperature_value = 25
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_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(fail to send temperature update notification )
int main(void) if SAMG55 || SAM4S Initialize the SAM system sysclk_init() board_init() elif SAM0 system_init() endif
Initialize serial console serial_console_init() Hardware timer hw_timer_init() button initialization button_init() 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 Gap ATBTLC1000 Callbacks register_btlc1000_callbacks()
Custom service init custom_environment_service_init()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 51
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
Register Gatt server callback register_gatt_server_callbacks()
Start Advertising process start_advertisement() while(true) ble_event_task() if(connected_flag == true ampamp timer_flag == true) timer_flag = false send_temperature_notification()
ATBTLC1000Appendix B Software Solution - Custom Service
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 52
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
8 Document Revision HistoryRev B - 42018
Section Changes
Document Revised contents to match various Bluetooth Low Energy standard versions
Rev A - 122017
Section Changes
Document Initial release
ATBTLC1000Document Revision History
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 53
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 54
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 55
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
copy 2018 Microchip Technology Incorporated Printed in the USA All Rights Reserved
ISBN 978-1-5224-2921-0
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
ATBTLC1000
copy 2018 Microchip Technology Inc Training Manual DS00002599B-page 56
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 Training Manual DS00002599B-page 57
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 Training Manual DS00002599B-page 57