<<

Application Note RE01B Group Low Energy Sample code (using CMSIS Driver Package) Introduction This application note describes the sample code of the application (hereinafter referred to as BLE application) which controls Bluetooth® Low Energy communication and uses RE01 Group CMSIS Driver Package.

Target Device RE01B Group

Related Documents • Bluetooth Core Specification (https://www.bluetooth.com) • RE01B Group Product with 1.5-Mbyte Flash Memory User’s Manual: Hardware (R01UH0903) • Getting Started Guide to Development Using CMSIS Package (R01AN5310) • e2 studio Getting Started Guide (R20UT4204) • RE01B Group Tuning procedure of Bluetooth dedicated clock frequency (R01AN5488) • Bluetooth Low Energy Profile Developer’s Guide (R01AN5638) • RE01B Group Bluetooth Low Energy Application Developer’s Guide (R01AN5643) • Bluetooth Low Energy MCU Bluetooth Test Tool Suite operating instructions (R01AN4554) • RE01B Group IAR Embedded Workbench for Arm patch Setup Guide (R20AN0596)

The Bluetooth® word mark and logos are registered trademarks owned by Bluetooth SIG, Inc. and any use of such marks by Renesas Electronics Corporation is under license. Other trademarks and registered trademarks are the property of their respective owners.

R01AN5606EJ0220 Rev.2.20 Page 1 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Contents

1. Overview ...... 4 1.1 BLE module ...... 5 1.2 Software Structure ...... 6 1.3 Directory / File structure ...... 7

2. Sample code...... 8 2.1 Operating environment ...... 8 2.2 Startup procedure ...... 9 2.3 Using sample code ...... 9 2.4 Programming ...... 10 2.5 Importing sample code ...... 14 2.5.1 In case of e2 studio ...... 14 2.5.2 In case of EWARM ...... 15 2.6 Building and debugging ...... 16 2.6.1 In case of e2 studio ...... 16 2.6.2 In case of EWARM ...... 16 2.7 GATT Server sample code ...... 17 2.8 GATT Client sample code ...... 21 2.9 A/D converter (ADC) + Bluetooth operation sample code ...... 23 2.10 HCI mode sample code ...... 25

3. BLE module detail ...... 26 3.1 BLE Protocol Stack...... 26 3.1.1 Structure ...... 26 3.1.2 Features overview ...... 29 3.1.3 Operation overview ...... 32 3.2 app_lib (Application Library) ...... 34 3.2.1 Structure ...... 34 3.2.2 Features overview ...... 34 3.3 Configuration options ...... 35 3.4 Abstraction API ...... 40 3.5 Software timer ...... 40 3.6 Profile common ...... 43 3.7 Logger ...... 44 3.8 Command Line ...... 46 3.8.1 Standard command ...... 47 3.8.2 User command creation procedure ...... 67 3.9 LED and Switch control ...... 68 3.9.1 Changing board ...... 68 3.10 MCU low power consumption ...... 69

4. Create project ...... 71 4.1 Import a project ...... 71 4.2 Stack/Heap size configuration ...... 71 4.3 Clocks configuration ...... 72

R01AN5606EJ0220 Rev.2.20 Page 2 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

4.4 Linker configurations ...... 73

5. How to implement user code ...... 76 5.1 Behavior of skeleton program ...... 78 5.2 app_main function ...... 79 5.2.1 Initialize process (ble_init function) ...... 80 5.2.2 Main loop and scheduler (R_BLE_Execute) ...... 83 5.3 GAP event (gap_cb function) ...... 84 5.4 GATTS event (gatts_cb function) ...... 86 5.5 GATTC event (gattc_cb function) ...... 87 5.6 VS event (vs_cb function) ...... 88 5.7 Server-side Profile API event ([service_name]s_cb function) ...... 89 5.8 Client-side Profile API event ([service_name]c_cb function) ...... 90 5.9 L2CAP event ...... 91 5.10 Event notification function (R_BLE_SetEvent) ...... 92 5.11 RF communication timing notification...... 94

6. Optional function ...... 95 6.1 RF communication timing notification...... 95 6.1.1 Connection event notification timing ...... 96 6.1.2 Advertising event notification timing ...... 97 6.1.3 Scan / Initiator event notification timing ...... 97 6.1.4 RF sleep mode event notification timing ...... 98 6.1.5 RF communication timing notification specifications ...... 99 6.2 Device-specific Data Management ...... 100 6.2.1 Specifying Device-specific data location block ...... 100 6.2.2 Device-specific data format ...... 101 6.2.3 Writing to the code flash memory ...... 101 6.2.4 BD address adoption flow ...... 103

7. HCI Mode ...... 104 7.1 Software Structure ...... 104 7.2 Project configuration ...... 105 7.3 UART-HCI Driver ...... 105 7.3.1 UART-HCI Driver configuration ...... 105

8. Tools ...... 106 8.1 CLVALTune ...... 106

9. Appendix ...... 107 9.1 Code Size ...... 107

Revision History ...... 108

General Precautions in the Handling of Microprocessing Unit and Microcontroller Unit Products 110

Notice ...... 111

R01AN5606EJ0220 Rev.2.20 Page 3 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 1. Overview This application note provides the sample code as the example to implement BLE application. BLE application can be created using BLE module. Refer to “2 Sample code” as for the sample code, “1.1 BLE module” and “3 BLE module detail” as for BLE module, and “4 Create project” or later as for how to create BLE application. The package (r01an5606xx0xxx-re01b-ble.zip) attached to this application note consists of the directories and files shown in Table 1.1.

Table 1.1 Package contents

Directory / File Description Documents\ CMSIS driver documents. ROM_Files\ Sample code’s binary files. tools\ CLVALTune\ Operation tool for calibration for HCI mode GATT Client sample code for EB-RE01B board. ble_project_client.zip As for detail, refer to “2.7 GATT Server ”. GATT Server sample code for EB-RE01B board. ble_project_server.zip As for detail, refer to “2.8 GATT Client ”. GATT Client sample code to read ADC automatically for EB-RE01B board. As for ble_project_client_adc.zip detail, refer to “2.9 A/D converter (ADC) + Bluetooth operation ”. GATT Server sample code to read ADC automatically for EB-RE01B board. As for ble_project_server_adc.zip detail, refer to “2.9 A/D converter (ADC) + Bluetooth operation ”. HCI mode sample code for EB-RE01B board. ble_project_uart_hci.zip As for detail, refer to “2.10 HCI mode ”. r_ble_api_spec.chm API document (English). r01an5606ej0xxx-re01b-ble.pdf This document (English / Japanese). r01an5606jj0xxx-re01b-ble.pdf

R01AN5606EJ0220 Rev.2.20 Page 4 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 1.1 BLE module The BLE module is the driver and the middleware implemented in a project and providing the API in the form of a library. Figure 1.1 shows the positioning of the BLE module with red frames.

Figure 1.1 Positioning of BLE module

The BLE module provides the following features which are compliant with Bluetooth Core Specification version 5.0.

Bluetooth 5.0 features: ⚫ LE 2M PHY ⚫ LE Coded PHY ⚫ LE Advertising Extensions ⚫ LE Channel Selection Algorithm #2 ⚫ High Duty Cycle Non-Connectable Advertising

Bluetooth 4.2 features: ⚫ LE Secure Connections ⚫ Link Layer Privacy ⚫ Link Layer Extended Scanner Filter policies ⚫ LE Data Packet Length Extension

Bluetooth 4.1 features: ⚫ LE L2CAP Connection Oriented Channel Support ⚫ Low Duty Cycle Directed Advertising ⚫ 32-bit UUID Support in LE ⚫ LE Link Layer Topology ⚫ LE Ping

R01AN5606EJ0220 Rev.2.20 Page 5 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 1.2 Software Structure Figure 1.2 shows the software structure of this sample code.

e studio2 QE for BLE

Generate

BLE Application

BLE base skeleton program

Abstraction API Profile API

app_lib Profile Common BLE Profile

R_BLE API BLE Protocol Stack

BLE (H/W)

Software provided by QE for BLE

Software provided by BLE Module

Hardware

Figure 1.2 Software structure

The BLE Application controls the BLE functions via the R_BLE API provided by the BLE Protocol Stack. The Abstraction API and Profile Common include auxiliary functions available for the BLE Application. The Abstraction API makes it easy to use the frequently used BLE functions. The QE for BLE generates the source codes (BLE base skeleton program) as a base for the BLE Application and the BLE Profile. Renesas recommends using the QE for BLE for the development of the BLE Application.

R01AN5606EJ0220 Rev.2.20 Page 6 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 1.3 Directory / File structure Table 1.2 shows the directory / file structure of this sample code.

Table 1.2 Directory / File structure Directory /File structure Description

.settings\ com.renesas.apltool.blera e² studio setting save folder CMSIS\ CMSIS config\ RE01B_1500KB_ble.icf Linker configuration file for IAR

abs\ Abstraction API(GAP) board\ Control the LED and SW on the board cli\ Command Line(input/output) cmd\ Command Line(command) app_lib\ discovery\ Profile common(discovery function) logger\ Logger BLE\ profile_cmn\ Profile common sec_data\ Security data management Device\ timer\ Software timer platform\ Driver for function

BLE Protocol Stack Library rble_lib\ (GCC ARM/EWARM)

CMSIS_Driver\ CMSIS driver Config\ r_ble_cfg.h Configuration option file BLE interface file Driver\ Include\ r_ble_api.h All API calls and their supporting interface definition app_main.c BLE application main code gatt_db.c GATT Database qe_gen\ ble\ gatt_db.h GATT Database r_ble_xxx.c Profile code r_ble_xxx.h Profile header script\ RE01B_1500KB_ble.ld Linker script file for GCC settings\ IAR setting save folder main.c Project main code src\ r_ble_[arbitrary].c Other BLE application code r_ble_[arbitrary].h Other BLE application header SVD\ RE01B_1500KB.svd Register information of peripheral function .cproject .project Project file for GCC ble_project_xxx HardwareDebug.launch ble_project_xxx.ewd ble_project_xxx.ewp Project file for IAR ble_project_xxx.eww

R01AN5606EJ0220 Rev.2.20 Page 7 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2. Sample code 2.1 Operating environment Table 2.1 shows the hardware requirements for using this sample code.

Table 2.1 Hardware requirements Hardware Description Host PC Windows® 10 PC with USB interface. MCU Board EB-RE01B board https://www.tessera.co.jp/eng/products/eb-re01b.html On- debugging GCC environment: Either of the following emulator. emulators E2 emulator [RTE0T00020KCE00000R] E2 emulator Lite [RTE0T0002LKCE00000R] J-Link IAR environment: Either of the following emulator. I-jet® J-Link USB cables Used to connect to the MCU board. 1 USB A-microB cable

Table 2.2 shows the software requirements for using this sample code.

Table 2.2 Software requirements Software Version Description GCC e² studio v21.1.0 or Integrated development environment (IDE) for Renesas environment later devices. GCC ARM Embedded v6.3.1 or C/C++ Compiler. (download from e2 studio installer) later CMSIS Driver v1.0.0 or Software package for developing applications for the RE Package later microcontroller series. QE for BLE[RA,RE] v1.2.0 or Generates the source codes (BLE base skeleton program) as later a base for the BLE Application and the BLE Profile. IAR IAR Embedded v8.50.5 or Integrated development environment (IDE) for ARM devices environment Workbench for ARM later made by IAR Systems. (EWARM) Note: RE01B device file patch setup is required for v8.50.5 and v9.10.1 environment. For the setup procedure, refer to "RE01B Group IAR Embedded Workbench for Arm patch Setup Guide (R20AN0596)". IAR C/C++ Compiler v8.50.5 or C/C++ Compiler made by IAR Systems. for ARM later CMSIS Driver v1.0.0 or Software package for developing applications for the RE Package later microcontroller series. QE for BLE[RA,RE] - Use by overwriting the code that QE for BLE in e2 studio generates to IAR project. Renesas Flash Programmer v3.06.01 or Tool for programming the on-chip flash memory of Renesas later microcontrollers. Integer types It uses ISO C99 “Exact width integer types”. These types are defined in stdint.h. Endian Little endian

R01AN5606EJ0220 Rev.2.20 Page 8 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.2 Startup procedure EB-RE01B board supports USB power supply. Confirm that the board switches are as Table 2.3 and connect USB connector CN4 to the USB port of your PC (or other power supply) with a USB cable.

Table 2.3 Board switch settings Board switch Setting JP1 Short (ON) JP2 Short (ON) JP3 Short (ON) JP4 / JP5 2-3(Regulator Out) / 1-2(USB) JP7 / JP8 / JP9 1-2 (Normal mode) / 1-2 (Normal mode) / 1-2 (Normal mode) JP10 / JP11 2-3 (UART) / 2-3 (UART) JP12 Open (OFF) JP13 Short (ON) SW3 1-2 (S_Chip) SW4 1-2 (Normal)

After turning on the power, confirm that LED1 lights. If it does not light, check that that the board switches are as Table 2.3.

2.3 Using sample code In case of programming and using the sample code’s binary file, refer to “2.4 Programming firmware”. In case of building and using the sample code, refer to “2.5 Importing sample code” and “2.6 Building and debugging”.

R01AN5606EJ0220 Rev.2.20 Page 9 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.4 Programming firmware Use the Renesas Flash Programmer (Hereafter referred to as RFP) to program the firmware to this product. Note: Use RFP v3.06.01 or later.

1. Change the board switches as Table 2.4 and connect your PC and CN4 connector with an A – micro B type USB cable.

Table 2.4 Board switch settings for using RFP

Board switch Setting JP1 Short (ON) JP2 Short (ON) JP3 Short (ON) JP4 / JP5 2-3(Regulator Out) / 1-2(USB) JP7 / JP8 / JP9 1-2 (Normal mode) / 1-2 (Normal mode) / 1-2 (Normal mode) JP10 / JP11 1-2 (RFP) / 1-2 (RFP) JP12 Open (OFF) JP13 Short (ON) SW3 1-3 (Boot) SW4 1-2 (Normal)

2. Start RFP and select “File” → “New Project…”.

Figure 2.1 Creating New Project

R01AN5606EJ0220 Rev.2.20 Page 10 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

3. In the “Create New Project” window, make the following settings and click the “Connect” button. • Microcontroller: RE • Project Name: Any name • Project Folder: Any folder • Communication Tool: COM port

Figure 2.2 Project Setting

4. If the connection is successful, “Operation completed.” is displayed.

Figure 2.3 Successful Connection

R01AN5606EJ0220 Rev.2.20 Page 11 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

5. Click the “Browse…” button, select hex file in the ROM_Files folder, and click the “Open” button.

Figure 2.4 Selecting File

6. Click the “Start” button on the “Operation” tab to start programming the firmware.

Figure 2.5 Programming Firmware

R01AN5606EJ0220 Rev.2.20 Page 12 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

7. When programming is completed normally, “Operation completed.” And “OK” are displayed.

Figure 2.6 Programming Completion

8. After programming is complete, disconnect the USB cable that connected this product to your PC.

R01AN5606EJ0220 Rev.2.20 Page 13 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.5 Importing sample code How to import a sample code is below. Refer to “e2 studio Getting Started Guide (R20UT4204)” for installing e2 studio.

2.5.1 In case of e2 studio (1) Select “File” → ”Import”.

Figure 2.7 File menu

(2) Select “Existing Projects into Workspace” and click “Next” button.

Figure 2.8 Select an import wizard

R01AN5606EJ0220 Rev.2.20 Page 14 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(3) Select “Select archive file”, click “Browse…” button and select the sample code archive file. Click “Finish” button and the sample code project is imported.

Figure 2.9 Import Projects

2.5.2 In case of EWARM Click [Project]→[Add Existing Project…] and select the project file (.ewp).

R01AN5606EJ0220 Rev.2.20 Page 15 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.6 Building and debugging 2.6.1 In case of e2 studio Refer to “e2 studio Getting Started Guide (R20UT4204)”. Note: J-Link is set for the sample code debugger. When using E2 Lite, set the following. [Run]→[Debug Configurations]→[Renesas GDB Hardware Debugging]→[Debugger]→[Debug hardware]: E2 Lite (ARM)

2.6.2 In case of EWARM Refer to [Help]→[IDE and Building Guide] and [C-SPY Debugging Guide] on EWARM. Note: J-Link is set for the sample code debugger. When using I-jet, set the following. [Project]→[Options]→[Debugger]→[Setup]→[Driver]: I-jet [Project]→[Options]→[Debugger]→[Download]→[Use flash loader]: ON

R01AN5606EJ0220 Rev.2.20 Page 16 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.7 GATT Server sample code EB-RE01B board programmed the GATT Server sample works as below. Note: A is used as the example of remote device. Prepare a smartphone with the OS shown in Table 2.5 and the smartphone app “GATTBrowser” made by Renesas Electronics.

Table 2.5 Supported OS OS Version iOS 9.0 or later Android 5.0.1 or later

GATTBrowser

iOS version:

https://apps.apple.com/app/gattbrowser/id1163057977 Android version:

https://play.google.com/store/apps/details?id=com.renesas.ble.gattbrowser

⚫ GATT Server sample starts advertising after startup. ⚫ By scanning from a remote device, GATT Server sample is detected by the “RBLE-DEV” device name.

Figure 2.10 Scan result example

R01AN5606EJ0220 Rev.2.20 Page 17 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

⚫ When connected, GATT Server sample stops advertising. ⚫ The followings are discovered by searching GATT services from a remote device (service discovery). ➢ LED Switch Service(LSS, UUID : 58831926-5F05-4267-AB01-B4968E8EFCE0) ➢ Switch State Characteristic(UUID : 58837F57-5F05-4267-AB01-B4968E8EFCE0) ➢ LED Blink Rate Characteristic(UUID : 5883C32F-5F05-4267-AB01-B4968E8EFCE0)

Figure 2.11 GATT Services

GATT Server sample provides the following standard service and custom service.

Table 2.6 GATT Server sample’s service Service Property Size Description (byte) GAP service Standard service GATT service Standard service LED Switch service Custom service →Switch State characteristic Notify 1 Send 1 as Notification when switch is pushed. →Client Characteristic Configuration descriptor Read / Write 2 Enable / Disable Notification →LED Blink Rate characteristic Read / Write 1 Read / Write LED blinking cycle.

R01AN5606EJ0220 Rev.2.20 Page 18 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

⚫ If the LED Switch Service second parameter in the gs_gatt_service variable in the gatt_db.c is set to BLE_GATT_DB_SER_SECURITY_UNAUTH | BLE_GATT_DB_SER_SECURITY_ENC, the GATT Server requests pairing to access to the Characteristic in the LED Switch Service. If 0 is set, pairing is not necessary.

static const st_ble_gatts_db_serv_cfg_t gs_gatt_service[] = {

...

/* LED Switch */ { /* Num of Services */ { 1, }, Pairing is necessary. /* Description */ BLE_GATT_DB_SER_SECURITY_UNAUTH | BLE_GATT_DB_SER_SECURITY_ENC, /* Service Start Handle */ 0x0010, /* Service End Handle */ 0x0015, /* Characteristic Start Index */ 6, /* Characteristic End Index */ 7, },

};

static const st_ble_gatts_db_serv_cfg_t gs_gatt_service[] = {

...

/* LED Switch */ { /* Num of Services */ { 1, }, Pairing is not necessary. /* Description */ 0, /* Service Start Handle */ 0x0010, /* Service End Handle */ 0x0015, /* Characteristic Start Index */ 6, /* Characteristic End Index */ 7, },

};

Figure 2.12 The security setting of the access to the LED Switch Service.

R01AN5606EJ0220 Rev.2.20 Page 19 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Figure 2.13 shows usage example for the GATT Server sample and a remote device.

Figure 2.13 Usage example for the GATT Server sample and a remote device

⚫ After enabling the notification in the Switch State characteristic from a remote device, the notification packet is sent to the remote device by pushing the SW2 on the board. ⚫ By writing a number to the LED Blink Rate characteristic from a remote device, the LED blinks depend on written number. The LED turns off by writing zero to the characteristic. ⚫ When disconnected, GATT Server sample restarts advertising.

R01AN5606EJ0220 Rev.2.20 Page 20 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.8 GATT Client sample code The GATT Client sample works as below.

⚫ After starting, it waits for a command. ⚫ If you would like to confirm the presence of the GATT Server sample, execute the “gap scan” command by your terminal software and the advertising packet are received. Refer to “3.8.1.1(2) Scan command” for the details of the “gap scan” command. After receiving the advertising, stop scan by press CTRL + C on the terminal software. ⚫ Execute the “gap conn” command by the terminal software to connect with the GATT Server sample. Refer to “3.8.1.1(3) Connection command” for the details of the “gap conn” command. ⚫ When connected, packet data length exchange is done. ⚫ When the packet data length changed, it sends the MTU exchange request. ⚫ Receiving the MTU exchange response, it starts searching GATT services in the remote device. ⚫ If the GATT Server sample project is set to request pairing (BLE_GATT_DB_SER_SECURITY_UNAUTH | BLE_GATT_DB_SER_SECURITY_ENC : Figure 2.12), pairing needs to be done previous to the LED Switch client command execution. Input the “gap auth” command to start pairing. Refer to “3.8.1.1(9) Authentication command” for the details of the “gap auth” command. ⚫ After the completion of the above procedure, it allows to use the following LED Switch client commands.

➢ Enable / Disable Notification lsc set_switch_state_ntf [connection handle] [0(disabled) or 1(enabled)]

➢ Write the LED blink rate lsc write_led_blink_rate [connection handle] [blink_rate] The LED blinks at the [blink_rate ] x 100ms. Valid range is 0-255. The LED turns off by writing 0.

⚫ Execute the “gap disconn” command by the terminal software to disconnect the GATT Server sample. Refer to “3.8.1.1(4) Disconnection command” for the details of the “gap disconn” command.

R01AN5606EJ0220 Rev.2.20 Page 21 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Figure 2.14 shows usage example for the GATT Client sample and the GATT Server sample.

Figure 2.14 Usage example for the GATT Client sample and the GATT Server sample

R01AN5606EJ0220 Rev.2.20 Page 22 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.9 A/D converter (ADC) + Bluetooth operation sample code The GATT Server ADC sample and the GATT Client ADC sample work as below.

⚫ After starting, GATT Server ADC sample starts advertising. GATT Client ADC sample waits for a command. ⚫ Operations of “gap scan” command, “gap conn” command, “gap auth” command and “gap disconn” command are the same with GATT Client sample. ⚫ The followings are discovered by searching GATT services from a remote device (service discovery). ➢ Auto Read ADC Service(ARAS, UUID : 0x7777) ➢ ADC Data Characteristic(UUID : 0x7778) ➢ ADC reserved Characteristic(UUID : 0x7779)

Note: This sample project uses a 16-bit UUID for ease of debugging, but beware that custom services must use a 128-bit UUID according to the standard. ⚫ After the completion of the above procedure, it allows to use the following Auto Read ADC client commands.

➢ Enable / Disable Notification arac set_adc_data_ntf [connection handle] [0(disabled) or 1(enabled)]

⚫ GATT Server ADC sample sends A/D data Notification at the interval of A/D convert Interval (default:10ms) * Trans Count (default:10times) = 100msec.

ADC sample uses the following MCU resources.

Table 2.7 MCU resources used by ADC sample

Resource Port Description AGT0 - Used as a timer for the A/D convert read trigger. S14AD P000 Used to capture sensor data. DMAC0 - Used for automatic read of A/D convert results. I/O P704 Used for AMP control.

GATT Server ADC sample provides the following standard service and custom service.

Table 2.8 GATT Server ADC sample’s service Service Property Size Description (byte) GAP service Standard service. GATT service Standard service. LED Switch service Custom service. →ADC Data characteristic Notify / Read / 31 Send A/D data as Notification / Write Read / Write. →Client Characteristic Configuration descriptor Read / Write 2 Enable / Disable Notification / Read / Write. →ADC reserved characteristic Read / Write 1 Read / Write reserved area.

R01AN5606EJ0220 Rev.2.20 Page 23 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Figure 2.15 shows usage example for the GATT Client ADC sample and the GATT Server ADC sample.

[BD Address] D0:12:34:56:78:9A GATT Server ADC GATT Client ADC Terminal emulator

[Address Type] opt [Confirm whether the GATT Server is running.] Random Address gap scan Start advertising Start scanning GATT Client action Start scanning Advertising Packet GATT Server action D0:12:34:56:78:9A rnd ff 0000 After detecting the GATT Server, stop scanning. Press CTRL + C BLE Event

Stop scanning Input from Terminal emulator receive BLE_GAP_EVENT_SCAN_OFF result : 0x0000

Output to Terminal emulator Request for connection gap conn D0:12:34:56:78:9A rnd Connect to the GATT Server. Connection complete receive BLE_GAP_EVENT_CONN_IND result : 0x0000 (BLE_GAP_EVENT_CONN_IND) gap: connected conn_hdl:0x0020, addr:D0:12:34:56:78:9A rnd [Connection Handle] 0x0020 Packet data length exchange complete receive BLE_GAP_EVENT_DATA_LEN_CHG (BLE_GAP_EVENT_DATA_LEN_CHG) result : 0x0000, conn_hdl : 0x0020

MTU exchange request R_BLE_GATTC_ReqExMtu() MTU exchange complete (BLE_GATTC_EVENT_EX_MTU_RSP)

Search GATT service R_BLE_DISC_Start()

GATT service search complete disc finished

opt Start pairing gap auth start 0x0020 Start pairing [GATT Server requests pairing to access to the Auto Read ADC service.] receive BLE_GAP_EVENT_ENC_CHG result : 0x0000 receive BLE_GAP_EVENT_PEER_KEY_INFO Pairing complete LTK : 00112233445566778899aabbccddeeff receive BLE_GAP_EVENT_PAIRING_COMP result : 0x0000 (BLE_GAP_EVENT_PAIRING_COMP) sec : 0x01, mode : 0x02, bond : 0x01, key_size : 0x10

Enable Notification arac set_adc_data_ntf 0x0020 1 Enable Notification with arac command.

Notification arac: Receive ADC data Ntf.

Notification arac: Receive ADC data Ntf.

Notification arac: Receive ADC data Ntf.

Notification arac: Receive ADC data Ntf.

Notification arac: Receive ADC data Ntf.

Notification arac: Receive ADC data Ntf.

Request for disconnection gap disconn 0x0020 Disconnect to the GATT Server.

receive BLE_GAP_EVENT_DISCONN_IND result : 0x0000 Disconnection complete gap: disconnected conn_hdl:0x0020, addr:D0:12:34:56:78:9A rnd, (BLE_GAP_EVENT_DISCONN_IND) reason:0x16

Restart advertising

Figure 2.15 Usage example for the GATT Client ADC sample and the GATT Server ADC sample

R01AN5606EJ0220 Rev.2.20 Page 24 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 2.10 HCI mode sample code The HCI mode sample waits for an HCI command after starting. Input an HCI command for the RF characteristic evaluation or connect to BTTS (Bluetooth Test Tool Suite: R01AN4554).

R01AN5606EJ0220 Rev.2.20 Page 25 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3. BLE module detail The BLE module includes the BLE Protocol Stack, which provides Bluetooth Low Energy communication functions, and the app_lib (application library), which provides auxiliary functions available to BLE applications.

3.1 BLE Protocol Stack 3.1.1 Structure Figure 3.1 shows the configuration of the BLE Protocol Stack.

BLE Application Layer

BLE Protocol Stack

R_BLE API

Vendor Specific GAP GATT Client L2CAP MCU Low Power Consumption

GATT Server Common GATT Common

Host Stack Scheduler

GAP GATT

Vendor Specific SMP ATT

L2CAP

HCI

Link Layer

HCI

Vendor Specific

BLE (H/W)

Figure 3.1 BLE Protocol Stack structure

BLE Protocol Stack consists of R_BLE API, Host Stack, Link Layer, and Scheduler.

R01AN5606EJ0220 Rev.2.20 Page 26 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

• R_BLE API The R_BLE API provides the shown in Table 3.1 to provide BLE functions for BLE applications. Refer to “API document (r_ble_api_spec.chm)” for detailed specifications of each API.

Table 3.1. R_BLE API overview R_BLE_API Protocol/Profile Description API for control BLE Open / Close and scheduler processing. Main features Common API ⎯ • Open/Close the BLE protocol stack. • Execute the BLE task. • Add an event in the BLE protocol stack internal queue. API for supports procedures defined in GAP and SMP. Main features GAP • GAP GAP API SMP Advertising, Scan, Connection, Security • SMP Pairing API for GATT Server that publishes service-related attributes and data sets (GATT Database). ATT GATT Server API Main features GATT • Access to GATT Database • Notification / Indication API for GATT Client that makes requests to GATT Server. ATT Main features GATT Client API GATT • Service/Characteristic Discovery • Characteristic Read/Write ATT API for functions used in common with GATT Server/Client. GATT Common API GATT API for data transfer on channels that perform credit-based flow L2CAP API L2CAP control. API that provides Renesas original extended features. Main features Vendor Specific API ⎯ • Enhanced Direct Test Mode • Set/Get BD Address MCU Low Power API for reducing MCU power consumption. ⎯ Consumption API

The supported API differs depending on the type of BLE Protocol Stack. See Table 3.3 for the APIs supported by each library.

R01AN5606EJ0220 Rev.2.20 Page 27 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

• Host Stack Host Stack provides the protocol and profile functions specified by Bluetooth SIG. The data received from the R_BLE API is sent to the Link Layer according to the procedures specified in each protocol and profile, and the data received from the Link Layer is notified as an R_BLE API event or data.

• Link Layer The Link Layer controls the BLE hardware implemented in the MCU and provides BLE functions such as Advertising, Scan, Connection, and to the Host Stack via HCI (Host Controller Interface). BLE commands and transmission data are sent from Host Stack to Link Layer. BLE command results and data received from remote devices are sent from Link Layer to Host Stack.

• Scheduler Scheduler processes the task according to the message queue sent to the task of each layer of BLE Protocol Stack by R_BLE_Execute() of Common API. Figure 3.2 shows the basic sequence chart of BLE Protocol Stack.

Source Code Library Software Hardware BLE Protcol Stack

Application R_BLE API Scheduler Host Stack Link Layer(LL) BLE H/W

Call R_BLE API Send Message to Host Stack

return R_BLE API Function Call return Call R_BLE_Execute() Execute Task Send Message Send Message to LL Access BLE H/W return

BLE Interrupt Execute Task Access BLE H/W Send Message to Host Stack return

Execute Task

callback R_BLE event callback

return return return

return R_BLE_Execute()

BLE Interrupt Send Message to LL Call R_BLE_Execute() Execute Task Access BLE H/W Send Message to Host Stack

return

Execute Task

callback R_BLE event callback

return return return

return R_BLE_Execute()

Figure 3.2. Basic sequence chart of BLE Protocol Stack

R01AN5606EJ0220 Rev.2.20 Page 28 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.1.2 Features overview The features of the BLE Protocol Stack depends on the BLE_CFG_LIB_TYPE option in Configuration options. Table 3.2 shows the features of each type of the BLE Protocol Stack.

Table 3.2 Features of the BLE Protocol Stack

Type of BLE Protocol Stack BLE Feature All features Balance Compact

LE 2M PHY Yes Yes No

LE Coded PHY Yes Yes No

LE Advertising Extensions Yes No No

LE Channel Selection Algorithm #2 Yes Yes No

High Duty Cycle Non-Connectable Yes Yes Yes Advertising

LE Secure Connections Yes Yes Yes

Link Layer privacy Yes Yes Yes

Link Layer Extended Scanner Filter Yes Yes No policies

LE Data Packet Length Extension Yes Yes Yes

LE L2CAP Connection Oriented Channel Yes No No Support

Low Duty Cycle Directed Advertising Yes Yes Yes

LE Link Layer Topology Yes Yes No

LE Ping Yes Yes Yes

Central Central Peripheral Peripheral Peripheral GAP Role Observer Observer Broadcaster Broadcaster Broadcaster Sever Sever Sever GATT Role Client Client Client

32-bit UUID Support in LE Yes Yes Yes

R01AN5606EJ0220 Rev.2.20 Page 29 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

• LE 2M PHY Supports BLE communication with 2Msym/s PHY.

• LE Coded PHY Supports BLE communication with Coded PHY. Communication over a long range than 1M PHY and 2M PHY is possible.

• LE Advertising Extensions An extension of Advertising. The features of this function are as follows. ⎯ Up to 4 independent advertising can be executed simultaneously. (Use the configuration option BLE_CFG_RF_ADV_SET_MAX to set the number of Advertising executed simultaneously.) ⎯ Expansion of Advertising Data / Scan Response Data size up to 1650 bytes. (Set the maximum size (bytes) with the configuration option BLE_CFG_RF_ADV_DATA_MAX.) ⎯ Periodic Advertising is possible.

• LE Channel Selection Algorithm # 2 This function selects a channel using the algorithm for selecting a hopping channel added in Version 5.0.

• High Duty Cycle Non-Connectable Advertising This function supports non-connectable advertising with a minimum interval of 20 msec.

• LE Secure Connections Elliptic curve Diffie-Hellman key agreement method (ECDH) supports passive eavesdropping pairing.

• Link Layer privacy This function avoids tracking from other BLE devices by changing the BD Address periodically.

• LE Data Packet Length Extension This function expands the BLE data communication packet size. It can be expanded to 251 bytes. (Set the maximum size (bytes) with the configuration option BLE_CFG_RF_CONN_DATA_MAX.)

• LE L2CAP Connection Oriented Channel Support This function supports communication using the L2CAP credit based flow control channel.

• Low Duty Cycle Directed Advertising This function supports low duty cycle advertising for reconnection with known devices.

• LE Link Layer Topology This function supports both Master and Slave roles and can operate as Master when connected to a remote device and as Slave when connected to another remote device.

R01AN5606EJ0220 Rev.2.20 Page 30 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

• LE Ping After connection encryption, this feature checks whether connection is maintained by a packet transmission request including MIC field.

• GAP Role GAP Role supports the following. ⎯ Central: A device that sends a connection request to a peripheral device. ⎯ Peripheral: A device that accepts connection requests from Central and establishes a connection. ⎯ Observer: A device that scans Advertising. ⎯ Broadcaster: A device that sends Advertising.

• GATT Role GATT Role supports the following. ⎯ Server: A device that prepares Characteristic provided by service in GATT Database and responds to requests from Client. ⎯ Client: A device that makes request for services provided by Server.

• 32-bit UUID Support in LE Supports GATT 32-bit UUID.

Table 3.3 shows R_BLE API support for each type of BLE Protocol Stack.

Table 3.3 R_BLE API support for BLE Protocol Stack

Type of BLE Protocol Stack R_BLE_API All features Balance Compact Common API Yes Yes Yes GAP API Yes C.1 C.1 GATT Common API Yes Yes Yes GATT Server API Yes Yes Yes GATT Client API Yes Yes Yes L2CAP API Yes No No Vendor Specific API Yes Yes Yes MCU Low Power Consumption API Yes Yes Yes C.1: Support for each GAP API varies depending on the type of BLE Protocol Stack. Refer to “API Document (r_ble_api_spec.chm)” for details.

R01AN5606EJ0220 Rev.2.20 Page 31 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.1.3 Operation overview The BLE protocol stack controls the BLE peripheral functions and manages the execution of RF events. RF event refers to one communication operation at each interval in the following four operation states specified by Bluetooth LE. ⚫ Advertising ⚫ Scanning ⚫ Initiating ⚫ Connection

The BLE protocol stack provides the control interface for Bluetooth LE operation as R_BLE API. The BLE peripheral functions generate an interrupt (BLEIRQ) corresponding to an RF event to the MCU. When BLEIRQ occurs, it is necessary to call R_BLE_Execute and perform task processing according to the RF event status. Also, when various R_BLE APIs are called, it is necessary to call R_BLE_Execute to perform API task processing of the BLE protocol stack.

When BLE_CFG_RF_DEEP_SLEEP_EN is set to 1 in “3.3 Configuration options”, when there is no task to be executed by the BLE protocol stack, and when there is a time of 40ms or more before the start of the next RF event time, transition to RF sleep mode to reduce the current consumption of the RF part. This time does not mean the "interval time" of an RF event, but the "RF idle time" between the completion of one RF event and the start of the next RF event. Therefore, it is necessary to set the RF event interval to 60ms or more in consideration of the processing time of each layer in order to shift the RF part to sleep mode. In Scanning operation, the time difference between the Scan interval and Scan window must also be set to 60ms or more. The BLE protocol stack performs RF sleep processing and RF wake-up processing to transition the RF part to sleep mode. Figure 3.3 shows MCU/RF operation overview with RF sleep.

MCU IDLE Application processing possible.

R_BLE_Execute Required processing by call R_BLE_Execute.

RF event interval

RF idle time

RF sleep time MCU

R_BLE_Execute R_BLE_Execute R_BLE_Execute R_BLE_Execute MCU MCU Event callback, MCU MCU Event callback, MCU RF Wakeup RF Wakeup IDLE IDLE RF Sleep IDLE IDLE RF Sleep IDLE Processing Processing Processing Processing

BLEIRQ BLEIRQ BLEIRQ BLEIRQ (RF Wakeup) (RF event) (RF Wakeup) (RF event)

RF

RF RF Wakeup RF RF Wakeup RF RF RF RF RF RF RF RF RF Event Event SLEEP IDLE IDLE SLEEP IDLE IDLE SLEEP

(Tx/Rx) (Tx/Rx)

Figure 3.3. MCU/RF operation overview with RF sleep

R01AN5606EJ0220 Rev.2.20 Page 32 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

While the MCU is idle, it is possible to transition the MCU to the low power consumption mode or execute application processing. However, if the RF wakeup process by R_BLE_Execute is not performed before the RF event starts, the RF event cannot be executed. Therefore, application processing must be implemented so as not to interfere with the R_BLE_Execute call. When BLE_CFG_RF_DEEP_SLEEP_EN is set to 0 in “3.3 Configuration options”, or when BLE_CFG_RF_DEEP_SLEEP_EN is set to 1 but the RF sleep transition condition is not satisfied, the BLE protocol stack dose not transition RF part to sleep mode. In this case, the current consumption during RF idle time increases, but the MCU idle time that can be used by the application increases because RF sleep processing and RF wakeup processing are not performed. Figure 3.4 shows MCU/RF operation without RF sleep.

MCU IDLE Application processing possible.

R_BLE_Execute Required processing by call R_BLE_Execute.

RF event interval

RF idle time

MCU

MCU R_BLE_Execute MCU R_BLE_Execute MCU IDLE Event callback IDLE Event callback IDLE

BLEIRQ BLEIRQ (RF event) (RF event) RF

RF RF RF RF RF Event Event IDLE IDLE IDLE (Tx/Rx) (Tx/Rx)

Figure 3.4. MCU/RF operation overview without RF sleep

Regardless of the RF sleep state, if the application process continuously occupies the MCU and R_BLE_Execute is not called, the connection may not be maintained. Therefore, it is recommended that the application processing is short time. For processing that takes a long time, refer to "5.10 Event notification function (R_BLE_SetEvent)" and execute the processing by dividing it into multiple times.

R01AN5606EJ0220 Rev.2.20 Page 33 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.2 app_lib (Application Library) 3.2.1 Structure Figure 3.5 shows the structure of app_lib.

app_lib

Profile Common Part Abstraction API (profile_cmn)

Software Timer Logger

Command Line Interface LED and Switch Control

Figure 3.5 app_lib structure

3.2.2 Features overview Refer to the section below for the features provided by app_lib.

• 3.4 Abstraction API • 3.5 Software timer • 3.6 Profile common • 3.7 Logger • 3.8 Command Line • 3.9 LED and Switch control

R01AN5606EJ0220 Rev.2.20 Page 34 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.3 Configuration options The configuration options of the BLE module can be configured in r_ble_cfg.h. The option names and setting values are listed in the table shown as follows.

Table 3.4 Configuration options Configuration options (r_ble_cfg.h) BLE_CFG_LIB_TYPE Type of the BLE Protocol Stack. Select one of the followings. Default : "1" 0: All features 1: Balance 2: Compact

Refer to Table 3.2 for details. BLE_CFG_RF_DBG_PUB_ADDR Initial Public Address. If the public addresses in the Code Default : "{0xFF,0xFF,0xFF,0x50,0x90,0x74}" Flash Memory are all 0x00 or 0xFF, the device adopts this public address. If all 0x00 or 0xFF is set, the device uses 74:90:50:FF:FF:FF as public address. Refer to "6.2 Device-specific Data Management" for details. BLE_CFG_RF_DBG_RAND_ADDR Initial Random Address. If the static addresses in the Code Default : “{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}" Flash Memory are all 0x00 or 0xFF, the device adopts this random address. If all 0x00 or 0xFF is set, the device uses the value generated with the MCU specific value the static address. Refer to "6.2 Device-specific Data Management" for details. BLE_CFG_RF_CONN_MAX Maximum number of simultaneous connections. Default : "2" Range : 1 to 7 BLE_CFG_RF_CONN_DATA_MAX Maximum packet data length (bytes). Default : "251" Range : 27 to 251 BLE_CFG_RF_ADV_DATA_MAX Maximum advertising data length (bytes). Default : "252" Range : 31 to 1650

The maximum advertising data length of the BLE Protocol Stack libraries other than "All features" is fixed to 31 [bytes]. BLE_CFG_RF_ADV_SET_MAX Maximum number of the advertising set. Default : "1" Range : 1 to 4

The number of the advertising set of the BLE Protocol Stack libraries other than "All features" is fixed to 1 [set]. BLE_CFG_RF_SYNC_SET_MAX Maximum number of periodic sync set. Default : "1" Range : 1 to 2

If the BLE Protocol Stack library is other than "All features", this option is not used. BLE_CFG_EVENT_NOTIFY_CONN_START Enable or disable start interrupt notification of a connection Default : "0" complete event.

0: Disable 1: Enable

Because the start notification is triggered by the interrupt, it occurs after the actual RF event. BLE_CFG_EVENT_NOTIFY_CONN_CLOSE Enable or disable end interrupt notification of a connection Default : "0" complete event.

0: Disable 1: Enable

R01AN5606EJ0220 Rev.2.20 Page 35 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Configuration options (r_ble_cfg.h) BLE_CFG_EVENT_NOTIFY_ADV_START Enable or disable the advertising event start interrupt Default : "0" notification.

0: Disable 1: Enable

The notification occurs at the following timings. - Start Primary Advertising channel. - Start Secondary Advertising Channel - Start Periodic Advertising. ( When the Extended Advertising is enabled.)

Because the start notification is triggered by the interrupt, it occurs after the actual RF event.

BLE_CFG_EVENT_NOTIFY_ADV_CLOSE Enable or disable the advertising event complete interrupt Default : "0" notification.

0: Disable 1: Enable

The notification occurs at the following timings. - Complete Primary Advertising channel. - Complete Secondary Advertising Channel - Complete Periodic Advertising. ( When the Extended Advertising is enabled.)

Because the start notification is triggered by the interrupt, it occurs after the actual RF event. If the advertising is terminated by a command, the notification doesn't occur. BLE_CFG_EVENT_NOTIFY_SCAN_START Enable or disable the scan start interrupt notification. Default : "0" 0: Disable 1: Enable

If the scan interval is equal to the scan window, this notification doesn't occur. Because the start notification is triggered by the interrupt, it occurs after the actual RF event.

BLE_CFG_EVENT_NOTIFY_SCAN_CLOSE Enable or disable the scan complete interrupt notification Default : "0" 0: Disable 1: Enable

If the scan interval is equal to the scan window, this notification doesn't occur. If the scan is terminated by a command, the notification doesn't occur. BLE_CFG_EVENT_NOTIFY_INIT_START Enable or disable the notification that the scan start interrupt Default : "0" has occurred in sending a connection request.

0: Disable 1: Enable

If the scan interval is equal to the scan window, this notification doesn't occur. Because the start notification is triggered by the interrupt, it occurs after the actual RF event.

R01AN5606EJ0220 Rev.2.20 Page 36 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Configuration options (r_ble_cfg.h) BLE_CFG_EVENT_NOTIFY_INIT_CLOSE Enable or disable the notification that the scan complete Default : "0" interrupt has occurred in sending a connection request.

0: Disable 1: Enable

If the scan interval is equal to the scan window, this notification doesn't occur. If the connection request is terminated by a command, the notification doesn't occur.

BLE_CFG_EVENT_NOTIFY_DS_START Enable or disable the RF_DEEP_SLEEP start notification. Default : "0"

0: Disable 1: Enable BLE_CFG_EVENT_NOTIFY_DS_WAKEUP Enable or disable the RF_DEEP_SLEEP wakeup notification. Default : "0" 0: Disable 1: Enable

BLE_CFG_RF_CLVAL Adjustment value of the 32MHz crystal oscillator. Default : "7" Set this option according to the board environment. Range : 0 to 15

Refer to "Tuning procedure of Bluetooth dedicated clock frequency(R01AN5488)" for details.

BLE_CFG_RF_DDC_EN Enable or disable the DC-DC on the RF. Default : "1" 0: Disable 1: Enable BLE_CFG_RF_SCA Sleep Clock Accuracy (SCA) for the RF slow clock. Default : "250" Range : 250 to 500 ppm

BLE_CFG_RF_MAX_TX_POW Maximum transmit power configuration. Default : "0" Range : 0 to 1

0: max +0dBm 1: max +4dBm BLE_CFG_RF_DEF_TX_POW Default transmit power level. Default : "0" Range : 0 to 2 This option depends on the BLE_CFG_RF_MAX_TX_POW option.

If the BLE_CFG_RF_MAX_TX_POW option is 0(0dBm), this option is as follows. 0(High) : 0dBm 1(Mid) : 0dBm 2(Low) : -18dBm

If the BLE_CFG_RF_MAX_TX_POW option is 1(+4dBm), this option is as follows. 0(High) : +4dBm 1(Mid) : 0dBm 2(Low) : -20dBm BLE_CFG_RF_DEEP_SLEEP_EN Enable or disable the RF Deep Sleep. Default : "1"

0: Disable 1: Enable

R01AN5606EJ0220 Rev.2.20 Page 37 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Configuration options (r_ble_cfg.h) BLE_CFG_DEV_DATA_CF_BLOCK The Code Flash(ROM) block stored the device specific data. Default : "383" Range : -1 to 383 If this option is set to -1, the device specific data in the Code Flash isn't used. The blocks from "0" to "15" are the Start-Up Program Protection block. If the Start-Up Program Protection is used, don’t use the blocks from "0" to "15". Refer to "6.2 Device-specific Data Management" for details. BLE_CFG_DEV_DATA_DF_BLOCK Not support in RE01B. Default : "-1" BLE_CFG_GATT_MTU_SIZE The MTU size (bytes) for the GATT communication. Default : "247" Range : 23 to 247 BLE_CFG_NUM_BOND Not support in RE01B. Default : "7" BLE_CFG_EN_SEC_DATA Not support in RE01B. Default : "0" BLE_CFG_SECD_DATA_DF_BLOCK Not support in RE01B. Default : "0"

BLE_CFG_CMD_LINE_EN Enable or disable the command line function. Default : "1" 0: Disable 1: Enable

BLE_CFG_BOARD_LED_SW_EN Enable or disable support the board LED & Switch control. Default : "1" 0: Disable 1: Enable BLE_CFG_LOG_LEVEL Log level. Default : "3" Range : 0 to 3

0 : disable 1 : Error 2 : Error & Warning 3 : Error & Warning & Debug

BLE_CFG_ABS_API_EN Enable or disable support the Abstraction API. Default : "1" 0: Disable 1: Enable

BLE_CFG_SOFT_TIMER_EN Can not change from “1” in RE01B. Default : "1" BLE_CFG_MCU_LPC_EN Enable or disable support the MCU low power consumption Default : "1" control.

0: Disable 1: Enable BLE_CFG_HCI_MODE_EN Select start in HCI mode or not. Default : "0" 0: Not start in HCI mode 1: Start in HCI mode BLE_CFG_SOFT_TIMER_AGT_CH Select AGT channel used by software timer. Default : "1" 0: AGT0 1: AGT1

R01AN5606EJ0220 Rev.2.20 Page 38 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Configuration options (r_ble_cfg.h) BLE_CFG_AUTO_READ_ADC_EN Enable or disable the automatically reading A/D convertor (ADC). Default : "0" 0: Disable 1: Enable

BLE_CFG_MCU_PSM_OPE Select MCU Power Supply Mode during Operating mode (OPE). Default : "1"

0: ALLPWON 1: EXFPWON (*1)

*1: When selecting EXFPWON, the program code except a part of one must be located in RAM. BLE_CFG_MCU_VBB_SSTBY Enable or disable Back Bias Voltage (VBB) control of MCU power control mode during Software standby mode (SSTBY). Default : "1" 0: Disable 1: Enable

R01AN5606EJ0220 Rev.2.20 Page 39 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.4 Abstraction API Abstraction API simplifies the procedure used with the BLE Protocol Stack. Refer to “API Document (r_ble_api_spec.chm)” for details.

3.5 Software timer Software timer uses the Asynchronous general-purpose timer (AGT) of MCU. The AGT channel is selected by BLE_CFG_SOFT_TIMER_AGT_CH option. If the Software timer is used, set the BLE_CFG_SOFT_TIMER_EN option to “1”. The features of Software Timer are as follows:

• Software Timer uses one channel of Asynchronous general-purpose timer (AGT).(default AGT1) Since the AGT count source uses AGTLCLK (Low-speed On-Chip Oscillator (LOCO) in MCU), timer operation is possible even in the software standby of the MCU. • Timeout time of Software Timer is specified in units of milliseconds. Callback function is invoked when Software Timer is triggered and the timeout time expires. • Software Timer has two operation modes. ⎯ Periodic Notification mode (BLE_TIMER_PERIODIC): Once application starts operation of Software Timer channel, expiration of timeout time is notified periodically. ⎯ One-Shot Notification mode (BLE_TIMER_ONE_SHOT): When application starts operation of Software Timer channel, expiration of timeout time is notified only once. • Software Timer has multiple channels. Timeout time, operation mode, and callback function can be set independently for each channel. • The number of Software Timer channels is defined by the BLE_TIMER_NUM_OF_SLOT macro (default is 10) and can be changed. Note that 24bytes management area is required on RAM per channel.

Notes for using Software Timer are as follows:

• If a long timeout time is specified, or if multiple channels are used, timeout is delayed because CMT operation is started and stopped repeatedly. • CMT suspends its operation on Software Standby Mode, which is low power consumption mode of CPU. Do not transition to Software Standby Mode while Software Timer is running. • Abstraction API uses Software Timer. If application uses Abstraction API, invoke the R_BLE_TIMER_Init(), which is the initialization function of Software Timer, before invoking R_BLE_ABS_Init(), which is the initialization function of Abstraction API. • Since this software timer is also used in the BLE Protocol Stack, the software timer feature cannot be disabled.

R01AN5606EJ0220 Rev.2.20 Page 40 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Software Timer provides the following API to applications. For more information about API specification, refer to the API document (r_ble_api_spec.chm).

Table 3.5 Software requirements

Software Timer API Description R_BLE_TIMER_Init Initialize Software Timer R_BLE_TIMER_Terminate Terminate Software Timer R_BLE_TIMER_Create Allocate Software Timer channel and set operation parameters R_BLE_TIMER_Delete Release Software Timer channel R_BLE_TIMER_Start Start operation of Software Timer channel R_BLE_TIMER_Stop Stop operation of Software Timer channel R_BLE_TIMER_UpdateTimeout Update timeout time and start operation of Software Timer channel R_BLE_TIMER_GetRemainingTime Get remaining time of the Software Timer Channel

The state transition of Software Timer is shown in Figure 3.6.

Uninitialized R_BLE_TIMER_Init Initialized Timeout state state state callback notification R_BLE_TIMER_Terminate R_BLE_TIMER_ONE_SHOT R_BLE_TIMER_Create R_BLE_TIMER_Delete Timeout Time R_BLE_TIMER_PERIODIC expires R_BLE_TIMER_Start / Channel-allocated R_BLE_TIMER_UpdateTimeout Channel-running state state (Channel stoped) R_BLE_TIMER_Stop

R_BLE_TIMER_UpdateTimeout

Figure 3.6 State Transition of Software Timer

• R_BLE_TIMER_UpdateTimeout() can be invoked on the Timeout state too. • R_BLE_TIMER_Delete() can be invoked on the Running state and the Timeout state too.

Example implementation of Software Timer is shown as below.

• Include header file of Software Timer and initialize Software Timer with the R_BLE_TIMER_Init().

/* Include Software Timer header */ #include "timer/r_ble_timer.h"

{ /* Initialize Software Timer */ R_BLE_TIMER_Init(); }

R01AN5606EJ0220 Rev.2.20 Page 41 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

• Allocate a channel of Software Timer and specify the following operation parameters with the R_BLE_TIMER_Create(). Also, the R_BLE_TIMER_Create() returns handle value to identify the Software Timer channel allocated. ⎯ Timeout Time (in units of milliseconds) ⎯ Callback function to notify timeout ⎯ Operation Mode: BLE_TIMER_PERIODIC or BLE_TIMER_ONE_SHOT

Note: Application attempts to allocate channels more than the number of channels (BLE_TIMER_NUM_OF_SLOT) that can be allocated, the R_BLE_TIMER_Create() returns the BLE_ERR_LIMIT_EXCEEDED error code.

static void timer_cb(uint32_t timer_hdl) { }

{ /* Allocate Software Timer channel */ ble_status_t status; status = R_BLE_TIMER_Create(&gs_timer_hdl, 1000, BLE_TIMER_PERIODIC, timer_cb);

/* Start operation of Software Timer channel */ R_BLE_TIMER_Start(gs_timer_hdl); }

• Start operation of Software Time channel with either the R_BLE_TIMER_Start() or the R_BLE_TIMER_UpdateTimeout(). When timeout time expires, callback function which is registered with the R_BLE_TIMER_Create() is invoked. • Operation of Software Timer channel can be stopped with the R_BLE_TIMER_Stop(). • Software Timer channel allocated can be used any number of times.

/* Handle of Software Timer Handle */ static uint32_t gs_timer_hdl;

{ /* Start Operation of Software Timer Channel */ R_BLE_TIMER_Start(gs_timer_hdl);

/* Update timeout time and start operation of Software Time channel */ R_BLE_TIMER_UpdateTimeout(gs_timer_hdl, 500);

/* Stop operation of Software Timer Channel */ R_BLE_TIMER_Stop(gs_timer_hdl); }

R01AN5606EJ0220 Rev.2.20 Page 42 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

• If Software Timer channel allocated is no longer needed, it can be released with the R_BLE_TIMER_Delete().

{ /* Release Software Timer Channel */ R_BLE_TIMER_Delete(&gs_timer_hdl); }

• If Software Timer is no longer used, it can be terminated with the R_BLE_TIMER_Terminate(). Note that the R_BLE_TIMER_Terminate() must be invoked after releasing all Software Timer channels.

{ /* Terminate Software Timer */ R_BLE_TIMER_Terminate(); }

3.6 Profile common This function provides the common interfaces in the BLE Profile. The interfaces are call by the code generated by the QE for BLE. Refer to “Bluetooth Low Energy Profile Developer’s Guide(R01AN5638)” for the details of the profile development and the profile common.

R01AN5606EJ0220 Rev.2.20 Page 43 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.7 Logger The Logger feature provides the following log message output functions.

• Three log levels (ERROR, WARNING, DEBUG) • Log message output is written in the same format as printf() function. • Provision of functions that convert BD addresses and UUID into character strings.

The log message is output to the command line feature console. Therefore, BLE_CFG_CMD_LINE_EN must be set to “1” when using the logger feature. The log level is set using BLE_CFG_LOG_LEVEL configuration option that specifies the log level for the entire project. Table 3.6 shows the setting values of BLE_CFG_LOG_LEVEL and log output settings.

Table 3.6 Setting BLE_CFG_LOG_LEVEL BLE_CFG_LOG_LEVEL value Description 0 No log message output 1 ERROR log message output 2 ERROR and WARNING log message output 3 ERROR and WARNING and DEBUG log message output

The log output uses the macro for log output shown in Table 3.7, which is defined in r_ble_logger.h.

Table 3.7 Macro for log output Macro Name LOG_LABEL Description BLE_LOG_ERR ERR For ERROR log message output BLE_LOG_WRN WRN For WARNING log message output BLE_LOG_DBG DBG For DEBUG log message output

Use the log message output macro to set the log in the same format as printf() as follows.

BLE_LOG_DBG("BLE_GAP_EVENT_STACK_ON \n");

Log messages are output in the following format.

module_tag: [LOG_LABEL] (function:line) log_body \n

“module_tag” can specify the tag to be added to the log for each module by “BLE_LOG_TAG” macro. Define “BLE_LOG_TAG” macro before including r_ble_logger.h.

#define BLE_LOG_TAG “app_main” #include “logger/r_lib_logger.h”

In the previous example, the log is output as follows: “module_tag” is set to “app_main”.

app_main: [DBG] (ble_app_gapcb:238) BLE_GAP_EVENT_STACK_ON

R01AN5606EJ0220 Rev.2.20 Page 44 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

In addition, BLE_BD_ADDR_STR() and BLE_UUID_STR() functions are provided for output of BD address and 16-bit/128-bit UUID log messages. BLE_BD_ADDR_STR() function returns string in BD address format when BD address byte array and address type are specified as parameters. BLE_UUID_STR() function returns a UUID format string when UUID byte array and UUID type are specified as parameters. Refer to “R_BLE API document (r_ble_api_spec.chm)” for details. BLE_ADDR_STR() and BLE_UUID_STR() functions are used as follows:

BLE_LOG_DBG(“Connected to %s\n”, BLE_ADDR_STR(addr, addr_type)); BLE_LOG_DBG(“UUID: %s\n”, BLE_UUID_STR(uuid, uuid_type));

R01AN5606EJ0220 Rev.2.20 Page 45 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.8 Command Line Command Line control the BLE functions via a serial interface. This function uses the serial communication interface (SCI) of MCU. Command types are standard commands provided by the BLE module and user commands created by user. Command Line Interface (CLI) provides a function to execute BLE control commands through a terminal emulator that supports VT100 emulation. Terminal emulators that support VT100 emulation can be used with Tera Term application. The debug console provided by e2 studio does not support VT100 emulation. The features provided by Command Line Interface are shown in Table 3.8.

Table 3.8 Command Line Interface Features Features Description Prompt display "$" is displayed as a prompt to indicate that the command can be executed. Specifying the editing position With the left and right arrow keys, you can specify the position to edit the with the left and right arrow keys characters in the command line. Edit characters with backspace Use the BS and DEL keys to delete characters in the command line. and delete keys Command help Enter "help" after a command and execute it, help message shown at each command. Support hierarchical command Provides a hierarchical command system. system with subcommands Support multiple command sets Multiple command sets can be registered. Abort command execution Press “Ctrl + C” or “Ctrl + D” keys to aborts the current command. Command completion Press TAB key to complete command input.

When using Command Line Interface features, set the BLE_CFG_CMD_LINE_EN configuration option to “1”. This sample code is uses SCI2.

Set the following items in the terminal emulator of the computer connected to the board. Table 3.9 Terminal emulator settings Items Settings New-line (Receive) LF New-line (Transmit) CR Terminal Mode VT100 Baud rate 115200 Data 8bit Parity none Stop bits 1bit Flow Control none

R01AN5606EJ0220 Rev.2.20 Page 46 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.8.1 Standard command BLE control command provided by BLE module using the command line interface features are shown in the following sections.

3.8.1.1 GAP command (1) Advertising command adv command gap adv [adv_type] [operation] (addr_type) (-wl) Format : Start, stop or remove advertising. Select one of the followings as the type of advertising. legacy : legacy advertising ext : extended advertising [adv_type] non-conn : non-connectable advertising periodic : periodic advertising

Start or stop advertising. start : start advertising [operation] stop : stop advertising. remove : remove advertising set specified by adv_type.

Parameters : Specify the address type of advertising. When this parameter is omitted, static address is selected. pub : Public Address rnd : Static Address rpa_pub : If registering an identity address by gap priv set command (addr_type) or application, RPA is used. In cases other than the above, it will be a public address. rpa_rnd : If registering an identity address by gap priv set command or application, RPA is used. In cases other than the above, it will be a static address.

Specify this parameter when using white list. (-wl) If white list is not used, this parameter is can be omitted. gap adv legacy start Start legacy advertising.

Example : gap adv ext stop Stop extended advertising.

Other parameters related to Advertising that cannot be set from this command are set in the Advertising parameter variables of gs_legacy_adv_param, gs_ext_adv_param, gs_non_conn_adv_param, and gs_periodic_adv_param in app_lib\cmd\r_ble_cmd_abs.c. Changing these variables will change the setting of Advertising parameters. As for details of parameters, refer to Modules >> Application Library >> Abstraction API >> Structures >> st_ble_abs_legacy_adv_param_t, st_ble_abs_ext_adv_param_t, st_ble_abs_non_conn_adv_param_t, and st_ble_abs_perd_adv_param_t in API document (r_ble_api_spec.chm).

R01AN5606EJ0220 Rev.2.20 Page 47 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(2) Scan command scan command gap scan (operation) (filter_ad_type) (filter_data) (addr_type) (-wl) Start scan. Format : It is not necessary to specify (operation) when starting scan. When scan stops, input [ctrl] + [c]. Specify operation for scan (operation) stop : stop scan. The AD type for filtering. Refer to Bluetooth SIG, "Assigned numbers and GAP" for the definition (filter_ad_type) of the AD type. If the filter is not used, this parameter can be omitted. The data for filtering. Specify the data for the filter_ad_type. (filter_data) If the filter is not used, this parameter can be omitted. If the filter_ad_type is not used, this parameter is ignored. Specify the address type of scan request. Parameters : When this parameter is omitted, static address is selected. pub : Public Address rnd : Static Address rpa_pub : If registering an identity address by gap priv set (addr_type) command or application, RPA is used. In cases other than the above, it will be a public address. rpa_rnd : If registering an identity address by gap priv set command or application, RPA is used. In cases other than the above, it will be a static address.

Specify this parameter when using white list. (-wl) If white list is not used, this parameter is can be omitted. gap scan Start scan.

Example : gap scan 2 0x01,0x29 Search the advertising report which of the AD Type : Incomplete List of 16-bit Service Class UUIDs(0x02) and the service UUID : 0x2901.

Other parameters related to Scan that cannot be set from this command are set in the scan parameter variables of gs_phy_param_1m and gs_scan_param in app_lib\cmd\r_ble_cmd_abs.c. Changing these variables will change the scan parameter settings. As for details of parameters, refer to Modules >> Application Library >> Abstraction API >> Structures >> st_ble_abs_scan_param_t and st_ble_abs_scan_phy_param_t in API document (r_ble_api_spec.chm).

R01AN5606EJ0220 Rev.2.20 Page 48 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(3) Connection command conn command gap conn [addr] [addr_type] (own_addr_type) (dummy_irk) (-wl) Format : Send a connection request. In case of stopping connection request, input [ctrl] + [c]. [addr] Remote device address. Specify the followings as remote device address type. pub : Public Address [addr_type] rnd : Random Address

Specify the address type of connection request. When this parameter is omitted, static address is selected. pub : Public Address rnd : Static Address (own_addr_type) rpa_pub : If registering an identity address by gap priv set Parameters : command or application, RPA is used. In cases other than the above, it will be a public address. rpa_rnd : If registering an identity address by gap priv set command or application, RPA is used. In cases other than the above, it will be a static address. Select whether to use the IRK of the dummy of the remote device to be registered in the Resolving List when RPA is specified in (dummy_irk) own_addr_type. dummy_irk : use the IRK of the dummy of the remote device Specify this parameter when using white list. (-wl) If white list is not used, this parameter is can be omitted. gap conn 74:90:50:00:95:a8 pub Send a connection request to the remote device whose public address is 74:90:50:00:95:a8.

gap priv set net gap conn d8:19:e3:30:92:21 pub Example : Send a connection request to the remote device whose random address is d8:19:e3:30:92:21. Local devices use RPA. The IRK for the remote device use dummy IRK.

Note: If the local device uses RPA, it is necessary to execute the "gap priv" command in advance.

Other parameters related to Connection that cannot be set from this command are set in the connection parameter variables of gs_conn_phy_1m and gs_conn_param in app_lib\cmd\r_ble_cmd_abs.c. Changing these variables will change the connection parameter settings. As for details of parameters, refer to Modules >> Application Library >> Abstraction API >> Structures >> st_ble_abs_conn_phy_param_t and st_ble_abs_conn_param_t in API document (r_ble_api_spec.chm).

R01AN5606EJ0220 Rev.2.20 Page 49 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(4) Disconnection command disconn command gap disconn [conn_hdl] Format : Disconnect the connection. Connection handle of which the connection is disconnected. Parameters : [conn_hdl]

gap disconn 0x0020 Example : Disconnect the connection with connection handle 0x0020.

(5) Device command device command gap device Format : Display the addresses of the connected devices. Parameters : None gap device Example : Display the addresses of the connected devices.

R01AN5606EJ0220 Rev.2.20 Page 50 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(6) Privacy command priv command gap priv [operation] (IRK) [priv_mode] gap priv [operation] [addr] [addr_type] Format : gap priv [operation] lrpa ([addr] [addr_type]) gap priv [operation] Operate the local device's privacy. Select one of the followings as the operation of privacy. set : Register the IRK of the local device in the resolving list and turn on the address generation function. It is used when the local device uses [operation] RPA in the advertising command and connection command. remove : Delete the remote device registered in the resolving list. get : Get the local device RPA for sending to remote device. off : Turn off the address generation function. [operation] : set (IRK) : The local device's IRK which is registered in the resolving list. If this parameter is omitted, the IRK is generated with the random generation function. [priv_mode] : Privacy mode and the address type of local device. Select one of the followings. net : network privacy mode. Static address is used as identity address. dev : device privacy mode. Static address is used as identity address. Parameters : net_pub : network privacy mode. Public address is used as identity address. dev_pub : device privacy mode. Public address is used as identity address. [priv_mode] net_rnd : network privacy mode. Static address is used as identity address. dev_rnd : device privacy mode. Static address is used as identity address. [operation] : remove [addr] : Specify the address (6 bytes) of the remote device registered in the Resolving list. [addr_type] : Specify the address type of the remote device registered in the Resolving list. [operation] : get lrpa : Get the local device RPA for advertising. [addr] : Specify the address (6 bytes) of the remote device registered in the Resolving list. [addr_type] : Specify the address type of the remote device registered in the Resolving list.

R01AN5606EJ0220 Rev.2.20 Page 51 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

gap priv set 0001020304050600708090a0b0c0d0e0f dev Register IRK : 0x0f0e0d0c0b0a09080706050403020100 and set the privacy mode to "device privacy mode". Static address is used as identity address.

gap priv set net IRK is generated by the random number generation . The privacy mode is set to "network privacy mode". Static address is used as identity address. Example :

gap priv set net_pub IRK is generated by the random number generation . The privacy mode is set to "network privacy mode". Public address is used as identity address.

gap priv remove 12:34:56:78:9a:bc pub Delete the 12:34:56:78:9a:bc (public) remote device registered in the resolving list.

R01AN5606EJ0220 Rev.2.20 Page 52 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(7) Connection config command conn_cfg command gap conn_cfg [operation] {params, ...} Format : Connection configuration command. Type of connection configuration. Select one of the followings. update : Connection parameter update. [operation] phy : Set PHY. def_phy : Set default phy. data_len : Set data packet length or data transmit time. [operation] : update Parameter1 : Connection handle. Parameter2 : Connection interval. Time(ms) = Parameter2 x 1.25. Valid range is 0x0006-0x0C80. Parameter3 : Slave latency. Valid range is 0x0000-0x01F3. Parameter4 : Supervision timeout. Time(ms) = Parameter4 x 10. Valid range is 0x000A-0x0C80. Input Parameter2-4 to meet the following condition. Parameter4 x 10 >= (1 + Parameter3) x Parameter2 x 1.25 [operation] : phy Parameter1 : Connection handle Parameter2 : Transmitter PHY. Parameter2 is set to a bitwise OR of the following values. bit0 : 1M PHY bit1 : 2M PHY bit2 : Coded PHY Parameter3 : Receiver PHY. Parameter3 is set to a bitwise OR of the following values. Parameters : bit0 : 1M PHY bit1 : 2M PHY bit2 : Coded PHY {params, ...} Parameter4 : Coding scheme of Coded PHY. Select one of the following. 0x00 : The controller's preferred value. 0x01 : S=2 Coding scheme. 0x02 : S=8 Coding scheme. [operation] : def_phy Parameter1 : Transmitter PHY preferences which a remote device may change. Parameter1 is set to a bitwise OR of the following values. bit0 : 1M PHY bit1 : 2M PHY bit2 : Coded PHY Parameter2 : Receiver PHY preferences which a remote device may change. Parameter2 is set to a bitwise OR of the following values. bit0 : 1M PHY bit1 : 2M PHY bit2 : Coded PHY [operation] : data_len Parameter1 : Connection handle Parameter2 : Maximum transmit packet data length (in bytes). Valid range is 0x001B-0x00FB. Parameter3 : Maximum transmit time (us). Valid range is 0x0148-0x4290.

R01AN5606EJ0220 Rev.2.20 Page 53 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

gap conn_cfg update 0x0026 0x0100 0 0x0100 Change the connection parameters of the connection handle : 0x0026 to the following values.

connection interval : 0x0100 slave latency : 0 supervision timeout : 0x0100

gap conn_cfg phy 0x0026 2 2 0 Change the PHY of the connection (connection handle : 0x0026) Transmitter PHY : 2M Example : Receiver PHY : 2M

gap conn_cfg def_phy 7 7 Accept the following change request. Transmitter PHY : 1M, 2M and Coded PHY. Receiver PHY : 1M, 2M and Coded PHY.

gap conn_cfg data_len 0x0026 0x00FB 0x4290 Change the following transmit packet length or transmit time Max transmit packet length : 251 bytes Max transmit time : 0x4290 us

R01AN5606EJ0220 Rev.2.20 Page 54 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(8) White List command wl command gap wl [operation] {params, ...} Format : White List operation command. White List operation. Select one of the followings. reg : Register a device specified with the {params, ...} on the White List. [operation] del : Delete the device specified with the {params, ...} on the White List. clear : Clear the White List. [operation] : reg Parameter1 : Address of a device to be registered on the White List. Parameter2 : Address type of a device to be registered on the White List. pub : Public Address Parameters : rnd : Random Address

[operation] : del {params, ...} Parameter1 : Address of a device to be deleted on the White List. Parameter2 : Address type of a device to be deleted on the White List. pub : Public Address rnd : Random Address

[operation] : clear Not used.

gap wl reg 74:90:50:00:95:a8 pub Register the device whose public address is 74:90:50:00:95:a8 on the White List.

gap wl del 74:90:50:00:95:a8 pub Example : Delete the device whose public address is 74:90:50:00:95:a8 on the White List.

gap wl clear Clear the White List.

R01AN5606EJ0220 Rev.2.20 Page 55 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(9) Authentication command auth command gap auth [operation] {params, ...} Format : Pairing or encryption command. Security operation. start : Start pairing or encryption. passkey : Input 6-digit number(decimal) to be required in passkey [operation] entry pairing. numcmp : Return the result of a numeric comparison. del : Delete the pairing keys.

[operation] : start Parameter1 : Connection handle identifying the connection which local device starts pairing or encryption.

[operation] : passkey Parameter1 : 6 digit passkey (decimal)

[operation] : numcmp Parameter1 : Result of a numeric comparison.("yes" or "no") Return "yes" if both devices display same number, otherwise Parameters : "no". [operation] : del Parameter1 : Type of key to be deleted. local : keys which local device distributes. {params,...} remote : keys distributed from the remote devices. all : the above two types of keys.

Parameter2: Type of the remote device key deletion. addr : Delete the keys specified by the Parameter3, 4. all : Delete all the keys distributed from remote devices. not_conn : Delete the keys of the unconnected remote devices.

Parameter3 : Address of the remote device whose keys to be deleted.

Parameter4 : Address type of the remote device whose keys to be deleted. pub : Public Address rnd : Random Address

R01AN5606EJ0220 Rev.2.20 Page 56 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

gap auth start 0x0026 Start pairing or encryption with the connection (connection handle : 0x0026).

gap auth passkey 123456 Input "123456" as a passkey.

Example : gap auth numcmp yes Return "yes" as a result of numeric comparison.

gap auth del remote all Delete all the keys distributed from the remote devices.

R01AN5606EJ0220 Rev.2.20 Page 57 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(10) Synchronization command sync command gap sync [operation] {params...} Format : Create or Terminate a periodic sync. Periodic sync operation. create : Create a periodic sync with the device whose address is specified by the {params...}. Scanning runs until a periodic sync is established. [operation] In case of stopping creating periodic sync, input [ctrl] + [c].

term : Terminate the periodic sync whose sync_hdl is specified by the {params...}. Parameters : [operation] : create Parameter1 : Address of the advertiser. Parameter2 : Address type of the advertiser.

{params,...} [operation] : term Parameter1 : Sync handle identifying the periodic sync to be terminated. If no parameters are given, all the established periodic syncs are terminated. gap sync create 74:90:50:00:95:a8 pub Establish a periodic sync with the advertiser whose public address is 74:90:50:00:95:a8. Example : gap sync term 0x01 Terminate the periodic sync (sync handle : 0x01).

R01AN5606EJ0220 Rev.2.20 Page 58 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(11) Version command

ver command gap ver Get the following BLE Protocol Stack version information. - Link Layer Format : - HCI - Host Stack - Manufacturer ID - BLE module - library type Parameters : None gap ver Get the version information.

Result sample : Link Layer / HCI Version HCI version : 0x09 *1 HCI revision : 0x000b Link Layer version : 0x09 *1 Example : Link Layer subversion : 0x1908 Manufacturer ID : 0x0036 Host stack Version major version : 0x0d minor version : 0x19 subminor version : 0x08 BLE module Version major | minor version : 0x00010000 *2 lib type : 0x00000001 *3

*1 : The version number defined by Bluetooth SIG (https://www.bluetooth.com/specifications/assigned- numbers). The version number 0x09 shows Bluetooth 5.0 . *2 : The upper 2 bytes shows the major version and the lower 2 bytes shows the minor version. *3 : 0: All features, 1: Balance, 2: Compact

R01AN5606EJ0220 Rev.2.20 Page 59 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.8.1.2 Vendor Specific (VS) command (1) Tx Power command txp command vs txp [operation] [conn_hdl] {params,...} Format : Set / Get the transmit power. Transmit power operation. [operation] set : Set the transmit power. get : Get the transmit power. Connection handle identifying the connection whose transmit power to be set or retrieved. [conn_hdl] Inputting 0xFFFF sets / gets the transmit power in the non-connected state. Parameters : [operation] : set Parameter1 : Tx power level to be set.

0 : High {params,...} 1 : Middle 2 : Low [operation] : get Not used. vs txp set 0xFFFF 0 Set the non-connected state transmit power to the High level.

Example : vs txp get 0x0026 Get the transmit power of the connection (connection handle : 0x0026).

(2) Coded Scheme command scheme command vs scheme [type] Format : Set the coding scheme of the Coded PHY. Coding scheme for Primary advertising PHY, Secondary advertising PHY, request for connection establishment. This parameter is set to a bitwise OR of the following values.

Parameters : [type] By default, S=8 coding scheme is enabled. bit0 : Coding scheme for Primary Advertising PHY(0:S=8/1:S=2). bit1 : Coding scheme for Secondary Advertising PHY(0:S=8/1:S=2). bit2 : Coding scheme for Connection(0:S=8/1:S=2). vs scheme 7 Example : Set coding scheme for Primacy Advertising, for Secondary Advertising, and for Connection to S=2.

R01AN5606EJ0220 Rev.2.20 Page 60 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(3) Extended Direct Test Mode(DTM) command test command vs test [operation] {params, ...} Format : DTM test command. DTM test operation. Select one of the followings. tx : Start DTM transmitter test. Set "channel", "length", "payload", "phy", "tx_power", "option" and "number of packet" to {params, ..,}. [operation] rx : Start DTM receiver test. Set "channel" and "phy" to {params, ...}. end : Terminate DTM test. No parameter. [operation] : tx Parameter1 : Channel used in Tx test. Valid range is 0 to 39. Frequency range is 2402 MHz to 2480 MHz. Parameter2 : Length(in bytes) of the packet used in Tx Test. Valid range is 0 to 255. Parameter3 : Packet Payload. Valid range is 0x00-0x07. If the Parameter6 is set to "non-", this parameter is ignored.

Parameters : Payload type: 0x00 : PRBS9 sequence '11111111100000111101..'. 0x01 : Repeated '11110000' 0x02 : Repeated '10101010' {params, ...} 0x03 : PRBS15 sequence 0x04 : Repeated '11111111' 0x05 : Repeated '00000000' 0x06 : Repeated '00001111' 0x07 : Repeated '01010101' Parameter4 : Transmitter PHY used in test. Select one of the following. If the Parameter6 is set to "non-modulation", this parameter is ignored. If the Parameter6 is configured to "modulation" and "continuous transmission", 0x03 : Coded PHY (S=8) and 0x04 : Coded PHY (S=2) are not supported.

0x01 : 1M PHY 0x02 : 2M PHY 0x03 : Coded PHY (S=8) 0x04 : Coded PHY (S=2)

R01AN5606EJ0220 Rev.2.20 Page 61 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Parameter5 : Tx Power Level used in DTM Tx Test. Select one of the following. 0x00 : High 0x01 : Middle 0x02 : Low Parameter6 : The test option configuration. This parameter is set to a bitwise OR of the following bits. bit0 : 0:modulation, 1:non-modulation bit1 : 0:packet transmission, 1:continuous transmission Parameter7 : The number of packets to be sent. Valid range is 0x0000- 0xFFFF. If the Parameter6 is configured to "continuous transmission", this parameter is ignored. If this parameter is set to 0x0000, the packets are continuously transmitted until test end command is issued.

Parameters : {params, ...} [operation] : rx Parameter1 : Channel used in the test. Valid range is 0 to 39. Frequency range is 2402 MHz to 2480 MHz. Parameter2 : Receiver PHY used in the test. Select one of the following.

0x01 : 1M PHY 0x02 : 2M PHY 0x03 : Coded PHY

The coding scheme (S=8/S=2) doesn't need to be specified in the receiver test.

[operation] : end Not used.

vs test tx 39 251 1 3 1 0 1 Start DTM transmitter test. CH : 39ch Packet length : 251 bytes payload : Repeated '11110000' sequence phy : Coded PHY(S=8) tx_power : Middle option : modulation packet transmission num_of_packet : 1 Example : vs test rx 39 2 Start DTM receiver test. CH : 39ch phy : 2M PHY

vs test end Terminate DTM test.

R01AN5606EJ0220 Rev.2.20 Page 62 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(4) BD Address command addr command vs addr [operation] [area] {params...} Format : Set/Get the address of the local device. Address operation. Select one of the followings. set : Set an address to the local device. [operation] Set address type and address to {params...} . get : Get the address of the local device. Set the address type to {params...}. The area where the address is stored. [area] curr : The temporary area storing the address.

[operation] : set Parameters : Parameter1 : Address type pub : Public Address rnd : Random Address Parameter2 : Address {params...} [operation] : get Parameter1 : Address type pub : Public Address rnd : Random Address

vs addr set curr pub 78:90:50:00:95:a8 Set 78:90:50:00:95:a8 to the current public address.

Example : vs addr get curr pub Get the current public address.

R01AN5606EJ0220 Rev.2.20 Page 63 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

(5) Random Number generation command rand command vs rand [rand_size] Format : Generate a random number. Specify the size of the random number to be generated. Parameters : [rand_size] Range: 4 to 16 [bytes]. vs rand 16 Example : Generate a 16 bytes random number.

(6) Scan Channel command

scan_ch_map command vs scan_ch_map [operation] {params,...} Format : Set/Get the scan channel map. Scan Channel operation. Select one of the followings. set : Set the channel map specified by {params,...} as scan channel.

[operation] get : Get the current scan channel map.

[operation] : set Parameter 1 : The channel map to be set. Parameter : It is a bitwise OR of the following values. bit 0 : 37 ch bit 1 : 38 ch {params,...} bit 2 : 39 ch other than the above : reserved

[operation] : get “Get” operation does not use parameter.

vs scan_ch_map set 7 Set 37, 38, 39ch as scan channel.

Example : vs scan_ch_map get Get the current scan channel map.

R01AN5606EJ0220 Rev.2.20 Page 64 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

3.8.1.3 SYS command (1) MCU Software Standby command stby command sys stby [operation] Format : Control the software standby mode. Software standby operation. Select one of the followings. on : Enter the software standby mode. Parameters : [operation] off : Come back from the software standby mode. get : Get the current software standby status. sys stby on Example : Enter the software standby mode.

R01AN5606EJ0220 Rev.2.20 Page 65 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.8.1.4 BLE command (1) BLE protocol stack Reset command stby command ble reset Format : Reset the BLE protocol stack. Parameters : None ble reset Example :

(2) BLE protocol stack Close command stby command ble close Format : Terminate the BLE protocol stack. To restart the BLE protocol stack, execute “ble reset” command. Parameters : None ble close Example :

R01AN5606EJ0220 Rev.2.20 Page 66 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.8.2 User command creation procedure Refer to “4.5.2 How to create a user command” in “RE01B Group Bluetooth Low Energy Application Developer's Guide (R01AN5643)”.

R01AN5606EJ0220 Rev.2.20 Page 67 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.9 LED and Switch control When using Command Line Interface features, set the BLE_CFG_BOARD_LED_SW_EN configuration option to “1”. Table 3.10 shows the pins that connects to the LED and the Switch on the board. Change the options according to the board that you want to use.

Table 3.10 Pins connected to the LED and the Switch.

Board LED Switch

EB-RE01B board LED2: P506 SW2: IRQ1

3.9.1 Changing board Modify the followings in Device\BLE\app_lib\r_ble_board.c according to needs.

Table 3.11 Board configuration Configuration options (r_ble_board.c)

SW2_IRQ 1 LED2_PORT 506

R01AN5606EJ0220 Rev.2.20 Page 68 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 3.10 MCU low power consumption When using MCU low power consumption function (LPC), set the BLE_CFG_MCU_LPC_EN configuration option to “1”. MCU LPC processing is performed by API of r_ble_pf_lowpower.c.

• Use R_BLE_LPC_Init() to initialize Low power consumption function. ⎯ The SSTBY suppression flag variable (g_ble_mcu_wakeup_offset) is initialized in this API. When the command line function is enabled (BLE_CFG_CMD_LINE_EN is set to 1), the initial value of the flag is true (SSTBY suppression). When the command line function is disabled (BLE_CFG_CMD_LINE_EN is set to 0), the initial value of the flag is false (SSTBY suppression is released). To change this flag variable dynamically, use R_BLE_LPC_SetInhibitSoftwareStandby(). • Use R_BLE_LPC_EnterLowPowerMode() to shift to Low power consumption state. Call this function after the execution of R_BLE_Execute() is completed, and execute the following. ⎯ Disable MCU interrupts ⎯ Check that there is no problem even if each component shifts to Low power consumption state ⎯ Execute the transition processing to Low power consumption state of each component ⎯ Enter MCU to Low power consumption state. (Switch between low power consumption states is executed depending on the status of peripheral functions.) • When check_vbb_software_standby() returns true: Transition to VBB+SSTBY (*1) • When check_normal_software_standby() returns true: Transition to NORMAL+SSTBY • Other than the above: Transition to NORMAL+SLEEP *1: The transition to VBB + SSTBY requires BLE_CFG_MCU_VBB_SSTBY to be set to 1. ⎯ After MCU wakes-up from Low power consumption state, resume each component to the normal state • When BLE communication occurs, it resumes from Low power consumption state by RF interrupt.

The MCU has three power supply modes (ALLPWON / EXFPWON / MINPWON). BLE application uses EXFPWON for LPC. When using EXFPWON, set the BLE_CFG_MCU_PSM_OPE configuration option to “1”.

• When operating the BLE Protocol Stack, it is operated with EXFPWON NOMARL mode (High-speed ICLK/PCLKB 32MHz). • When the RF part is in RF_SLEEP state, it transitions to EXFPWON VBB+SSTBY mode (ICLK/PCLKB 32.7kHz). • Switching between VBB mode and NORMAL mode requires about 10msec. • If the RF part is not in RF_SLEEP state, an interrupt may occur within 10msec, so performed in NORMAL+SSTBY mode without transition to VBB mode.

Figure 3.7 MCU power supply mode

R01AN5606EJ0220 Rev.2.20 Page 69 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

In EXFPWON (Flash-excluded power supply mode), the flash power is powered off. The flash memory is disabled due to power shutoff, so instruction execution from the SRAM is necessary. In the BLE application, the method of specifying a section for each object in the linker configuration file is selected to location program code in SRAM.

• In the IAR EWARM environment, specify a section for each object in the linker configuration file (ICF file). • In the GCC environment, specify a section for each object in the linker script file (LD file).

Note: The maximum SRAM size of RE01B is 256KB. If the program code size placed in SRAM exceeds 256KB, an error will occur during linking. In that case, it is necessary to review the configuration options of the BLE module and reduce the program code of the application.

R01AN5606EJ0220 Rev.2.20 Page 70 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 4. Create project This section describes how to create a project to develop a BLE application. For the details about creating a project, see “Getting Started Guide to Development Using CMSIS Package (R01AN5310)”.

4.1 Import a project Referring “2.5 Importing sample code”, import a sample code.

4.2 Stack/Heap size configuration In case of e² studio, set the memory size needed for BLE to the following file in the project.

Device\startup_RE01B_1500KB.c

#define SYSTEM_CFG_STACK_SIZE (0x1000) #define SYSTEM_CFG_HEAP_SIZE (0x400)

In case of EWARM, set the memory size needed for BLE to [Project]→[Options…]→[Linker]→[Config] tab→[Linker configuration file]→[Edit…] button→[Stack/Heap Sizes] tab in the project.

Figure 4.1 Scack/Heap size configuration on EWARM

R01AN5606EJ0220 Rev.2.20 Page 71 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 4.3 Clocks configuration Referring “Getting Started Guide to Development Using CMSIS Package (R01AN5310) 6.1.2 Setting Clock/Power Control Modes on Start of Operation”, configure the clocks to the following file in the project.

Device\Config\r_core_cfg.h

#define SYSTEM_CFG_HOCO_ENABLE (1) #define SYSTEM_CFG_HOCO_FREQUENCY (1) #define SYSTEM_CFG_LOCO_ENABLE (1) #define SYSTEM_CFG_CLOCK_SOURCE (0) #define SYSTEM_CFG_ICK_PCKA_DIV (0) #define SYSTEM_CFG_PCKB_DIV (0) #define SYSTEM_CFG_POWER_CONTROL_MODE (1)

If the BLE is used, set the clocks within the following range.

⚫ System clock / Peripheral module clock A (ICLK/PCLKA): more than 32MHz ⚫ Peripheral module clock B (PCLKB): more than 32MHz

The BLE Protocol Stack is optimized with ICLK/PCLKA, PCLKB: 32MHz. Renesas prerequires configuring the frequency of ICLK and PCLKA to 32MHz to maximize the BLE performance.

R01AN5606EJ0220 Rev.2.20 Page 72 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 4.4 Linker configurations The BLE Protocol Stack is provided as static library. Three types of libraries shown in Table 4.1 are included in the Device\BLE\rble_lib directory.

Table 4.1 BLE Protocol Stack libraries

Type of the BLE Protocol Stack Library /lib_gcc_sotb/lib_ble_a.a All features /lib_iar_sotb/lib_ble_a.a /lib_gcc_sotb/lib_ble_b.a Balance /lib_iar_sotb/lib_ble_b.a /lib_gcc_sotb/lib_ble_c.a Compact /lib_iar_sotb/lib_ble_c.a

Configure the followings to make the BLE Application project available to the BLE Protocol Stack library.

(1) Library configuration In case of e2 studio, Click [Project] → [Properties]. Select “C/C++ Build” → “Settings” → “Tool Settings” → “Cross ARM C Linker” → “Libraries”. Confirm that the followings are added (Figure 4.2). If not, add the followings.

User defined archive (library) files (-l): “:lib_ble.a” User defined archive search directories (-L): "${ProjDirPath}/Device/BLE/rble_lib/lib_gcc_sotb"

Figure 4.2 Linker configuration

R01AN5606EJ0220 Rev.2.20 Page 73 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

In case of EWARM, Select [Project]→[Options…]→[Linker]→[Library]. Confirm that the [Automatic runtime library selection] is checked (Figure 4.3).

Figure 4.3 Linker configuration

(2) Register the bat files Register the bat files to switch the referred library and the linker configuration in conjunction with the configuration option of the BLE module.

In case of e2 studio, select [Project]→[Properties]→[C/C++ Build]→[Settings]→[Build Steps]. Input the following to the “Command(s)” in the “Pre-build steps”. (see Figure 4.4)

${ProjDirPath}/Device/BLE/rble_lib/lib_gcc_sotb/ble_lib_selector.bat & ${ProjDirPath}/script/ble_linker_selector.bat

Figure 4.4 Build Steps configuration

R01AN5606EJ0220 Rev.2.20 Page 74 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

In case of EWARM, select [Project]→[Options…]→[Build Actions]. Input the following to the “Pre-build command line”. (see Figure 4.5)

$PROJ_DIR$\Device\BLE\rble_lib\lib_iar_sotb\ble_lib_selector.bat & $PROJ_DIR$\config\ble_linker_selector.bat

Figure 4.5 Build Steps configuration

R01AN5606EJ0220 Rev.2.20 Page 75 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5. How to implement user code QE for BLE does not only code-generate the designed profile part but also the application processing corresponding to GAP role (Central/Peripheral) into qe_gen\ble. Once just only creating a project for each GAP role and code-generating, the mutually connectable programs are generated as app_main.c. As for the behavior of the generated program, refer to "5.1 Behavior of skeleton program".

Applications can be developed by adding/modifying user code using various APIs in the following functions of app_main.c. Some APIs, once are executed, immediately returns the result as the return value of the function, but most APIs are queued and executed as events in the scheduler, and the execution results are returned as event notifications to the event handler.

Table 5.1 Functions of app_main.c

Function of app_main.c Description app_main function The app_main function has a main loop.

The following API is used before the main loop. - Initialization API This is a required function. Register an event handler or interrupt handler as a callback function in the BLE Protocol Stack scheduler. Also register the GATT database. It is explained in "5.2.1 Initialize process (ble_init function)".

The following API is used in the main loop. - R_BLE_Execute This is a required function. Run the scheduler to handle the event and return the result to your callback function. It is explained in "5.2.2 Main loop and scheduler (R_BLE_Execute)". - R_BLE_CLI_Process Used when the command line function is enabled. - R_BLE_LPC_EnterLowPowerMode This is used when the MCU low power consumption function is enabled. Callback function Event handler Called when GAP / GATTS / GATTC / VS / Profile Server / Profile Client / L2CAP / DISC event occurs. Note: The RF communication timing notification is called from the LL → scheduler when an RF interrupt occurs. Note: The software timer is called from the CMT module → BLE Protocol Stack scheduler when a timer interrupt occurs. [Note] LED of LED and Switch control does not use notification. Switch is called from the IRQ module → BLE Protocol Stack scheduler when a switch press interrupt occurs. Interrupt handler When the command line function is enabled, it is called from the SCI module when a UART transmission/reception interrupt occurs.

If dividing the process of app_main.c into another file, right-click the src folder on e2 studio and add another file by the following procedure. Add r_ble_[arbitrary name].c from [New] → [Source File]. Add r_ble_[arbitrary name].h from [New] → [Header File]. Note: By adding the prefix "r_ble_" to the file name, you can save time of editing the linker configuration file when allocating RAM. If not adding "r_ble_" to the file name, please note to need manually editing the linker configuration file. As for details of API parameters, refer to API document (r_ble_api_spec.chm).

R01AN5606EJ0220 Rev.2.20 Page 76 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Note: Beware that files generated from QE for BLE will be regenerated each time code generation operates. To protect user code from regeneration, please implement user code inside of following comment.

/* Start user code for XXXX. Do not edit comment generated here */

Implement user code here

/* End user code. Do not edit comment generated here */

R01AN5606EJ0220 Rev.2.20 Page 77 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.1 Behavior of skeleton program The behavior of the skeleton program generated by QE for BLE and the main events to be notified are shown below. The BLE protocol stack automatically handles the dotted line responses and operations, so no code is required.

Central Peripheral (GATT Client) (GATT Server)

Power ON Power ON Stack ON Stack ON

BLE_GAP_EVENT_STACK_ON BLE_GAP_EVENT_STACK_ON

Scan with filtering using device Advertising using device name name (RBLE_DEV) (RBLE_DEV)

Advertising BLE_GAP_EVENT_ADV_REPT_IND

Connection request

Connection response

Connection establish BLE_GAP_EVENT_CONN_IND BLE_GAP_EVENT_CONN_IND BLE_GATTC_CONN_IND

Request changing maximum packet length BLE_GAP_EVENT_DATA_LEN CHG

Response changing maximum packet length BLE_GAP_EVENT_DATA_LEN CHG

Start service discovery for designed profile

Response service discovery disc_comp_cb

Complete discovery

BLE Protocol Stack automation process

QE for BLE code-generation

Figure 5.1 Behaviour of skeleton program generated by QE for BLE

R01AN5606EJ0220 Rev.2.20 Page 78 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.2 app_main function The app_main function performs initialization processing and implementation of the main loop. When using the timer, board setting, command line, etc., the initialization process is performed by the app_main function. Note: When using QE for BLE, the source code of the app_main function is automatically generated.

Code 5-1 shows an example of the app_main function.

/* CommandLine parameters */ static const st_ble_cli_cmd_t * const gsp_cmds[] = { &g_abs_cmd, &g_vs_cmd, &g_sys_cmd, &g_ble_cmd };

void app_main(void) { BLE Protocol Stack initialization (R_BLE_Open) /* Initialize BLE */ Note: Be sure to call at the beginning of the app_main function. R_BLE_Open(); Note: Be sure to call in power supply mode ALLPWON.

#if (BLE_CFG_MCU_PSM_OPE) /* MCU Power supply modes change: ALLPWON -> EXFPWON */ /* Note: EXFPWON needs to execute a program on RAM area. */ R_LPM_PowerSupplyModeExfpwonSet(); Changing MCU power supply mode R_LPM_PowerSupplyModeExfpwonSet) #endif /* (BLE_CFG_MCU_PSM_OPE) */

/* Configure the board */ R_BLE_BOARD_Init(); Board initialization (BLE_BOARD_Init)

/* Initialize the Low Power Control function */ R_BLE_LPC_Init(); MCU low Power Consumption function initialization (R_BLE_LPC_Init)

/* Initialize timer for ABS & LED blink */ R_BLE_TIMER_Init(); Application timer initialization (R_BLE_TIMER_Init) /* Configure CommandLine */ R_BLE_CLI_Init(); R_BLE_CLI_RegisterCmds(gsp_cmds, ARRAY_SIZE(gsp_cmds)); R_BLE_CMD_SetResetCb(ble_init); Command line initialization (R_BLE_CLI_Init)

/* Initialize BLE host stack and profiles */ ble_init(); Host stack and profile initialization (ble_init) /* main loop */ while (1) { /* Process Command Line */ R_BLE_CLI_Process(); /* Process Event */ Main loop (Call R_BLE_Execute, Transition to MCU low power R_BLE_Execute(); consumption state by R_BLE_LPC_EnterLowPowerMode) /* Enter the Lower Power Mode */ R_BLE_LPC_EnterLowPowerMode(); } } Code 5-1 app_main function example

R01AN5606EJ0220 Rev.2.20 Page 79 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.2.1 Initialize process (ble_init function) The ble_init function initializes the host stack and profile. Register the callback function and GATT database. Note: When using QE for BLE, the source code of the ble_init function is automatically generated.

Code 5-2 shows an example of the ble_init function.

static ble_status_t ble_init(void) { ble_status_t status;

g_conn_hdl = BLE_GAP_INVALID_CONN_HDL; gs_timer_hdl = BLE_TIMER_INVALID_HDL; Host stack initialization (R_BLE_ABS_Init) Note: When not using Abstraction API, use below. /* Initialize host stack */ R_BLE_GAP_Init status = R_BLE_ABS_Init(&gs_abs_init_param); R_BLE_VS_Init if (BLE_SUCCESS != status) R_BLE_GATTS_Init { R_BLE_GATTC_Init return BLE_ERR_INVALID_OPERATION; }

/* Initialize GATT Database */ GATT database registration (R_BLE_GATTS_SetDbInst) status = R_BLE_GATTS_SetDbInst(&g_gatt_db_table); Note: Code-generated when GATT role is set as whichever if (BLE_SUCCESS != status) Server and Client by QE for BLE. { return BLE_ERR_INVALID_OPERATION; } GATT Server function initialization (R_BLE_SERVS_Init) /* Initialize GATT Server */ Note: Code-generated when GATT role is set as whichever Server and Client by QE status = R_BLE_SERVS_Init(); for BLE. if (BLE_SUCCESS != status) { return BLE_ERR_INVALID_OPERATION; } GATT Client function initialization (R_BLE_SERVC_Init) /* Initialize GATT client */ Note: Code-generated when GATT role is set as whichever Server and Client by status = R_BLE_SERVC_Init(); QE for BLE. if (BLE_SUCCESS != status) { return BLE_ERR_INVALID_OPERATION; }

/* Initialize GATT Discovery Library */ Service Discovery function initialization (R_BLE_DISC_Init) status = R_BLE_DISC_Init(); Note: Code-generated when GAP role is set as Central by QE for BLE. if (BLE_SUCCESS != status) { return BLE_ERR_INVALID_OPERATION; } Service initialization /* Initialize LED and Switch Service */ (R_BLE_[service name]S_Init or R_BLE_[service name]C_Init) status = R_BLE_LSC_Init(lss_cb); Note: Code-generated as R_BLE_[service name]S_Init) when GATT if (BLE_SUCCESS != status) role is set as Server by QE for BLE. { Note: Code-generated as R_BLE_[service name]C_Init) when GATT return BLE_ERR_INVALID_OPERATION; role is set as Client by QE for BLE. }

/* Create timer for LED blink */ status = R_BLE_TIMER_Create(&gs_timer_hdl, 1, BLE_TIMER_PERIODIC, timer_cb); if (BLE_SUCCESS != status) { Software timer creation (R_BLE_TIMER_Create) return BLE_ERR_INVALID_OPERATION; }

return status; } Code 5-2 ble_init function example

R01AN5606EJ0220 Rev.2.20 Page 80 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.2.1.1 Registering callback function By registering the callback function in the application, it is possible to process at the reception timing of various events. Table 5.2 shows the callback registration API of each function block.

Table 5.2 Callback registration API

Function block Callback registration API Comment Registered callback function is called when receiving the result of R_BLE_ABS_Init or GAP R_BLE_GAP_XXX such as R_BLE_GAP_Init Advertising, Scan, Connection establishment and so on. GATT Server R_BLE_ABS_Init or Registered callback function is called (Profile common) R_BLE_GATTS_RegisterCb when accessed from GATT Client. GATT Client R_BLE_ABS_Init or Registered callback function is called (Profile common) R_BLE_GATTC_RegisterCb when accessed from GATT Server. Service Discovery Registered callback function is called R_BLE_DISC_Start() (Profile common) when completing Service Discovery. Registered callback function is called R_BLE_ABS_Init or Vendor Specific when receiving the result of R_BLE_VS_Init R_BLE_VS_XXX. Registered callback function is called when receiving the result of R_BLE_L2CAP_XXX such as that the response of L2CAP Credit-Based L2CAP R_BLE_L2CAP_RegisterCfPsm() Flow Control request is received, L2CAP Credit-Based Flow Control is received and so on. Note: Not code-generated by QE for BLE. Registered callback function is called when receiving the result of R_BLE_BOARD_XXX such as that LED and Switch R_BLE_BOARD_RegisterSwitchCb() the board switch is pushed and so control on. Note: Not code-generated by QE for BLE. Registered callback function is called when receiving the result of R_BLE_TIMER_XXX such as that the Software timer R_BLE_TIMER_Create() specifying time has passed and so on. Note: Not code-generated by QE for BLE. Server side profile R_BLE_XXXS_Init() Registered callback function is called API (XXX is Service name) when accessed from Client. R_BLE_XXXC_Init() Registered callback function is called Client side profile API (XXX is Service name) when accessed from Server.

Note: R_BLE_ABS_Init can register GAP, GATT Server, GATT Client, and VS callback functions together.

R01AN5606EJ0220 Rev.2.20 Page 81 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.2.1.2 Registering GATT database (R_BLE_GATTS_SetDbInst) When creating a GATT service application that operates as a GATT server, QE for BLE generates a service database code in the following file.

⚫ gatt_db.c ⚫ gatt_db.h

This GATT database is registered in the application by R_BLE_GATTS_SetDbInst.

R01AN5606EJ0220 Rev.2.20 Page 82 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.2.2 Main loop and scheduler (R_BLE_Execute) BLE Protocol Stack uses a scheduler to process the API called by the application. Please call R_BLE_Execute in the main loop to operate the scheduler. The event that occurred is notified to the registered callback function.

The scheduler processes the task according to the message queue sent to the task of each layer of BLE Protocol Stack by R_BLE_Execute. Figure 5.2 shows the basic sequence chart of BLE Protocol Stack.

Source Code Library Software Hardware BLE Protcol Stack

Application R_BLE API Scheduler Host Stack Link Layer(LL) BLE H/W

Call R_BLE API Send Message to Host Stack

return R_BLE API Function Call return Call R_BLE_Execute() Execute Task Send Message Send Message to LL Access BLE H/W return

BLE Interrupt Execute Task Access BLE H/W Send Message to Host Stack return

Execute Task

callback R_BLE event callback

return return return

return R_BLE_Execute()

BLE Interrupt Send Message to LL Call R_BLE_Execute() Execute Task Access BLE H/W Send Message to Host Stack

return

Execute Task

callback R_BLE event callback

return return return

return R_BLE_Execute()

Figure 5.2 Basic sequence chart of BLE Protocol Stack

R01AN5606EJ0220 Rev.2.20 Page 83 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.3 GAP event (gap_cb function) GAP callback function receives following events.

enum e_ble_gap_evt_t { BLE_GAP_EVENT_INVALID = 0x1001, BLE_GAP_EVENT_STACK_ON, BLE_GAP_EVENT_STACK_OFF, BLE_GAP_EVENT_LOC_VER_INFO, BLE_GAP_EVENT_HW_ERR, BLE_GAP_EVENT_CMD_ERR = 0x1101, BLE_GAP_EVENT_ADV_REPT_IND, BLE_GAP_EVENT_ADV_PARAM_SET_COMP, BLE_GAP_EVENT_ADV_DATA_UPD_COMP, BLE_GAP_EVENT_ADV_ON, BLE_GAP_EVENT_ADV_OFF, BLE_GAP_EVENT_PERD_ADV_PARAM_SET_COMP, BLE_GAP_EVENT_PERD_ADV_ON, BLE_GAP_EVENT_PERD_ADV_OFF, BLE_GAP_EVENT_ADV_SET_REMOVE_COMP, BLE_GAP_EVENT_SCAN_ON, BLE_GAP_EVENT_SCAN_OFF, BLE_GAP_EVENT_SCAN_TO, BLE_GAP_EVENT_CREATE_CONN_COMP, BLE_GAP_EVENT_CONN_IND, BLE_GAP_EVENT_DISCONN_IND, BLE_GAP_EVENT_CONN_CANCEL_COMP, BLE_GAP_EVENT_WHITE_LIST_CONF_COMP, BLE_GAP_EVENT_RAND_ADDR_SET_COMP, BLE_GAP_EVENT_CH_MAP_RD_COMP, BLE_GAP_EVENT_CH_MAP_SET_COMP, BLE_GAP_EVENT_RSSI_RD_COMP, BLE_GAP_EVENT_GET_REM_DEV_INFO, BLE_GAP_EVENT_CONN_PARAM_UPD_COMP, BLE_GAP_EVENT_CONN_PARAM_UPD_REQ, BLE_GAP_EVENT_AUTH_PL_TO_EXPIRED, BLE_GAP_EVENT_SET_DATA_LEN_COMP, BLE_GAP_EVENT_DATA_LEN_CHG, BLE_GAP_EVENT_RSLV_LIST_CONF_COMP, BLE_GAP_EVENT_RPA_EN_COMP, BLE_GAP_EVENT_SET_RPA_TO_COMP, BLE_GAP_EVENT_RD_RPA_COMP, BLE_GAP_EVENT_PHY_UPD, BLE_GAP_EVENT_PHY_SET_COMP, BLE_GAP_EVENT_DEF_PHY_SET_COMP, BLE_GAP_EVENT_PHY_RD_COMP, BLE_GAP_EVENT_SCAN_REQ_RECV, BLE_GAP_EVENT_CREATE_SYNC_COMP, BLE_GAP_EVENT_SYNC_EST, BLE_GAP_EVENT_SYNC_TERM, BLE_GAP_EVENT_SYNC_LOST, BLE_GAP_EVENT_SYNC_CREATE_CANCEL_COMP, BLE_GAP_EVENT_PERD_LIST_CONF_COMP, BLE_GAP_EVENT_PRIV_MODE_SET_COMP, BLE_GAP_EVENT_PAIRING_REQ = 0x1401, BLE_GAP_EVENT_PASSKEY_ENTRY_REQ, BLE_GAP_EVENT_PASSKEY_DISPLAY_REQ, BLE_GAP_EVENT_NUM_COMP_REQ, BLE_GAP_EVENT_KEY_PRESS_NTF, BLE_GAP_EVENT_PAIRING_COMP, BLE_GAP_EVENT_ENC_CHG, BLE_GAP_EVENT_PEER_KEY_INFO, BLE_GAP_EVENT_EX_KEY_REQ, BLE_GAP_EVENT_LTK_REQ, BLE_GAP_EVENT_LTK_RSP_COMP, BLE_GAP_EVENT_SC_OOB_CREATE_COMP }

R01AN5606EJ0220 Rev.2.20 Page 84 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Reception condition of the frequently occurring events are shown below.

Table 5.3 Frequently occurring event of GAP callback

Event Reception condition BLE_GAP_EVENT_STACK_ON(0x1001) Complete R_BLE_GAP_Init BLE_GAP_EVENT_ADV_PARAM_SET_COMP(0x1003) Complete R_BLE_GAP_SetAdvParam BLE_GAP_EVENT_ADV_DATA_UPD_COMP (0x1004) Complete R_BLE_GAP_SetAdvSresData BLE_GAP_EVENT_ADV_ON (0x1005) Start Advertising BLE_GAP_EVENT_ADV_OFF (0x1006) End Advertising BLE_GAP_EVENT_SCAN_ON (0x1111) Start Scan BLE_GAP_EVENT_SCAN_OFF (0x1112) End Scan BLE_GAP_EVENT_CONN_IND (0x1115) Start Connection BLE_GAP_EVENT_CONN_IND (0x1115) End Connection BLE_GAP_EVENT_DISCONN_IND (0x1116) End Disconnection

GAP callback function is following.

static void gap_cb(uint16_t type, ble_status_t result, st_ble_evt_data_t *p_data) { ble_app_gapcb(type, result, p_data);

switch(type) { /* TODO: Set callback events of GAP. Check BLE API reference for events. */ Note: Add processing when an event is received here.

Code 5-3 GAP callback function

R01AN5606EJ0220 Rev.2.20 Page 85 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.4 GATTS event (gatts_cb function) GATT server (GATTS) callback function receives following events.

enum e_r_ble_gatts_evt_t { BLE_GATTS_EVENT_EX_MTU_REQ = 0x3002, BLE_GATTS_EVENT_READ_BY_TYPE_RSP_COMP = 0x3009, BLE_GATTS_EVENT_READ_RSP_COMP = 0x300B, BLE_GATTS_EVENT_READ_BLOB_RSP_COMP = 0x300D, BLE_GATTS_EVENT_READ_MULTI_RSP_COMP = 0x300F, BLE_GATTS_EVENT_WRITE_RSP_COMP = 0x3013, BLE_GATTS_EVENT_PREPARE_WRITE_RSP_COMP = 0x3017, BLE_GATTS_EVENT_EXE_WRITE_RSP_COMP = 0x3019, BLE_GATTS_EVENT_HDL_VAL_CNF = 0x301E, BLE_GATTS_EVENT_DB_ACCESS_IND = 0x3040, BLE_GATTS_EVENT_CONN_IND = 0x3081, BLE_GATTS_EVENT_DISCONN_IND = 0x3082, BLE_GATTS_EVENT_INVALID = 0x30FF }

Reception condition of frequently occurring events are shown below.

Table 5.4 Frequently occurring events of GATTS callback

Event Reception condition BLE_GATTS_EVENT_CONN_IND(0x3081) Establish Connection Changing MTU is requested from GATT Client BLE_GATTS_EVENT_EX_MTU_REQ(0x3002) after Connection BLE_GATTS_EVENT_DB_ACCESS_IND(0x3040) Accessed to GATT database BLE_GATTS_EVENT_READ_BY_TYPE_RSP_COMP(0x3009) Complete sending Read By Type Response BLE_GATTS_EVENT_WRITE_RSP_COMP(0x3013) Complete sending Write Response Complete receiving Confirmation from GATT BLE_GATTS_EVENT_HDL_VAL_CNF(0x301E) Client BLE_GATTS_EVENT_DISCONN_IND(0x3082) End Disconnection

GATTS callback function is following.

static void gatts_cb(uint16_t type, ble_status_t result, st_ble_gatts_evt_data_t *p_data) { R_BLE_SERVS_GattsCb(type, result, p_data);

switch(type) { /* TODO: Set callback events of GATTS. Check BLE API reference for events. */ Note: Add processing when an event is received here.

Code 5-4 GATTS callback function

R01AN5606EJ0220 Rev.2.20 Page 86 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.5 GATTC event (gattc_cb function) GATT client (GATTC) callback function receives following events.

enum e_r_ble_gattc_evt_t { BLE_GATTC_EVENT_ERROR_RSP = 0x4001, BLE_GATTC_EVENT_EX_MTU_RSP = 0x4003, BLE_GATTC_EVENT_CHAR_READ_BY_UUID_RSP = 0x4009, BLE_GATTC_EVENT_CHAR_READ_RSP = 0x400B, BLE_GATTC_EVENT_CHAR_PART_READ_RSP = 0x400D, BLE_GATTC_EVENT_MULTI_CHAR_READ_RSP = 0x400F, BLE_GATTC_EVENT_CHAR_WRITE_RSP = 0x4013, BLE_GATTC_EVENT_CHAR_PART_WRITE_RSP = 0x4017, BLE_GATTC_EVENT_HDL_VAL_NTF = 0x401B, BLE_GATTC_EVENT_HDL_VAL_IND = 0x401D, BLE_GATTC_EVENT_CONN_IND = 0x4081, BLE_GATTC_EVENT_DISCONN_IND = 0x4082, BLE_GATTC_EVENT_PRIM_SERV_16_DISC_IND = 0x40E0, BLE_GATTC_EVENT_PRIM_SERV_128_DISC_IND = 0x40E1, BLE_GATTC_EVENT_ALL_PRIM_SERV_DISC_COMP = 0x40E2, BLE_GATTC_EVENT_PRIM_SERV_DISC_COMP = 0x40E3, BLE_GATTC_EVENT_SECOND_SERV_16_DISC_IND = 0x40E4, BLE_GATTC_EVENT_SECOND_SERV_128_DISC_IND = 0x40E5, BLE_GATTC_EVENT_ALL_SECOND_SERV_DISC_COMP = 0x40E6, BLE_GATTC_EVENT_INC_SERV_16_DISC_IND = 0x40E7, BLE_GATTC_EVENT_INC_SERV_128_DISC_IND = 0x40E8, BLE_GATTC_EVENT_INC_SERV_DISC_COMP = 0x40E9, BLE_GATTC_EVENT_CHAR_16_DISC_IND = 0x40EA, BLE_GATTC_EVENT_CHAR_128_DISC_IND = 0x40EB, BLE_GATTC_EVENT_ALL_CHAR_DISC_COMP = 0x40EC, BLE_GATTC_EVENT_CHAR_DISC_COMP = 0x40ED, BLE_GATTC_EVENT_CHAR_DESC_16_DISC_IND = 0x40EE, BLE_GATTC_EVENT_CHAR_DESC_128_DISC_IND = 0x40EF, BLE_GATTC_EVENT_ALL_CHAR_DESC_DISC_COMP = 0x40F0, BLE_GATTC_EVENT_LONG_CHAR_READ_COMP = 0x40F1, BLE_GATTC_EVENT_LONG_CHAR_WRITE_COMP = 0x40F2, BLE_GATTC_EVENT_RELIABLE_WRITES_TX_COMP = 0x40F3, BLE_GATTC_EVENT_RELIABLE_WRITES_COMP = 0x40F4, BLE_GATTC_EVENT_INVALID = 0x40FF }

Reception condition of frequently occurring events are shown below.

Table 5.5 Frequently occurring events of GATTC callback

Event Reception condition BLE_GATTC_EVENT_CONN_IND(0x4081) Establish Connection Request Changing MTU to GATT Server after Connection and BLE_GATTC_EVENT_EX_MTU_RSP(0x4003) receive normal response BLE_GATTC_EVENT_ERROR_RSP(0x4001) Receive error response from GATT Server BLE_GATTC_EVENT_HDL_VAL_NTF(0x401B) Complete receiving Notification BLE_GATTC_EVENT_HDL_VAL_IND(0x401D) Complete receiving Indication BLE_GATTC_EVENT_DISCONN_IND(0x4082) End Disconnection

GATTC callback function is following.

static void gattc_cb(uint16_t type, ble_status_t result, st_ble_gattc_evt_data_t *p_data) { R_BLE_SERVC_GattcCb(type, result, p_data);

switch(type) { /* TODO: Set callback events of GATTC. Check BLE API reference for events. */ Note: Add processing when an event is received here. Code 5-5 GATTC callback function

R01AN5606EJ0220 Rev.2.20 Page 87 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.6 VS event (vs_cb function) Vender specific (VS) callback function receives following events.

enum e_r_ble_vs_evt_t { BLE_VS_EVENT_SET_TX_POWER = 0x8001, BLE_VS_EVENT_GET_TX_POWER = 0x8002, BLE_VS_EVENT_TX_TEST_START = 0x8003, BLE_VS_EVENT_TX_TEST_TERM = 0x8004, BLE_VS_EVENT_RX_TEST_START = 0x8005, BLE_VS_EVENT_TEST_END = 0x8006, BLE_VS_EVENT_SET_CODING_SCHEME_COMP = 0x8007, BLE_VS_EVENT_RF_CONTROL_COMP = 0x8008, BLE_VS_EVENT_SET_ADDR_COMP = 0x8009, BLE_VS_EVENT_GET_ADDR_COMP = 0x800A, BLE_VS_EVENT_GET_RAND = 0x800B, BLE_VS_EVENT_TX_FLOW_STATE_CHG = 0x800C, BLE_VS_EVENT_FAIL_DETECT = 0x800D, BLE_VS_EVENT_SET_SCAN_CH_MAP = 0x800E, BLE_VS_EVENT_GET_SCAN_CH_MAP = 0x800F, BLE_VS_EVENT_INVALID = 0x80FF }

Reception condition of frequently occurring events are shown below.

Table 5.6 Frequently occurring events of VS callback

Event Reception condition BLE_VS_EVENT_SET_TX_POWER(0x8001) Complete R_BLE_VS_SetTxPower BLE_VS_EVENT_GET_TX_POWER(0x8002) Complete R_BLE_VS_GetTxPower BLE_VS_EVENT_SET_ADDR_COMP(0x8009) Complete R_BLE_VS_SetBdAddr BLE_VS_EVENT_GET_ADDR_COMP(0x800A) Complete R_BLE_VS_GetBdAddr

VS callback function is following.

static void vs_cb(uint16_t type, ble_status_t result, st_ble_vs_evt_data_t *p_data) { R_BLE_SERVS_VsCb(type, result, p_data);

switch(type) { /* TODO: Set callback events of VS. Check BLE API reference for events. */ Note: Add processing when an event is received here.

Code 5-6 VS callback function

R01AN5606EJ0220 Rev.2.20 Page 88 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.7 Server-side Profile API event ([service_name]s_cb function) Callback function of the server-side Profile API receives following events.

enum e_ble_servs_event_t { BLE_SERVS_WRITE_REQ = 0x00, BLE_SERVS_WRITE_CMD = 0x01, BLE_SERVS_WRITE_COMP = 0x02, BLE_SERVS_READ_REQ = 0x03, BLE_SERVS_HDL_VAL_CNF = 0x04 }

enum e_ble_[service name]s_event_t { BLE_[service name]S_EVENT_[characteristic name]_WRITE_REQ = 0xXX00, BLE_[service name]S_EVENT_[characteristic name]_WRITE_CMD= 0xXX01, BLE_[service name]S_EVENT_[characteristic name]_WRITE_COMP = 0xXX02, BLE_[service name]S_EVENT_[characteristic name]_READ_REQ = 0xXX03, BLE_[service name]S_EVENT_[characteristic name]_HDL_VAL_CNF = 0xXX04, BLE_[service name]S_EVENT_[characteristic name]_[descriptor name]_WRITE_REQ = 0xYY00, BLE_[service name]S_EVENT_[characteristic name]_[descriptor name]_READ_REQ = 0xYY03, : : }

Note: The 10th to 15th bits are serial numbers that distinguish attributes (characteristics and descriptors). XX and YY are 00, 04, 08, 10, ..., FC.

Reception condition of frequently occurring events are shown below.

Table 5.7 Frequently occurring events of Profile Server callback

Event Reception condition XXX_WRITE_REQ (0xXXX0) Complete receiving Write Request XXX_WRITE_CMD (0xXXX1) Complete receiving Write Without Response XXX_WRITE_COMP (0xXXX2) Complete sending Write Response XXX_READ_REQ (0xXXX3) Complete receiving Read Request XXX_HDL_VAL_CNF (0xXXX4) Complete receiving Confirmation

Callback function of server-side profile API is following. (Example of ls service)

static void lss_cb(uint16_t type, ble_status_t result, st_ble_servs_evt_data_t *p_data) { switch(type) { Note: Add processing when an event is received here.

Code 5-7 Profile Server callback function

R01AN5606EJ0220 Rev.2.20 Page 89 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.8 Client-side Profile API event ([service_name]c_cb function) Callback function of the client-side profile API receives following events.

enum e_ble_servc_event_t { BLE_SERVC_WRITE_RSP, BLE_SERVC_READ_RSP, BLE_SERVC_HDL_VAL_NTF, BLE_SERVC_HDL_VAL_IND }

enum e_ble_[service name]c_event_t { BLE_[service name]C_EVENT_[characteristic name]_WRITE_RSP = 0xXX00, BLE_[service name]C_EVENT_[characteristic name]_READ_RSP= 0xXX01, BLE_[service name]C_EVENT_[characteristic name]_HDL_VAL_NTF = 0xXX02, BLE_[service name]C_EVENT_[characteristic name]_HDL_VAL_IND = 0xXX03, BLE_[service name]C_EVENT_[characteristic name]_[descriptor name]_WRITE_RSP = 0xYY00, BLE_[service name]C_EVENT_[characteristic name]_[descriptor name]_READ_RSP = 0xYY01, : : }

Note: The 10th to 15th bits are serial numbers that distinguish attributes (characteristics and descriptors). XX and YY are 00, 04, 08, 10, ..., FC.

Reception condition of the frequently occurring events are shown below.

Table 5.8 Frequently occurring events of Profile Client callback

Event Reception condition XXX_WRITE_RSP (0xXXX0) Complete receiving Write Response XXX_READ_RSP (0xXXX1) Complete receiving Read Response XXX_HDL_VAL_NTF (0xXXX2) Complete receiving Notification XXX_HDL_VAL_IND (0xXXX3) Complete receiving Indication

Callback function of client-side profile API is following. (Example of ls service)

static void lsc_cb(uint16_t type, ble_status_t result, st_ble_servc_evt_data_t *p_data) { (void)result; (void)p_data;

switch (type) { /* TODO: Set callback events of lsc. Check BLE API reference or e_ble_lsc_event_t for events. */ Note: Add processing when an event is received here.

Code 5-8 Profile Client callback function

R01AN5606EJ0220 Rev.2.20 Page 90 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.9 L2CAP event L2CAP callback function receives following events.

enum e_r_ble_l2cap_cf_evt_t { BLE_L2CAP_EVENT_CF_CONN_CNF = 0x5001, BLE_L2CAP_EVENT_CF_CONN_IND = 0x5002, BLE_L2CAP_EVENT_CF_DISCONN_CNF = 0x5003, BLE_L2CAP_EVENT_CF_DISCONN_IND = 0x5004, BLE_L2CAP_EVENT_CF_RX_DATA_IND = 0x5005, BLE_L2CAP_EVENT_CF_LOW_RX_CRD_IND = 0x5006, BLE_L2CAP_EVENT_CF_TX_CRD_IND = 0x5007, BLE_L2CAP_EVENT_CF_TX_DATA_CNF = 0x5008, BLE_L2CAP_EVENT_CMD_REJ = 0x5009 }

L2CAP callback function is following.

static void l2cap_cb(uint16_t type, ble_status_t result, st_ble_l2cap_cf_evt_data_t *p_data) { switch (type) { Note: Add processing when an event is received here.

Code 5-9 L2CAP callback function

R01AN5606EJ0220 Rev.2.20 Page 91 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.10 Event notification function (R_BLE_SetEvent) Calling R_BLE_SetEvent enables to queue events to the scheduler of BLE Protocol Stack. BLE Protocol Stack checks the event status with R_BLE_Execute, if the event is queued, calls the callback function registered with R_BLE_SetEvent. Note: The maximum number of events that can be queued is 8.

This function is mainly used in the following cases. ⚫ The time-consuming processing in the interrupt handler should be executed outside the interrupt handler. Note: RF control processing of BLE Protocol Stack is processed by MCU with high priority. To reduce the impact on RF control processing, it is recommended that the application processing time is short (recommended time is within 30% of RF idle time after completion of RF event processing). Use R_BLE_SetEvent to divide long-time processing into multiple callbacks and execute. ⚫ The function that cannot be executed in the interrupt handler should be called outside the interrupt handler.

The sequence chart of R_BLE_SetEvent is shown below.

Source Code Library Software Hardware BLE Protcol Stack

Application R_BLE API Scheduler Host Stack Link Layer(LL) BLE H/W

Call R_BLE SetEvent Send Message to Host Stack

return R_BLE SetEvent Function Call return Call R_BLE_Execute() Send Message Execute Task Access BLE H/W callback R_BLE event callback BLE Interrupt return return return

return R_BLE_Execute()

Figure 5.3 Sequence chart of R_BLE_SetEvent

Code 5-10 shows a sample of turning on/off the LED between RF control processing (Advertising). In order to reduce the influence on the next Advertising, the event is queued at the end of Advertising and the LED is turned on and off.

[Device\BLE\platform\r_ble_pf_functions.c] extern void sw_ntf_recv_event(void); void r_ble_rf_notify_event_close(uint32_t param) { /* Note: Do not processing long time here. */ switch( (uint16_t)(param>>16) ) { case BLE_EVENT_TYPE_ADV: { R_BLE_SetEvent( sw_ntf_recv_event ); } break;

R01AN5606EJ0220 Rev.2.20 Page 92 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

} }

[app_main.c] #include "board/r_ble_board.h"

void sw_ntf_recv_event(void) { R_BLE_BOARD_ToggleLEDState(BLE_BOARD_LED1); }

void app_main(void) { /* Configure the board */ R_BLE_BOARD_Init();

Note: LED and Switch control function is used. Set BLE_CFG_BOARD_LED_SW_EN to 1. Note: RF communication timing notification function is used. Change BLE_CFG_EVENT_NOTIFY_ADV_CLOSE to 1. Code 5-10 Event notification example (1)

Code 5-11 shows a sample of queuing an event from the interrupt handler sw_cb and turning on/off the LED when SW2 is pressed.

[app_main.c] #include "board/r_ble_board.h"

void sw_ntf_recv_event(void) { R_BLE_BOARD_ToggleLEDState(BLE_BOARD_LED1); }

static void sw_cb(void) { R_BLE_SetEvent( sw_ntf_recv_event ); }

void app_main(void) { /* Configure the board */ R_BLE_BOARD_Init(); R_BLE_BOARD_RegisterSwitchCb(BLE_BOARD_SW2, sw_cb);

Note: LED and Switch control function is used. Set BLE_CFG_BOARD_LED_SW_EN to 1. Code 5-11 Event notification example (2)

R01AN5606EJ0220 Rev.2.20 Page 93 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 5.11 RF communication timing notification In order to perform application development synchronized with RF event, it is necessary to use "5.10 Event notification function (R_BLE_SetEvent)" and the RF communication timing notification function. Refer to “6.1 RF communication timing notification” as for how to use RF communication timing notification function.

The sequence chart of RF communication timing notification is shown below.

Source Code Library Software Hardware BLE Protcol Stack

Application R_BLE API Scheduler Host Stack Link Layer(LL) BLE H/W

Call R_BLE API Send Message to Host Stack

return R_BLE API Function Call return Call R_BLE_Execute() Execute Task Send Message Send Message to LL Access BLE H/W return

BLE Interrupt Execute Task Access BLE H/W Send Message to Host Stack return

Execute Task

callback R_BLE event callback

return return return

return R_BLE_Execute()

BLE Interrupt Send Message to LL Call R_BLE_Execute() Execute Task Access BLE H/W Send Message to Host Stack

r_ble_event_notify_xxx callback

return

return

Execute Task

callback R_BLE event callback

return return return

return R_BLE_Execute()

Figure 5.4 Sequence chart of RF communication timing notification

R01AN5606EJ0220 Rev.2.20 Page 94 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 6. Optional function 6.1 RF communication timing notification

The RF communication timing notification function notifies the user application layer of the timing before and after BLE RF communication is performed with a callback. Callback notification before and after transition to RF sleep mode can also be performed. For the RF communication timing notification feature, you can select the BLE RF event type to be executed and whether to enable or disable the timing notification at before and after BLE RF event. Note: This function performs a callback within the BLE Protocol Stack software task processing. Therefore, callback notification is delayed from the actual RF communication timing. In addition, the delay time may not be constant depending on the operating frequency of the MCU, the interrupts of other peripheral functions, and the processing contents of the user application.

Table 6.1 shows the event types that can be notified.

Table 6.1 RF communication timing notification event type Event Types Description Connection event start / event close Callback notification at start or close of the Connection event. • BLE_CFG_EVENT_NOTIFY_CONN_START • BLE_CFG_EVENT_NOTIFY_CONN_CLOSE Advertising event start / event close Callback notification at start or close of the Advertising event. • BLE_CFG_EVENT_NOTIFY_ADV_START • BLE_CFG_EVENT_NOTIFY_ADV_CLOSE Scan event start / event close Callback notification at start or close of the Scan event. If Scan Interval is the same value as Scan Window, callback notification is not performed. • BLE_CFG_EVENT_NOTIFY_SCAN_START • BLE_CFG_EVENT_NOTIFY_SCAN_CLOSE Initiator event start / event close Callback notification at start or close of the Initiator event. If Scan Interval is the same value as Scan Window, callback notification is not performed. • BLE_CFG_EVENT_NOTIFY_INIT_START • BLE_CFG_EVENT_NOTIFY_INIT_CLOSE RF sleep mode start / wakeup Callback notification at start or wakeup of the RF sleep mode. • BLE_CFG_EVENT_NOTIFY_DS_START • BLE_CFG_EVENT_NOTIFY_DS_WAKEUP

Refer to "3.3 Configuration options" for an overview of each option.

R01AN5606EJ0220 Rev.2.20 Page 95 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

6.1.1 Connection event notification timing

The Connection event notification is callback at the RF communication timing for each Connection Interval. Figure 6.1 shows the connection event notification timing.

Connection Interval

Master Tx Rx Tx Rx

Start Start

Close Close

Connection Event Connection Event Connection Event Connection Event Connection

Connection Interval

Slave Rx Tx Rx Tx

Start Start

Close Close

Connection Event Connection Event Connection Event Connection Connection Event Connection Figure 6.1 Connection event notification timing

R01AN5606EJ0220 Rev.2.20 Page 96 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

6.1.2 Advertising event notification timing

The Advertising event notification is callback at the RF communication timing for each Advertising Interval. Figure 6.2 shows the advertising event notification timing.

Advertising Interval

37ch 38ch 39ch 37ch 38ch 39ch

Tx Rx Tx Rx Tx Rx Tx Rx Tx Rx Tx Rx

Start Start

Close Close

Advertising Event Advertising Advertising Event Event Advertising Advertising Event Figure 6.2 Advertising event notification timing

6.1.3 Scan / Initiator event notification timing

The Scan / Initiator event notification is callback at the RF communication timing for each Scan Interval. Figure 6.3 shows the Scan / Initiator event notification timing. Note: If Scan Interval is the same value as Scan Window, callback notification is not performed.

Scan Interval Scan Interval Scan Interval

Scan Window Scan Window Scan Window

37ch 38ch 39ch

Rx Rx Rx

Start Start Start

Close Close Close

Scan Event Scan Event Scan Event Scan Event Scan Event Scan Event Scan

Figure 6.3 Scan / Initiator event notification timing

R01AN5606EJ0220 Rev.2.20 Page 97 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

6.1.4 RF sleep mode event notification timing

When BLE_CFG_RF_DEEP_SLEEP_EN macro is set to 1 (Enable) and the time until the next RF event is longer than a certain time, the RF sleep mode transition is performed in the scheduler of the BLE Protocol Stack. The RF sleep mode event notification is callback when there is an RF sleep mode state transition between each RF events. Figure 6.4 shows the RF sleep mode event notification timing during Advertising execution.

Advertising Interval

37ch 38ch 39ch 37ch 38ch 39ch

Tx Rx Tx Rx Tx Rx Tx Rx Tx Rx Tx Rx

Start Start Start Start

Close Close

Wakeup Wakeup

RF Sleep Mode Sleep RF Mode Sleep RF Mode Sleep RF Mode Sleep RF

Advertising Event Advertising Advertising Event Event Advertising Advertising Event Figure 6.4 RF sleep mode event notification timing during Advertising

R01AN5606EJ0220 Rev.2.20 Page 98 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

6.1.5 RF communication timing notification specifications

The timing notification callback function is registered in r_ble_pf_functions.c. Add processing within each callback function as necessary. Note: When processing with a large cycle is added, the throughput performance may be affected.

Table 6.2 outlines the RF communication timing notification callback function. Table 6.2 RF communication timing notification callback functions Callback functions Description void r_ble_rf_notify_event_start(uint32_t Notification callback function for each RF event start. param) Parameter: uint32_t param [31:16] Event type (see Table 6.3) [15: 0] Event identification code (see Table 6.4) void r_ble_rf_notify_event_close(uint32_t Notification callback function for each RF event close. param) Parameter: uint32_t param [31:16] Event type (see Table 6.3) [15: 0] Event identification code (see Table 6.4) void r_ble_rf_notify_deep_sleep(uint32_t Notification callback function for RF sleep mode start/wakeup param) event. Parameter: uint32_t param 0x1: RF sleep mode wakeup (return from RF sleep mode) 0x0: RF sleep mode start (transition to RF sleep mode)

Table 6.3 RF communication event type definition macros Event Type Macro Name Defined Value Connection event BLE_EVENT_TYPE_CONN 0x0000 Advertising event BLE_EVENT_TYPE_ADV 0x0001 Scan event BLE_EVENT_TYPE_SCAN 0x0002 Initiator event BLE_EVENT_TYPE_INITIATOR 0x0003

Table 6.4 RF communication event identification code Event Type Identification code Connection event Set the executed connection handle (conn_hdl). Advertising event Set the executed advertising handle (adv_hdl). Scan event Set 0x0000 Initiating event Set 0x0000

R01AN5606EJ0220 Rev.2.20 Page 99 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 6.2 Device-specific Data Management Bluetooth Device Address (hereinafter referred to as BD address) used by BLE Protocol Stack can be written as device-specific data in the code flash memory. This allows user to set different BD address for multiple devices using the same firmware. Device-specific data is placed in a different area from the firmware program area. If the device-specific data is not deleted when rewriting the firmware, the same BD address can be used continuously. If the device- specific data is deleted, determine the BD address according to “6.2.4 BD address adoption flow”.

6.2.1 Specifying Device-specific data location block The block number of the code flash memory where device-specific data is located can be specified with the BLE_CFG_DEV_DATA_CF_BLOCK configuration options. The block number of the code flash memory is block 0 at beginning of address (0x00000000) and block 383 at end of address (0x0017F000). Figure 6.5 shows the code flash memory block configuration.

Figure 6.5 Flash memory block configuration

When placing device-specific data in the code flash memory, it is necessary to specify blocks that are not used in program code. In addition, it is necessary to write device-specific data to the top address in specified user area block. When using MCU Startup Area Select function, do not place device-specific data in blocks 0 to 15 of the code flash memory.

R01AN5606EJ0220 Rev.2.20 Page 100 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 6.2.2 Device-specific data format Table 6.5 shows the device-specific data format. Table 6.5 device-specific data format Offset Size[bytes] Type Description 0 4 uint32_t Data length after magic number (fixed to 0x00000010) 4 4 uint32_t Magic number (fixed 0x12345678) 8 6 uint8_t [6] Public BD address 14 6 uint8_t [6] Random BD address

Each data must be written in little endian. For example, if BD address is “01:02:03:04:05:06”, write to the flash memory in the order of 0x06,0x05,0x04,0x03,0x02,0x01. Figure 6.6 shows an example of device-specific data flash memory layout.

Data Length 0x00000010 Magic Number 0x12345678 Public BD Address 01:02:03:04:05:06 Random BD Address D1:D2:D3:D4:D5:D6

offset +0 +1 +2 +3 +4 +5 +6 +7 0x0000 0x10 0x00 0x00 0x00 0x78 0x56 0x34 0x12 0x0008 0x06 0x05 0x04 0x03 0x02 0x01 0xD6 0xD5

0x0010 0xD4 0xD3 0xD2 0xD1 ...... Figure 6.6 Device-specific data flash memory layout

6.2.3 Writing to the code flash memory To write device-specific data to the code flash memory, use Renesas Flash Programmer (RFP) unique code function to write to the code flash memory at the same time as firmware program data. Figure 6.7 shows an overview of writing device-specific data using RFP.

Figure 6.7 Writing device-specific data using RFP

R01AN5606EJ0220 Rev.2.20 Page 101 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Figure 6.8 shows an example of setting device-specific data for RFP Unique Code (ruc) file. format hex area user flash ROM address of the block specified by address 0x17F000 BLE_CFG_DEV_DATA_CF_BLOCK size 20 index data 000001 1000000078563412060504030201D6D5D4D3D2D1 000002 10000000785634120C0B0A090807E6E5E4E3E2E1

Index Data Magic Public Random Length Number BD address BD address (Fixed) (Fixed) (Unique) (Unique)

Figure 6.8 Setting device-specific data for RFP Unique Code

R01AN5606EJ0220 Rev.2.20 Page 102 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 6.2.4 BD address adoption flow BLE Protocol Stack adopts initial value of BD address in following priority order in R_BLE_Open() API. (1) Code flash memory specified block (2) Firmware initial value (BLE_CFG_RF_DEB_PUB_ADDR or BLE_CFG_RF_DEB_RAND_ADDR)

For Random BD address, if BD addresses for all areas are not specified, static address is generated from Unique ID of MCU. Generated static address can be get with the R_BLE_VS_GetBdAddr() API. Note: The generated static address is a fixed value that does not change when the MCU power off or reset. Note: A static address consists of random numbers. The possibility of duplicate values with other devices is not zero.

Even after BD address is adopts, the BD address can be changed again with R_BLE_VS_SetBdAddr() API. Figure 6.9 shows BD address adoption flow of BLE Protocol Stack.

Figure 6.9 BD address adoption flow of BLE Protocol Stack

Since BLE Protocol Stack does not check format of BD address written in each area (1)-(2), when setting static address, set value that matches the format shown in Figure 6.10.

Figure 6.10 Static address format

R01AN5606EJ0220 Rev.2.20 Page 103 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 7. HCI Mode HCI (Host Controller Interface) mode is firmware for RF characteristics evaluation or BTTS (Bluetooth Test Tool Suite: R01AN4554). BLE communication can be performed by sending HCI commands from the host device connected to the serial interface such as a PC to the MCU. HCI event corresponding to BLE communication is sent from MCU to the host device. HCI mode conforms to Bluetooth Core Spec ver5.0.

Figure 7.1 HCI mode evaluation board and PC connection

7.1 Software Structure Figure 7.2 shows the HCI mode software structure. User applications cannot be implemented in HCI mode.

Host Device

(e.g. Windows PC, RF Tester) UART BLE Protocol Stack(HCI mode)

UART Driver Scheduler

HCI Transport

Link Layer

HCI

Figure 7.2 HCI mode software structure

R01AN5606EJ0220 Rev.2.20 Page 104 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 7.2 Project configuration

7.3 UART-HCI Driver In HCI mode, UART (Universal Asynchronous Receiver/Transmitter) communication is performed using MCU Serial Communication Interface (SCI) peripheral functions. In HCI mode, dedicated UART-HCI driver is prepared and UART-HCI driver APIs are used from BLE Protocol Stack. Table 7.1 shows the UART-HCI driver file contents in HCI mode.

Table 7.1 UART-HCI driver file contents File Name Description r_ble_uart_hci.c SCI control driver source file r_ble_uart_hci.h SCI control driver header file *1 *1: When changing the UART baud rate, this file need to edit.

7.3.1 UART-HCI Driver configuration UART-HCI driver can change the UART baud rate by configuration option in the “r_ble_uart_hci.h” file. Edit this file directly to change configuration options. The SCI channel used by the UART-HCI driver is fixed to SCI2. Table 7.2 outlines UART-HCI driver configuration.

Table 7.2 UART-HCI driver configuration

No. Macro Name Default Description 1 HCI_USART_BAUDRATE 115200 Set the UART baud rate.

R01AN5606EJ0220 Rev.2.20 Page 105 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 8. Tools

8.1 CLVALTune CLVALTune is a tool used for calibration operation for HCI mode. Refer to “RE01B Group Tuning procedure of Bluetooth dedicated clock frequency(R01AN5488)” for details.

R01AN5606EJ0220 Rev.2.20 Page 106 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) 9. Appendix 9.1 Code Size Table 9.1 shows the code size of the BLE Protocol Stack of the BLE module. The code size is based on optimization level -Os (optimization size) for GCC. The ROM (code and constants) and RAM (global data) sizes are determined by the build-time configuration options set in the BLE module configuration header file. The values in the table below are confirmed under the following conditions. The ROM size is the maximum value when all R_BLE APIs are used.

Table 9.1 Code Size

Type of the BLE Protocol Stack Device Compiler Category All Features Balance Compact

ROM 187K bytes 148K bytes 131K bytes RE01B GCC RAM 37K bytes 22K bytes 22K bytes Configuration Option

Common :

BLE_CFG_RF_CONN_MAX 7

BLE_CFG_RF_CONN_DATA_MAX 251

All Features :

BLE_CFG_LIB_TYPE 0

BLE_CFG_RF_ADV_DATA_MAX 1650

BLE_CFG_RF_ADV_SET_MAX 4

BLE_CFG_RF_SYNC_SET_MAX 2

Balance :

BLE_CFG_LIB_TYPE 1

Compact :

BLE_CFG_LIB_TYPE 2

[Note] The app_lib and the BLE Profile are not included in the above code size.

R01AN5606EJ0220 Rev.2.20 Page 107 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package) Revision History

Rev. Date Description Page Summary 1.00 Oct.30.2020 — First edition issued. 2.10 Mar 25 2021 — Change board name to EB-RE01B board. 4 Add CMSIS driver documents to package contents. 9, 10 Change board switch for EB-RE01B board. 16 Add the description for changing from default J-Link setting. 47 - Add (addr_type) and (-wl) to Advertising command. - Removed API parameter description and changed to reference to API documentation. 48 - Add (addr_type) and (-wl) to Scan command. - Removed API parameter description and changed to reference to API documentation. 49 - Add (own_addr_type), (dummy_irk) and (-wl) to Connection command. - Removed API parameter description and changed to reference to API documentation. 51 Add “remove”, “get” and “off” to Privacy command. 67 Move the contents in "3.8.2 User command creation procedure" to "Application Developer's Guide (R01AN5643)". Library - The RF restore process cannot be conducted normally, if the API execution process in R_BLE_Execute() and a BLE wake-up interrupt compete in limited timing (a few cycles). - A GATT server returns "Insufficient Authentication Error" during service discovery, if check "Encryption" of "Included Service" on the QE for BLE. - Changed so that if the static address is changed in the middle, it will be reflected in advertising. - Corrected the scanner address included in the Scan Request reception event when using the RPA function. - Fixed that the BLE_GAP_EVENT_ADV_REPT_IND event is not notified when scan is executed only 1M PHY after scan is executed only Coded PHY. - Fixed that R_BLE_Execute() API does not return when the non-maskable interrupt status register (NMISR) is not 0x00. Program - The scan and create connection abstraction APIs can specify the local device address type. - Added the following options to the Command Line. - Local device address type option for adv, scan, conn, priv command. - Use White List option for adv, scan, conn command. - Remove an advertising set option for adv command. - Delete an entry in the Resolving List for priv command. - Fixed the following command line functions - Fixed so that passkey starting from 0 can be identified as a decimal number when pairing by passkey entry.

R01AN5606EJ0220 Rev.2.20 Page 108 of 109 Jul.30.2021 RE01B Group Bluetooth Low Energy Sample code (using CMSIS Driver Package)

Rev. Date Description Page Summary 2.20 Jul 30 2021 Library Fixed for impersonation in the Passkey Entry Protocol (CVE- 2020-26558).

R01AN5606EJ0220 Rev.2.20 Page 109 of 109 Jul.30.2021

General Precautions in the Handling of Microprocessing Unit and Microcontroller Unit Products

The following usage notes are applicable to all Microprocessing unit and Microcontroller unit products from Renesas. For detailed usage notes on the products covered by this document, refer to the relevant sections of the document as well as any technical updates that have been issued for the products.

1. Precaution against Electrostatic Discharge (ESD) A strong electrical field, when exposed to a CMOS device, can cause destruction of the gate oxide and ultimately degrade the device operation. Steps must be taken to stop the generation of static electricity as much as possible, and quickly dissipate it when it occurs. Environmental control must be adequate. When it is dry, a humidifier should be used. This is recommended to avoid using insulators that can easily build up static electricity. devices must be stored and transported in an anti-static container, static shielding bag or conductive material. All test and measurement tools including work benches and floors must be grounded. The operator must also be grounded using a wrist strap. Semiconductor devices must not be touched with bare hands. Similar precautions must be taken for printed circuit boards with mounted semiconductor devices. 2. Processing at power-on The state of the product is undefined at the time when power is supplied. The states of internal circuits in the LSI are indeterminate and the states of register settings and pins are undefined at the time when power is supplied. In a finished product where the reset signal is applied to the external reset pin, the states of pins are not guaranteed from the time when power is supplied until the reset process is completed. In a similar way, the states of pins in a product that is reset by an on-chip power-on reset function are not guaranteed from the time when power is supplied until the power reaches the level at which resetting is specified. 3. Input of signal during power-off state Do not input signals or an I/O pull-up power supply while the device is powered off. The current injection that results from input of such a signal or I/O pull-up power supply may cause malfunction and the abnormal current that passes in the device at this time may cause degradation of internal elements. Follow the guideline for input signal during power-off state as described in your product documentation. 4. Handling of unused pins Handle unused pins in accordance with the directions given under handling of unused pins in the manual. The input pins of CMOS products are generally in the high-impedance state. In operation with an unused pin in the open-circuit state, extra electromagnetic noise is induced in the vicinity of the LSI, an associated shoot-through current flows internally, and malfunctions occur due to the false recognition of the pin state as an input signal become possible. 5. Clock signals After applying a reset, only release the reset line after the operating clock signal becomes stable. When switching the clock signal during program execution, wait until the target clock signal is stabilized. When the clock signal is generated with an external resonator or from an external oscillator during a reset, ensure that the reset line is only released after full stabilization of the clock signal. Additionally, when switching to a clock signal produced with an external resonator or by an external oscillator while program execution is in progress, wait until the target clock signal is stable. 6. Voltage application waveform at input pin

Waveform distortion due to input noise or a reflected wave may cause malfunction. If the input of the CMOS device stays in the area between VIL

(Max.) and VIH (Min.) due to noise, for example, the device may malfunction. Take care to prevent chattering noise from entering the device when the

input level is fixed, and also in the transition period when the input level passes through the area between VIL (Max.) and VIH (Min.). 7. Prohibition of access to reserved addresses Access to reserved addresses is prohibited. The reserved addresses are provided for possible future expansion of functions. Do not access these addresses as the correct operation of the LSI is not guaranteed. 8. Differences between products Before changing from one product to another, for example to a product with a different part number, confirm that the change will not lead to problems. The characteristics of a microprocessing unit or microcontroller unit products in the same group but having a different part number might differ in terms of internal memory capacity, layout pattern, and other factors, which can affect the ranges of electrical characteristics, such as characteristic values, operating margins, immunity to noise, and amount of radiated noise. When changing to a product with a different part number, implement a system- evaluation test for the given product.

Notice

1. Descriptions of circuits, software and other related information in this document are provided only to illustrate the operation of semiconductor products and application examples. You are fully responsible for the incorporation or any other use of the circuits, software, and information in the design of your product or system. Renesas Electronics disclaims any and all liability for any losses and damages incurred by you or third parties arising from the use of these circuits, software, or information. 2. Renesas Electronics hereby expressly disclaims any warranties against and liability for infringement or any other claims involving patents, copyrights, or other intellectual property rights of third parties, by or arising from the use of Renesas Electronics products or technical information described in this document, including but not limited to, the product data, drawings, charts, programs, algorithms, and application examples. 3. No license, express, implied or otherwise, is granted hereby under any patents, copyrights or other intellectual property rights of Renesas Electronics or others. 4. You shall be responsible for determining what licenses are required from any third parties, and obtaining such licenses for the lawful import, export, manufacture, sales, utilization, distribution or other disposal of any products incorporating Renesas Electronics products, if required. 5. You shall not alter, modify, copy, or reverse engineer any Renesas Electronics product, whether in whole or in part. Renesas Electronics disclaims any and all liability for any losses or damages incurred by you or third parties arising from such alteration, modification, copying or reverse engineering. 6. Renesas Electronics products are classified according to the following two quality grades: “Standard” and “High Quality”. The intended applications for each Renesas Electronics product depends on the product’s quality grade, as indicated below. "Standard": Computers; office equipment; communications equipment; test and measurement equipment; audio and visual equipment; home electronic appliances; machine tools; personal electronic equipment; industrial robots; etc. "High Quality": Transportation equipment (automobiles, trains, ships, etc.); traffic control (traffic lights); large-scale communication equipment; key financial terminal systems; safety control equipment; etc. Unless expressly designated as a high reliability product or a product for harsh environments in a Renesas Electronics data sheet or other Renesas Electronics document, Renesas Electronics products are not intended or authorized for use in products or systems that may pose a direct threat to human life or bodily injury (artificial life support devices or systems; surgical implantations; etc.), or may cause serious property damage (space system; undersea repeaters; nuclear power control systems; aircraft control systems; key plant systems; military equipment; etc.). Renesas Electronics disclaims any and all liability for any damages or losses incurred by you or any third parties arising from the use of any Renesas Electronics product that is inconsistent with any Renesas Electronics data sheet, user’s manual or other Renesas Electronics document. 7. No semiconductor product is absolutely secure. Notwithstanding any security measures or features that may be implemented in Renesas Electronics hardware or software products, Renesas Electronics shall have absolutely no liability arising out of any vulnerability or security breach, including but not limited to any unauthorized access to or use of a Renesas Electronics product or a system that uses a Renesas Electronics product. RENESAS ELECTRONICS DOES NOT WARRANT OR GUARANTEE THAT RENESAS ELECTRONICS PRODUCTS, OR ANY SYSTEMS CREATED USING RENESAS ELECTRONICS PRODUCTS WILL BE INVULNERABLE OR FREE FROM CORRUPTION, ATTACK, VIRUSES, INTERFERENCE, HACKING, DATA LOSS OR THEFT, OR OTHER SECURITY INTRUSION (“Vulnerability Issues”). RENESAS ELECTRONICS DISCLAIMS ANY AND ALL RESPONSIBILITY OR LIABILITY ARISING FROM OR RELATED TO ANY VULNERABILITY ISSUES. FURTHERMORE, TO THE EXTENT PERMITTED BY APPLICABLE LAW, RENESAS ELECTRONICS DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT AND ANY RELATED OR ACCOMPANYING SOFTWARE OR HARDWARE, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. 8. When using Renesas Electronics products, refer to the latest product information (data sheets, user’s manuals, application notes, “General Notes for Handling and Using Semiconductor Devices” in the reliability handbook, etc.), and ensure that usage conditions are within the ranges specified by Renesas Electronics with respect to maximum ratings, operating power supply voltage range, heat dissipation characteristics, installation, etc. Renesas Electronics disclaims any and all liability for any malfunctions, failure or accident arising out of the use of Renesas Electronics products outside of such specified ranges. 9. Although Renesas Electronics endeavors to improve the quality and reliability of Renesas Electronics products, semiconductor products have specific characteristics, such as the occurrence of failure at a certain rate and malfunctions under certain use conditions. Unless designated as a high reliability product or a product for harsh environments in a Renesas Electronics data sheet or other Renesas Electronics document, Renesas Electronics products are not subject to radiation resistance design. You are responsible for implementing safety measures to guard against the possibility of bodily injury, injury or damage caused by fire, and/or danger to the public in the event of a failure or malfunction of Renesas Electronics products, such as safety design for hardware and software, including but not limited to redundancy, fire control and malfunction prevention, appropriate treatment for aging degradation or any other appropriate measures. Because the evaluation of microcomputer software alone is very difficult and impractical, you are responsible for evaluating the safety of the final products or systems manufactured by you. 10. Please contact a Renesas Electronics sales office for details as to environmental matters such as the environmental compatibility of each Renesas Electronics product. You are responsible for carefully and sufficiently investigating applicable laws and regulations that regulate the inclusion or use of controlled substances, including without limitation, the EU RoHS Directive, and using Renesas Electronics products in compliance with all these applicable laws and regulations. Renesas Electronics disclaims any and all liability for damages or losses occurring as a result of your noncompliance with applicable laws and regulations. 11. Renesas Electronics products and technologies shall not be used for or incorporated into any products or systems whose manufacture, use, or sale is prohibited under any applicable domestic or foreign laws or regulations. You shall comply with any applicable export control laws and regulations promulgated and administered by the governments of any countries asserting jurisdiction over the parties or transactions. 12. It is the responsibility of the buyer or distributor of Renesas Electronics products, or any other party who distributes, disposes of, or otherwise sells or transfers the product to a third party, to notify such third party in advance of the contents and conditions set forth in this document. 13. This document shall not be reprinted, reproduced or duplicated in any form, in whole or in part, without prior written consent of Renesas Electronics. 14. Please contact a Renesas Electronics sales office if you have any questions regarding the information contained in this document or Renesas Electronics products. (Note1) “Renesas Electronics” as used in this document means Renesas Electronics Corporation and also includes its directly or indirectly controlled subsidiaries. (Note2) “Renesas Electronics product(s)” means any product developed or manufactured by or for Renesas Electronics.

(Rev.5.0-1 October 2020)

Corporate Headquarters Contact information TOYOSU FORESIA, 3-2-24 Toyosu, For further information on a product, technology, the most up-to-date Koto-ku, Tokyo 135-0061, Japan version of a document, or your nearest sales office, please visit: www.renesas.com www.renesas.com/contact/. Trademarks Renesas and the Renesas logo are trademarks of Renesas Electronics Corporation. All trademarks and registered trademarks are the property of their respective owners.

© 2021 Renesas Electronics Corporation. All rights reserved.