Wireless Connectivity Knowledge Base

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Wireless Connectivity Knowledge Base

Discussions

Sort by:
Introduction Over The Air Programming (OTAP) is a Bluetooth LE custom NXP's service that provides a solution to upgrade the software running in the microcontroller. This document guides to load a new software image in a KW38 device through (Over The Air Programming) OTAP Bluetooth LE service. Software Requirements MCUXpresso IDE or IAR Embedded Workbench IDE. FRDM-KW38 SDK. IoT Toolbox App, available for Android and iOS. You can also download the APK of the IoT Toolbox App from this post: IoT Toolbox for Android  Hardware Requirements FRDM-KW38 board. A smartphone with IoT Toolbox App. KW38 Flash Memory Used by the OTAP Client Software During the Update Process By default, the 512KB KW38 flash memory is partitioned into: One 256KB Program Flash array (P-Flash) divided into 2KB sectors with a flash address range from 0x0000_0000 to 0x0003_FFFF. One 256KB FlexNVM array divided into 2KB sectors with address range from 0x1000_0000 to 0x1003_FFFF. Alias memory with address range from 0x0004_0000 to 0x0007_FFFF. Writes or reads at the Alias memory modifies or returns the FlexNVM content, respectively. In other words, Alias memory is another way to refer to FlexNVM memory using different addresses. The following statements simplify how does the OTAP service work:   The OTAP application consists of two independent parts, OTAP bootloader, and OTAP client. The OTAP bootloader verifies if there is a new image available in the OTAP client to reprogram the device. The OTAP client software, on the other hand, provides the Bluetooth LE custom service needed to communicate the OTAP client device (device to be reprogrammed) with the OTAP server device (device that contains the image to reprogram the OTAP client device). Therefore, to prepare the software for the first time, the OTAP client device needs to be programmed twice, first with the OTAP bootloader, and then with the OTAP client software. The mechanism created to have two different software coexisting in the same device is storing each one in different memory regions. This is achieved by indicating to the linker file different memory regions on each individual software. For the KW38 device, the OTAP bootloader has reserved an 8KB slot from 0x0000_0000 to 0x0000_1FFF, thus the rest of the memory is reserved, among other things, by the OTAP client software.     When generating the new image file for the OTAP client device, we need to specify to the linker file that the code will be placed with an offset of 8KB (as the OTAP client software does), since these address range must be preserved to do not overwrite the OTAP bootloader. The new application should also contain the bootloader flags at the corresponding address to work properly (later we will return to this point).     While OTAP client and OTAP server devices are connected, and the download is in progress, the OTAP server device sends the image packets (known as chunks) to the OTAP client device via Bluetooth LE. The OTAP client device can store these chunks, in the external SPI flash (which is already populated on the FRDM-KW38) or in the on-chip FlexNVM region. The destination for these chunks is selectable in the OTAP client software (This post will give the instructions to modify the destination).     When the transfer of the image has finished, and all chunks were sent from the OTAP server device to the OTAP client device, the OTAP client software writes information such as the source of the software update (either external flash or FlexNVM) in a portion of memory known as bootloader flags. Then the OTAP client performs a software reset on the MCU to execute the OTAP bootloader code. Then, the OTAP bootloader code reads the bootloader flags to get the information needed to reprogram the device with the new application. See the following flow diagram which explains the flow of both applications.   Because the new application was built with an offset of 8KB, the OTAP bootloader programs the device starting from the 0x0000_2000 address, so, in consequence, the OTAP client application is overwritten by the new image. Then, the OTAP bootloader moves the flow of the application to start the execution of the new code.     In practice, the boundary between the OTAP client software and the software update when FlexNVM storage is enabled described in statement 3 is not placed exactly in the boundary of the P-Flash and FlexNVM memory regions, moreover, these values might change depending on your linker settings. To know where is located the boundary, you should inspect the effective memory addressing in your project.        Configuring and Programming OTAP Client Software in IAR Embedded Workbench IDE As mentioned in the last section, to complete the software for OTAP implementation, there are required two software programmed in your FRDM-KW38, OTAP bootloader and OTAP client. This section guides you to program and configure the settings to choose between external or internal storage using the IAR Embedded Workbench IDE. 1- The first step is to program the OTAP bootloader in your KW38. Unzip your SDK and then locate the OTAP bootloader software in the following path: <KW38_SDK>\boards\frdmkw38\wireless_examples\framework\bootloader_otap\bm\iar\bootloader_otap.eww 2- Program the OTAP bootloader project on your board by clicking on the "Download and Debug" icon (Ctrl + D) . Once the KW38 was programmed and the debug session begun, abort the session (Ctrl + Caps Lock + D)  to stop the MCU safely. 3- At this point, you have programmed the OTAP bootloader in your KW38. The next is to program and configure the OTAP client software. Locate the OTAP client software at the following path: Freertos project version: <KW38_SDK>\boards\frdmkw38\wireless_examples\bluetooth\otac_att\freertos\iar\otap_client_att_freertos.eww Baremetal project version: <KW38_SDK>\boards\frdmkw38\wireless_examples\bluetooth\otac_att\bm\iar\otap_client_att_bm.eww 4- Then, configure the OTAP client to select external or internal storage. To select the external storage, follow the next steps (this is the default configuration in the SDK project): 4.1- Locate the "app_preinclude.h" header file in the source folder of your workspace. Search the "gEepromType_d" define and set its value to "gEepromDevice_AT45DB041E_c". /* Specifies the type of EEPROM available on the target board */ #define gEepromType_d gEepromDevice_AT45DB041E_c 4.2- Open the project options window (Alt + F7). Go to Linker->Config window and set "gUseInternalStorageLink_d=0".   To select the internal storage, follow the next steps: 4.1- Locate the "app_preinclude.h" header file in the source folder of your workspace. Search the "gEepromType_d" define and set its value to "gEepromDevice_InternalFlash_c". /* Specifies the type of EEPROM available on the target board */ #define gEepromType_d gEepromDevice_InternalFlash_c 4.2- Open the project options window (Alt + F7). Go to Linker->Config window and set "gUseInternalStorageLink_d=1".   5- Once you have configured the storage settings, save the changes in the project. Then program the software on your board by clicking on the "Download and Debug" icon (Ctrl + D)  . Once the KW38 was programmed and the debug session began, abort the session (Ctrl + Caps Lock + D)  to stop the MCU safely. Creating an SREC Image to Update the Software in OTAP Client in IAR Embedded Workbench IDE This section shows how to create an image compatible with OTAP to reprogram the KW38 OTAP Client using as a starting point, our wireless examples with IAR Embedded Workbench IDE. 1- Select any example from your SDK package in the Bluetooth folder and open it using the IAR IDE. Bluetooth examples are located in the following path: <KW38_SDK>\boards\frdmkw38\wireless_examples\bluetooth  In this example, we will use the glucose sensor project: <KW38_SDK>\boards\frdmkw38\wireless_examples\bluetooth\glucose_s\freertos\iar\glucose_sensor_freertos.eww 2- Open the project options window in IAR (Alt + F7). In Linker->Config window, edit the options to include the "gUseBootloaderLink_d=1" flag and update the "gEraseNVMLink_d=0" flag. When the gUseBootlaoderLink_d flag is true, it indicates to the linker file that the image must be addressed after the first flash sector, to do not overwrite the OTAP Bootloader software (as we stated previously). On the other hand, the gEraseNVMLink_d symbol is used to fill with a 0xFF pattern the unused NVM flash memory region. Disabling this flag, our software image will not contain this pattern, in consequence, the image reduces its total size and it improves the speed of the OTAP download and memory usage. 3- Go to "Output Converter" window. Deselect the "Override default" checkbox, then expand the "Output format" combo box and select "Motorola S-records" format. Click the "OK" button to finish. 4- Build the project. 5- Locate the S-Record file (.srec) in the following path, and save it to a known location on your smartphone. <KW38_SDK>\boards\frdmkw38\wireless_examples\bluetooth\glucose_s\freertos\iar\debug\glucose_sensor_freertos.srec Configuring and Programming OTAP Client Software in MCUXpresso IDE As mentioned in a previous section, to complete the software for OTAP implementation, there are required two software programmed in your FRDM-KW38, OTAP bootloader and OTAP client. This section guides you to program and configure the settings to choose between external or internal storage using the MCUXpresso IDE. 1- Open MCUXpresso IDE. Click on "Import SDK example(s)" in the "Quickstart Panel". 2- Select the FRDM-KW38 icon and click "Next >". 3- Import the OTAP bootloader project. It is located in "wireless_examples -> framework -> bootloader_otap -> bm -> bootloader_otap". Click on the "Finish" button. 4- Program the OTAP bootloader project on your board by clicking on the "Debug" icon  . Once the KW38 was programmed and the debug session begun, abort the session  (Ctrl + F2) to stop the MCU safely. 5- Repeat steps 1 to 3 to import the OTAP client software on MCUXpresso IDE. It is located at "wireless_examples -> bluetooth -> otac_att -> freertos -> otap_client_att_freertos" for freertos version, or "wireless_examples -> bluetooth -> otac_att -> bm -> otap_client_bm_freertos" if you prefer baremetal instead. 6- Then, configure the OTAP client to select external or internal storage. To select the external storage, follow the next steps (this is the default configuration in the SDK project): 6.1- Locate the "app_preinclude.h" file under the source folder in your workspace. Search the "gEepromType_d" define and set its value to "gEepromDevice_AT45DB041E_c". /* Specifies the type of EEPROM available on the target board */ #define gEepromType_d gEepromDevice_AT45DB041E_c 6.2- Navigate to "Project -> Properties -> C/C++ Build -> MCU settings -> Memory details". Edit the Flash fields as shown in the figure below, and leave intact the RAM. To select the internal storage, follow the next steps: 6.1- Locate the "app_preinclude.h" file under the source folder in your workspace. Search the "gEepromType_d" define and set its value to "gEepromDevice_InternalFlash_c". /* Specifies the type of EEPROM available on the target board */ #define gEepromType_d gEepromDevice_InternalFlash_c 6.2- Navigate to "Project -> Properties -> C/C++ Build -> MCU settings -> Memory details". Edit the Flash fields as shown in the figure below, and leave intact the RAM. 7- Once you have configured the storage settings, save the changes in the project. Then program the software on your board by clicking on the "Debug" icon  . Once the KW38 was programmed and the debug session begun, abort the session  (Ctrl + F2) to stop the MCU safely. Creating an SREC Image to Update the Software in OTAP Client in MCUXpresso IDE This section shows how to create an image compatible with OTAP to reprogram the KW38 OTAP Client using as a starting point, our wireless examples with MCUXpresso IDE. 1- Import any example from your SDK package in the Bluetooth folder as explained previously. Bluetooth examples are located in "wireless_examples -> bluetooth" folder in the SDK Import Wizard. This example will make use of the glucose sensor project in "wireless_examples -> bluetooth -> glucose_s -> freertos -> glucose_sensor_freertos". See the picture below. 2- Navigate to "Project -> Properties -> C/C++ Build -> MCU settings -> Memory details". Edit the Flash fields as shown in the figure below, and leave intact the RAM. The last fields indicate to the linker file that the image must be addressed after the first flash sector, to do not overwrite the OTAP bootloader software, as we stated in the introduction of this post. 3- Unzip your KW38 SDK package. Drag and drop the "main_text_section.ldt" linker script from the following path to the "linkscripts" folder on your workspace. The result must be similar as shown in the following figure. <KW38_SDK>\middleware\wireless\framework\Common\devices\MKW38A4\mcux\linkscript_bootloader\main_text_section.ldt 4- Open the "end_text.ldt" linker script file located in the linkscripts folder in MCUXpresso IDE. Locate the section shown in the following figure and remove "FILL" and "BYTE" statements. BYTE and FILL lines are used to fill with a 0xFF pattern the unused NVM flash memory region. Removing this code, our software image will not contain this pattern, in consequence, the image reduces its total size and it improves the speed of the OTAP download and memory usage. 5- Open the "app_preinclude.h" file, and define "gEepromType_d" as internal storage. This is a dummy definition needed to place the bootloader flags in the proper address, so this will not affect the storage method chosen before when you programmed the OTAP client and the OTAP bootloader software in your MCU. /* Specifies the type of EEPROM available on the target board */ #define gEepromType_d gEepromDevice_InternalFlash_c 6-  Include in your project, the "OtaSupport" folder and its files in the "framework" folder of your project. Include as well the "External" folder and its files in the "framework -> Flash" folder of your project. "OtaSupport" and "External" folders can be found in your SDK. You can easily drag those folders from your SDK download path and drop it into your workspace in MCUXpresso to include them. "OtaSupport" and "External" folders are located at: OtaSupport <KW38_SDK>middleware\wireless\framework\OtaSupport External <KW38_SDK>middleware\wireless\framework\Flash\External The result must look like the following picture:  7- Go to "Project -> Properties -> C/C++ Build -> Settings -> Tool Settings -> MCU C Compiler -> Includes". Click on the icon next to "Include paths" (See the picture below). A new window will be displayed, then click on the "Workspace" button. 8- Deploy the directory of the project in the "Folder selection" window, and select "framework -> Flash -> External -> interface" and "framework -> OtaSupport -> interface" folders. Click the "OK" button to save the changes. 9- Ensure that "OtaSupport" and "External" folders were imported in the "Include paths" window. Then save the changes by clicking on the "Apply and Close" button. 10- Save and build the project by clicking this icon  . Then, deploy the "Binaries" icon in your project. Click the right mouse button on the ".axf" file and select the "Binary Utilities -> Create S-Record" option. The S-Record file generated will be saved in the Debug folder in your workspace with ".s19" extension. Save the S-Record file in a known location on your smartphone.    Testing the OTAP Client with IoT Toolbox App This section explains how to test the OTAP client software using the IoT Toolbox App. 1- Open the IoT Toolbox App on your smartphone. Select OTAP and click "SCAN" to start scanning for a suitable OTAP Client device.  2- Press the ADV button (SW2) on your FRDM-KW38 board to start advertising. 3- Once your smartphone has found the FRDM-KW38 board, it will be identified as "NXP_OTAA". Connect your smartphone with this device. Then a new window will be displayed on your smartphone.  4- Click the "Open" button and search for the SREC software update. 5- Click "Upload" to start the transfer. Wait while the download is completed. A confirmation message will be displayed after a successful update.  6- Wait a few seconds until the software update was programmed on your MCU. The new code will start automatically.   Please let me know any questions about this topic.
View full article
With the release of the Bluetooth LE core erratum 10734, two new Host test cases (SM/SLA/KDU/BI-01-C and SM/MAS/KDU/BI-01-C) were added to the Test Case Reference List (TCRL) and are active since 24-Jan-19. This has an impact on new product qualifications based on Component (Tested) QDIDs that used an older TCRL when the test cases for this erratum were not required. Products that rely on NXP HOST QDIDs have 2 options for covering the erratum 10734 in order to complete the qualification: NXP provides a new qualification/QDID that includes these 2 tests. This is scheduled for later this year for QN908x, KW35/36 and KW41/31 products. NXP provides the test evidence/logs for these 2 tests and the test house reviews them before completing the product qualification. Right now, option 2 can be followed using the test evidence/logs provided by NXP. Later in the year, option 1 can be followed with an updated QDID. To obtain the test evidence/logs, please submit a support request.
View full article
The FRDM-KW36 comes with the OpenSDA circuit which allows users to program and debug the evaluation board. There are different solutions to support such OpenSDA circuits: 1. The J-Link (SEGGER) firmware.  2. The CMSIS-DAP (mbed) firmware. The FRDM-KW36 comes pre-programmed with the CMSIS-DAP firmware. However, if you want to update the firmware version, you need to perform the next steps.  Press and hold the Reset button (SW1 push button in the board).  Unplug and plug the FRDM-KW36 again to the PC.  The board will be enumerated as "DAPLINKBOOT" device. Drag and drop the binary file to update the OpenSDA firmware.  If the J-Link version is programmed, the board will be enumerated as "FRDM-KW36J". On the other hand, if the CMSIS-DAP version is programmed, the board will be enumerated as "FRDM-KW36". The binary for the J-link version can be downloaded from the next link: SEGGER - The Embedded Experts - Downloads - J-Link / J-Trace  The binary for the CMSIS-DAP version can be found in the next link: OpenSDA Serial and Debug Adapter|NXP    Hope this helps... 
View full article
The QN9090 is a Bluetooth Low Energy device that achieves ultra-low-power consumption and integrates an Arm ® Cortex ® -M4 CPU with a comprehensive mix of analog and digital peripherals. If the developer is working with the Development platform for QN9090 wireless MCUs for the first time, it is recommended to follow the QN9090-DK Development kit Getting Started (this guide can be found in QN9090DK Documentation section). This Quick Start document provides an overview about the QN9090 DK and its software tools and lists the steps to install the hardware and the software. For this document, Temperature Sensor and Temperature Collector examples will be used to demonstrate the implementation of a custom profile (both examples can be found in the SDK). This article will explain how to add the Humidity Profile and how to modify the code to get the Humidity Sensor and Collector working.   Introduction   Generic Attribute Profile (GATT) GATT defines the way that profile and user data are exchanged between devices over a BLE connection. GATT deals with actual data transfer procedures and formats. All standard BLE profiles are based on GATT and must comply with it to operate correctly, making it a key section of the BLE specification since every single item of data relevant to applications and users must be formatted, packed and sent according to the rules. There are two GATT roles that define the devices exchanging data: GATT Server This device contains a GATT Database and stores the data transported over the Attribute Protocol (ATT). The Server accepts ATT requests, commands and confirmations sent by the Client; and it can be configured to send data on its own through notifications and indications. GATT Client This is the “active” device that accesses data on the remote GATT Server via read, write, notify, or indicate operations. Notify and indicate operations are enabled by the client but initiated by the server, providing a way to push data to the client. Notifications are unacknowledged, while indications are acknowledged. Notifications are therefore faster, but less reliable. GATT Database establishes a hierarchy to organize attributes and is a collection of Services and Characteristics exposing meaningful data. Profiles are high level definitions that define how Services can be used to enable an application; Services are collections of Characteristics. Descriptors define attributes that describe a characteristic value.   Server (Sensor)   The Temperature Sensor project will be used as base to create our Humidity Custom Profile Server (Sensor). BLE SIG profiles Some Profiles or Services are already defined in the specification, and we can verify this in the Bluetooth SIG profiles document. Also, we need to check in the ble_sig_defines.h files (${workspace_loc:/${ProjName}/bluetooth/host/interface}) if this is already declared in the code. In this case, the Service is not declared, but the Characteristic of the humidity is declared in the specification. Then, we need to check if the Characteristic is already included in ble_sig_defines.h. Since the characteristic is not included, we define it as shown: /*! Humidity Characteristic UUID */ #define gBleSig_Humidity_d                   0x2A6FU GATT Database The Humidity Sensor will act as GATT Server since it will be the device containing all the information for the GATT Client. Temperature Sensor demo already implements the Battery Service and Device Information, so we only have to change the Temperature Service to Humidity Service.   In order to create the demo, we need to define a Service that must be the same as in the GATT Client, this is declared in the gatt_uuid128.h. If the new service is not the same, Client and Server will not be able to communicate each other. All macros, functions or structures in the SDK have a common template which helps the application to act accordingly. Hence, we need to define this service in the gatt_uui128.h as shown next: /* Humidity */ UUID128(uuid_service_humidity, 0xfe, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x02, 0x00, 0xfa, 0x10, 0x10) Units All the Services and Characteristics are declared in gatt_db.h. Descriptor are declared after the Characteristic Value declaration, but before the next Characteristic declaration. In this case the permission is the CharPresFormatDescriptor that have specific description by the standard. The Units for Humidity Characteristic is Percentage, defined in the Bluetooth SIG profiles document as 0x27AD. Descriptor Client Characteristic Configuration Descriptor (CCCD) is a descriptor where Clients write some of the bits to activate Server notifications and/or indications. PRIMARY_SERVICE_UUID128(service_humidity, uuid_service_humidity)        CHARACTERISTIC(char_humidity, gBleSig_Humidity_d, (gGattCharPropNotify_c))              VALUE(value_humidity, gBleSig_Humidity_d, (gPermissionNone_c), 2, 0x00, 0x25)              DESCRIPTOR(desc_humidity, gBleSig_CharPresFormatDescriptor_d, (gPermissionFlagReadable_c), 7, 0x0E, 0x00, 0xAD, 0x27, 0x00, 0x00, 0x00)              CCCD(cccd_humidity) Humidity service and interface Create a folder named “humidity” in path ${workspace_loc:/${ProjName}/bluetooth/profiles}. In the same path you can find the “temperature” folder; copy the temperature_service.c file and paste it inside the “humidity” folder with another name (humidity_service.c). After this, go back to the “temperature” folder and copy the temperature_interface.h file; paste it inside the “humidity” folder and rename it (humidity_interface.h). You will need to include the path of the created folder. Go to Project properties > C/C++ Build > Settings > Tool Settings > MCU C Compiler > Includes: Humidity Interface The humidity_interface.h file should include the following code, where the Service structure contains the Service handle and the initialization value: /*! Humidity Service - Configuration */ typedef struct humsConfig_tag {        uint16_t serviceHandle;        int16_t initialHumidity; } humsConfig_t; /*! Humidity Client - Configuration */ typedef struct humcConfig_tag {        uint16_t hService;        uint16_t hHumidity;        uint16_t hHumCccd;        uint16_t hHumDesc;        gattDbCharPresFormat_t humFormat; } humcConfig_t; Humidity service At minimum, humidity_service.c file must contain the following code: /*! Humidity Service - Subscribed Client*/ static deviceId_t mHums_SubscribedClientId; The Service stores the device identification for the connected client. This value is changed on subscription and non-subscription events. Initialization Initialization of the Service is made by calling the start procedure. This function is usually called when the application is initialized. In this case, this is done in the BleApp_Config() function. bleResult_t Hums_Start(humsConfig_t *pServiceConfig) {     mHums_SubscribedClientId = gInvalidDeviceId_c;     /* Set the initial value of the humidity characteristic */     return Hums_RecordHumidityMeasurement(pServiceConfig->serviceHandle,                                             pServiceConfig->initialHumidity); } Stop & Unsubscribe On stop function, the unsubscribe function is called. bleResult_t Hums_Stop(humsConfig_t *pServiceConfig) {     /* Stop functionality by unsubscribing */     return Hums_Unsubscribe(); } bleResult_t Hums_Unsubscribe(void) {     /* Unsubscribe by invalidating the client ID */     mHums_SubscribedClientId = gInvalidDeviceId_c;     return gBleSuccess_c; } Subscribe The subscribe function will be used in the main file to subscribe the GATT client to the Humidity Service. bleResult_t Hums_Subscribe(deviceId_t clientDeviceId) {     /* Subscribe by saving the client ID */     mHums_SubscribedClientId = clientDeviceId;     return gBleSuccess_c; } Record Humidity Depending on the complexity of the Service, the API will implement additional functions. For the Humidity Sensor will only have one Characteristic. The measurement will be saved on the GATT Database and send the notification to the Client. This function will need the Service handle and the new value as input parameters. bleResult_t Hums_RecordHumidityMeasurement(uint16_t serviceHandle, int16_t humidity) {        uint16_t handle;        bleResult_t result;        bleUuid_t uuid = Uuid16(gBleSig_Humidity_d);        /* Get handle of Humidity characteristic */        result = GattDb_FindCharValueHandleInService(serviceHandle,                      gBleUuidType16_c, &uuid, &handle);        if (result == gBleSuccess_c)        {              /* Update characteristic value */              result = GattDb_WriteAttribute(handle, sizeof(uint16_t), (uint8_t *)&humidity);              if (result == gBleSuccess_c)              {                     /* Notify the humidity value */                     Hts_SendHumidityMeasurementNotification(handle);              }        }        return result; } Remember to add/update the prototype for Initialization, Subscribe, Unsubscribe, Stop and Record Humidity Measurement functions in humidity_interface.h. Send notification After saving the measurement on the GATT Database by using the GattDb_WriteAttribute function, we can send the notification. To send this notification, first we have to get the CCCD and check if the notification is active after that; if it is active, then we send the notification. static void Hts_SendHumidityMeasurementNotification (              uint16_t handle ) {        uint16_t hCccd;        bool_t isNotificationActive;        /* Get handle of CCCD */        if (GattDb_FindCccdHandleForCharValueHandle(handle, &hCccd)                     != gBleSuccess_c)              return;        if (gBleSuccess_c == Gap_CheckNotificationStatus                     (mHums_SubscribedClientId, hCccd, &isNotificationActive) &&                     TRUE == isNotificationActive)        {              GattServer_SendNotification(mHums_SubscribedClientId, handle);        } } Remember to add or modify the prototype for Send Humidity Measurement Notification function.   Main file There are some modifications that need to be done in the Sensor main file: Add humidity_interface.h in main file /* Profile / Services */ #include "humidity_interface.h" Declare humidity service There are some modifications that have to be done in order to use the new Humidity Profile in the Sensor example. First, we need to declare the Humidity Service: static humsConfig_t humsServiceConfig = {(uint16_t)service_humidity, 0};   Rename BleApp_SendTemperature -> BleApp_SendHumidity static void BleApp_SendHumidity(void); After this, we need to add or modify the following functions and events: Modify BleApp_Start /* Device is connected, send humidity value */        BleApp_SendHumidity();   Ble_AppConfig Start Humidity Service and modify the Serial_Print line. /* Start services */ humsServiceConfig.initialHumidity = 0; (void)Hums_Start(&humsServiceConfig); (void)Serial_Print(gAppSerMgrIf, "\n\rHumidity sensor -> Press switch to start advertising.\n\r", gAllowToBlock_d);   BleApp_ConnectionCallback events - Event: gConnEvtConnected_c (void)Hums_Subscribe(peerDeviceId);   - Event: gConnEvtDisconnected_c (void)Hums_Unsubscribe();   Notify value in BleApp_GattServerCallback function /* Notify the humidity value when CCCD is written */ BleApp_SendHumidity(); Add the Hums_RecordHumidityMeasurement function and modify the initial value update in BleApp_SendHumidity function /* Update with initial humidity */ (void)Hums_RecordHumidityMeasurement((uint16_t)service_humidity,                                            (int16_t)(BOARD_GetTemperature())); Note: in this example, the Record Humidity uses the BOARD_GetTemperature to allow the developer to use the example without any external sensor and to be able to see a change in the collector, but in this section, there should be a GetHumidity function.   app_config.c file There are some modifications that need to be done inside app_config.c file: Modify Scanning and Advertising Data {     .length = NumberOfElements(uuid_service_humidity) + 1,     .adType = gAdComplete128bitServiceList_c,     .aData = (uint8_t *)uuid_service_humidity }   *Optional* Modify name {     .adType = gAdShortenedLocalName_c,     .length = 9,     .aData = (uint8_t*)"NXP_HUM" }   Modify Service Security Requirements {     .requirements = {         .securityModeLevel = gSecurityMode_1_Level_3_c,         .authorization = FALSE,         .minimumEncryptionKeySize = gDefaultEncryptionKeySize_d     },     .serviceHandle = (uint16_t)service_humidity }   Client (Collector)   We will use the Temperature Collector project as base to create our Humidity Custom Profile Client (Collector). BLE SIG profiles As mentioned in the Server section, we need to verify if the Profile or Service is already defined in the specification. For this, we can take a look at the Bluetooth SIG profiles document and check in the ble_sig_defines.h file (${workspace_loc:/${ProjName}/bluetooth/host/interface}) if this is already declared in the code. In our case, the Service is not declared, but the Characteristic of the Humidity is declared in the specification. Then, we need to check if the Characteristic is already included in ble_sig_defines.h. Since the Characteristic is not included, we need to define it as shown: /*! Humidity Characteristic UUID */ #define gBleSig_Humidity_d                    0x2A6FU GATT Database The Humidity Collector is going to have the GATT client; this is the device that will receive all new information from the GATT Server. The demo provided in this article works in the same way as the Temperature Collector. When the Collector enables the notifications from the Sensor, received notifications will be printed in the seral terminal. In order to create the demo, we need to define or develop a Service that must be the same as in the GATT Server, this is declared in the gatt_uuid128.h file. If the new Service is no the same, Client and Server will not be able to communicate each other. All macros, functions or structures in the SDK have a common template which helps the application to act accordingly. Hence, we need to define this service in the gatt_uui128.h as shown next: /* Humidity */ UUID128(uuid_service_humidity, 0xfe, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x02, 0x00, 0xfa, 0x10, 0x10) Includes After that, copy the humidity profile folder from the Sensor project and paste it into the Collector project inside ${workspace_loc:/${ProjName}/bluetooth/profiles}. Also, include the path of the new folder.   Main file In the Collector main file, we need to do some modifications to use the Humidity Profile Include humidity_interface.h /* Profile / Services */ #include "humidity_interface.h"   Modify the Custom Info of the Peer device humcConfig_t     humsClientConfig;   Modify BleApp_StoreServiceHandles function static void BleApp_StoreServiceHandles {     APP_DBG_LOG("");     uint8_t i,j;     if ((pService->uuidType == gBleUuidType128_c) &&              FLib_MemCmp(pService->uuid.uuid128, uuid_service_humidity, 16))     {         /* Found Humidity Service */        mPeerInformation.customInfo.humsClientConfig.hService = pService->startHandle;         for (i = 0; i < pService->cNumCharacteristics; i++)         {             if ((pService->aCharacteristics[i].value.uuidType == gBleUuidType16_c) &&                     (pService->aCharacteristics[i].value.uuid.uuid16 == gBleSig_Humidity_d))             {                 /* Found Humidity Char */             mPeerInformation.customInfo.humsClientConfig.hHumidity = pService->aCharacteristics[i].value.handle;                 for (j = 0; j < pService->aCharacteristics[i].cNumDescriptors; j++)                 {                     if (pService->aCharacteristics[i].aDescriptors[j].uuidType == gBleUuidType16_c)                     {                         switch (pService->aCharacteristics[i].aDescriptors[j].uuid.uuid16)                         {                             /* Found Humidity Char Presentation Format Descriptor */                             case gBleSig_CharPresFormatDescriptor_d:                             {                                 mPeerInformation.customInfo.humsClientConfig.hHumDesc = pService->aCharacteristics[i].aDescriptors[j].handle;                                 break;                             }                             /* Found Humidity Char CCCD */                             case gBleSig_CCCD_d:                             {                                 mPeerInformation.customInfo.humsClientConfig.hHumCccd = pService->aCharacteristics[i].aDescriptors[j].handle;                                 break;                             }                             default:                                 ; /* No action required */                                 break;                         }                     }                 }             }         }     } }   Modify BleApp_StoreDescValues function if (pDesc->handle == mPeerInformation.customInfo.humsClientConfig.hHumDesc) {        /* Store Humidity format*/        FLib_MemCpy(&mPeerInformation.customInfo.humsClientConfig.humFormat,                     pDesc->paValue,                     pDesc->valueLength); }   Implement BleApp_PrintHumidity function static void BleApp_PrintHumidity (     uint16_t humidity ) {     APP_DBG_LOG("");     shell_write("Humidity: ");     shell_writeDec((uint32_t)humidity);     /* Add '%' for Percentage - UUID 0x27AD.        www.bluetooth.com/specifications/assigned-numbers/units */     if (mPeerInformation.customInfo.humsClientConfig.humFormat.unitUuid16 == 0x27ADU)     {         shell_write(" %\r\n");     }     else     {         shell_write("\r\n");     } }   Modify BleApp_GattNotificationCallback function if (characteristicValueHandle == mPeerInformation.customInfo.humsClientConfig.hHumidity) { BleApp_PrintHumidity(Utils_ExtractTwoByteValue(aValue)); }   Modify CheckScanEvent function foundMatch = MatchDataInAdvElementList(&adElement, &uuid_service_humidity, 16);   Some events inside BleApp_StateMachineHandler need to be modified: BleApp_StateMachineHandler - Event: mAppIdle_c if (mPeerInformation.customInfo.humsClientConfig.hHumidity != gGattDbInvalidHandle_d)   - Event: mAppServiceDisc_c if (mPeerInformation.customInfo.humsClientConfig.hHumDesc != 0U)  mpCharProcBuffer->handle = mPeerInformation.customInfo.humsClientConfig.hHumDesc;   - Event: mAppReadDescriptor_c if (mPeerInformation.customInfo.humsClientConfig.hHumCccd != 0U)   Modify BleApp_ConfigureNotifications function mpCharProcBuffer->handle = mPeerInformation.customInfo.humsClientConfig.hHumCccd;   Demonstration   In order to print the relevant data in console, it may be necessary to disable Power Down mode in app_preinclude.h file. This file can be found inside source folder. For this, cPWR_UsePowerDownMode and cPWR_FullPowerDownMode should be set to 0. Now, after connection, every time that you press the User Interface Button on QN9090 Humidity Sensor is going to send the value to QN9090 Humidity Collector. Humidity Sensor   Humidity Collector  
View full article
简介: 当 OTAP 客户端(接收软件更新的设备,通常为 Bluetooth LE 外围设备)从 OTAP 服务器 (发送软件更新的设备,通常为 Bluetooth LE Central)请求软件更新时,您可能希望保留一 些数据,例如绑定信息,系统振荡器的匹配值或您的应用程序的 FlexNVM 非易失数据。 本 文档指导您在执行 OTAP 更新时, 如何保留您感兴趣的闪存数据内容。 本文档适用于熟悉 OTAP 定制 Bluetooth LE 服务的开发人员,有关更多基础信息,您可以阅读以下文章: 使用 OTAP 客户端软件对 KW36 设备进行重新编程。 OTAP 标头和子元素 OTAP 协议为软件更新实现了一种格式,该格式由标题和定义数量的子元素组成。 OTAP 标 头描述了有关软件更新的一般信息,并且其定义的格式如下图所示。 有关标题字段的更多 信息,请转至 SDK 中的<SDK_2.2.X_FRDM-KW36_Download_Path> \ docs \ wireless \ Bluetooth 中的《 Bluetooth Low Energy Application Developer's Guide》文档的 11.4.1 Bluetooth Low Energy OTAP 标头一章。   每个子元素都包含用于特定目的的信息。 您可以为您的应用程序实现专有字段(有关子元 素字段的更多信息, 请转至 SDK 中的<SDK_2.2.X_FRDM-KW36_Download_Path> \ docs \ wireless \ Bluetooth 中的《 Bluetooth Low Energy Application Developer's Guide》文档的 11.4.1 Bluetooth Low Energy OTAP 标头一章。 OTAP 包含以下子元素: 镜像文件子元素 值字段长度(字节) 描述 升级镜像 变化 该子元素包含实际的二进制可执行镜像,该镜像将被复制到 OTAP 客户端设备的闪存中。 该子元素的最 大大小取决于目标硬件。 扇区位图 32 该子元素包含目标设备闪存的扇区位图,该位图告诉引导加载程序哪些扇区应被覆盖,哪些扇区保持完 整。 该字段的格式是每个字节的最低有效位在前,最低有效字节和位代表闪存的最低存储部分。 镜像文件CRC 2 是在镜像文件的所有元素(此字段本身除外)上计算的 16 位 CRC。 该元素必须是通过空中发送的镜像文件中的最后一个子元素。   OTAP 扇区位图子元素 KW36 闪存分为: 一个 256 KB 程序闪存( P-Flash)阵列, 最小单元为 2 KB 扇区,闪存地址范围为 0x0000_0000 至 0x0003_FFFF。 一个 256 KB FlexNVM 阵列, 最小单元为 2 KB 扇区,闪存地址范围为 0x1000_0000 至 0x1003_FFFF, 同时它也会被映射到地址范围为 0x0004_0000 至 0x0007_FFFF 的空间。 位图子元素的长度为 256 位,就 KW36 闪存而言,每个位代表 2KB 扇区,覆盖从 0x0- 0x0007_FFFF 的地址范围(P-Flash 到 FlexNVM 映射地址范围),其中 1 表示该扇区应 被擦 除, 0 表示应保留该扇区。 OTAP 引导加载程序使用位图字段来获取在使用软件更新对 KW36 进行编程之前应擦除的地址范围,因此必须在发送软件更新之前对其进行配置,以使包含您 的数据的内存的地址范围保持不变。仅擦除将被软件更新覆盖的地址范围。 例如:假设开发人员想要保留 0x7D800-0x7FFFF 之间的地址范围和 0x0-0x1FFF 之间的地址 范围,并且必须擦除剩余的存储器。 0x7D800-0x7FFFF 之间的地址范围对应于前 5 个闪存 扇区, 0x0-0x1FFF 之间的地址范围是最低的 4 个扇区。 因此,这意味着应将 256 和 252 之间的位(256、 255、 254、 253 和 252)以及 4 和 1 之间 的位(4、 3、 2 和 1)设置为 0,这样本示例的 OTAP 位图为 : 0x07FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0 使用 NXP 测试工具配置 OTAP 位图以保护地址范围 在恩智浦网站上下载并安装用于连接产品的测试工具   在 PC 上打开 NXP Test Tool 12 软件。 转到“ OTA 更新-> OTAP 蓝牙 LE”,然后单击“浏 览...”按钮加载用于软件更新的映像文件(NXP 测试工具仅接受.bin 和.srec 文件)。 您 可以配置 OTAP 位图,选择“覆盖扇区位图”复选框,并通过新的位图值更改默认值。 配 置位图后,选择“保存...”。   然后,将显示一个窗口,用于选择保存.bleota 文件的目的地,保存文件可以自行取名。 您可以将此文件与 Android 和 iOS 的 IoT Toolbox App 一起使用,以使用 OTAP 更新软 件。 这个新的.bleota 文件包含位图,该位图告诉 OTAP 引导加载程序哪些扇区将被擦 除,哪些扇区将被保留。    
View full article
The homologation requirements in China (MIIT [2002]353) obviously are planned (end of December 2022) to be sharpened (MIIT publication from 2021-01-27: “Notice on Matters Related to Radio Management in the 2400MHz, 5100MHz and 5800MHz Bands”).   A modification register is need on the KW38 and KW36 to pass the new Chinese  requirement with acceptable margin: PA_RAMP_SEL value must be set to 0x02h (2us) instead of 0x01h (1us default value) Modification SW: XCVR_TX_DIG_PA_CTRL_PA_RAMP_SEL(2) in the nxp_xcvr_common_config.c All the details are in the attached file.   Note: This SW modification is for China country only.
View full article
In the process of practical application, customers often need the combination of ble + NFC. At present, our IOT-DK006 is the only development board with NFC module. But the NFC example is not perfect. So we porting the library of NFC reader- PN7150, to support KW series microcomputer so that KW series can handle the demand of ble + NFC function. Now I will introduce you how to port the NFC lib to KW. 1 PN7150 Introduction PN7150 is the high-performance version of PN7120, the plug’n play NFC solution for easy integration into any OS environment, reducing Bill of Material (BOM) size and cost. PN71xx controllers are ideal for home-automation applications such as gateways and work seamlessly with NFC connected tags. 2 Tools hardware:FRDM-KW36,PN7150 , some wire software:mcuxpresso11.3 package:NXP-NCI MCUXpresso example Project This package contains the nfc library and example that we need. We will refer the ‘NXPNCI-K64F_example’ firstly. Sdk version: 2.2.8, Example: frdmkw36_rtos_examples_freertos_i2c  3 Steps Hardware part:We need connect the PN7150 to KW36 like the picture. Although we can connect the PN7150 to board through the ardunio connector, the pin’s voltage is not enough to drive the PN7150. So we need a wire connected to U1 to get 3.3V.   PN7150 FRDM-KW36 VBAT/PVDD 3.3V VANT 5V GND GND IRQ PTA16 VEN PTC15 SCL PTB0,I2C0 SDA PTB1,I2C0 Software part:We should add the nfc library and directory into our project. You can check the following picture to know what file is necessary. If you want to know how to add directory into our project, you can refer this link. The red line shows what file we need. Please notice that when we add file path into the mcuxpresso configuration, we also need add the path into ‘Path and Symbols’ .   We need add some macro into ‘Preprocessor’.   We copy the NXPNCI-K64F_example’s main file content into our ‘freertos_i2c.c’. Next, we need modify the file pin_mux.c, tml.c and board.h   In file board.h,add the following macro. Don't forget to enable the pin clock. /* NXPNCI NFC related declaration */ #define BOARD_NXPNCI_I2C_INSTANCE I2C0 #define BOARD_NXPNCI_I2C_BAUDRATE (100000) #define BOARD_NXPNCI_I2C_ADDR       (0x28) #define BOARD_NXPNCI_IRQ_PORTIRQn PORTA_IRQn #define BOARD_NXPNCI_IRQ_GPIO     (GPIOA) #define BOARD_NXPNCI_IRQ_PORT     (PORTA) #define BOARD_NXPNCI_IRQ_PIN      (16U) #define BOARD_NXPNCI_VEN_GPIO     (GPIOC) #define BOARD_NXPNCI_VEN_PORT     (PORTC) #define NXPNCI_VEN_PIN            (5U)     In file pin_mux.c, add head file ‘board.h’. Add the following code in function ’ BOARD_InitPins’. The step is to configure the VEN, IRQ and I2C0. This example contains the I2C1’s code, you can comment them.     /* Initialize NXPNCI GPIO pins below */   /* IRQ and VEN PIN_MUX Configuration */   PORT_SetPinMux(BOARD_NXPNCI_IRQ_PORT, BOARD_NXPNCI_IRQ_PIN, kPORT_MuxAsGpio);   PORT_SetPinMux(BOARD_NXPNCI_VEN_PORT, NXPNCI_VEN_PIN, kPORT_MuxAsGpio);   /* IRQ interrupt Configuration */   NVIC_SetPriority(BOARD_NXPNCI_IRQ_PORTIRQn, 6);   EnableIRQ(BOARD_NXPNCI_IRQ_PORTIRQn);   PORT_SetPinInterruptConfig(BOARD_NXPNCI_IRQ_PORT, BOARD_NXPNCI_IRQ_PIN, kPORT_InterruptRisingEdge);   Finally, in file tml.c, modify PORTC_IRQHandler as PORTA_IRQHandler We finished all steps. 4 Results We use ntag to test the reading and writing operation.   When the tag is closed to the PN7150, we will get the following message.   The text recording is ‘VER=03’. Next, we will modify the text recording We need add the new macro to preprocessor.   We can modify the variable NDEF_MESSAGE in function task_nfc_reader to modify the text recording.   Then we download the program again. We will see the original text ‘VER=03’ and the text has been modified. Then we read the tag again. We will see the new text.   If we want to send the larger text, what should we do? We need modify the macro ‘ADD’. When only 4 characters are sent, ‘ADD’ is 0. And every additional character is added, the ‘ADD’ will add. We modify the tag as ‘Ver=03’, and we have two more characters. So ‘ADD’ needs to be defined as 2   It firstly shows the text ‘Test’. Then it will show the new text ‘Ver=03’. Other tags’ reading and writing operation can be enabled by defining some macro.      
View full article
This example of custom profile uses the Temperature Sensor and Temperature Collector examples as a base, so it can be easily modified. Both examples are in the SDK, so this document explains how to add the Humidity profile, and how to modify the code to get the Humidity Sensor and Collector working. Introduction Generic Attribute Profile (GATT) establishes in detail how to exchange all profile and user data over a BLE connection. GATT deals only with actual data transfer procedures and formats. All standard BLE profiles are based on GATT and must comply with it to operate correctly. This makes GATT a key section of the BLE specification, because every single item of data relevant to applications and users must be formatted, packed, and sent according to the rules. GATT defines two roles: Server and Client. The GATT server stores the data transported over the Attribute Protocol (ATT) and accepts Attribute Protocol requests, commands and confirmations from the GATT client. The GATT client accesses data on the remote GATT server via read, write, notify, or indicate operations. Notify and indicate operations are enabled by the client but initiated by the server, providing a way to push data to the client. Notifications are unacknowledged, while indications are acknowledged. Notifications are therefore faster, but less reliable.  GATT Database establishes a hierarchy to organize attributes. These are the Profile, Service, Characteristic and Descriptor. Profiles are high level definitions that define how services can be used to enable an application and Services are collections of characteristics. Descriptors defined attributes that describe a characteristic value.    To define a GATT Database several macros are provided by the GATT_DB API in the Freescale BLE Stack, which is part KW38 SDK. Server (Sensor)  First, we need to use the Temperature Sensor project as a base, to create our Humidity Custom Profile Server (Sensor). BLE SIG profiles To know if the Profile or service is already defined in the specification, you have to look for in Bluetooth SIG profiles and check in the ble_sig_defines.h file (${workspace_loc:/${ProjName}/bluetooth/host/interface) if this is already declared in the code. In our case, the service is not declared, but the characteristic of the humidity is declared in the specification. Then, we need to check if the characteristic is already included in ble_sig_defines.h. Since, the characteristic is not included, we need to define it as shown next:   /*! Humidity Charactristic UUID */ #define gBleSig_Humidity_d 0x2A6F   GATT Database The Humidity Sensor is going to have the GATT Server, because is going to be the device that has all the information for the GATT Client. On the Temperature Sensor demo have the Battery Service and Device Information, so you only have to change the Temperature Service to Humidity Service    In order to create the demo we need to define or develop a service that has to be the same as in the GATT Client, this is declared in the gatt_uuid128.h.If the new service is not the same, they will never be able to communicate each other. All macros, function or structure in SDK have a common template which helps the application to act accordingly. Hence, we need to define this service in the gatt_uuid128.h as shown next:    /* Humidity */ UUID128(uuid_service_humidity, 0xfe ,0x34 ,0x9b ,0x5f ,0x80 ,0x00 ,0x00 ,0x80 ,0x00 ,0x10 ,0x00 ,0x02 ,0x00 ,0xfa ,0x10 ,0x10)   All the Service and Characteristics is declared in gattdb.h. Descriptors are declared after the Characteristic Value declaration but before the next Characteristic declaration. In this case the permission is the CharPresFormatDescriptor that have specific description by the standard. The Units of the Humidity Characteristic is on Percentage that is 0x27AD. Client Characteristic Configuration Descriptor (CCCD) is a descriptor where clients write some of the bits to activate Server notifications and/or indications.   PRIMARY_SERVICE_UUID128(service_humidity, uuid_service_humidity) CHARACTERISTIC(char_humidity, gBleSig_Humidity_d, (gGattCharPropNotify_c)) VALUE(value_humidity, gBleSig_Humidity_d, (gPermissionNone_c), 2, 0x00, 0x25) DESCRIPTOR(desc_humidity, gBleSig_CharPresFormatDescriptor_d, (gPermissionFlagReadable_c), 7, 0x0E, 0x00, 0xAD, 0x27, 0x00, 0x00, 0x00) CCCD(cccd_humidity)   After that, create a folder humidity in the next path ${workspace_loc:/${ProjName}/bluetooth/profiles. Found the temperature folder, copy the temperature_service.c and paste inside of the humidity folder with another name (humidity_service.c). Then go back and look for the interface folder, copy temperature_interface.h and change the name (humidity_interface.h) in the same path. You need to include the path of the created folder. Project properties>C/C+ Build>Settings>Tool Settings>MCU C Compiler>Includes: Humidity Interface The humidity_interface.h file should have the following code. The Service structure has the service handle, and the initialization value.   /*! Humidity Service - Configuration */ typedef struct humsConfig_tag { uint16_t serviceHandle; int16_t initialHumidity; } humsConfig_t; /*! Humidity Client - Configuration */ typedef struct humcConfig_tag { uint16_t hService; uint16_t hHumidity; uint16_t hHumCccd; uint16_t hHumDesc; gattDbCharPresFormat_t humFormat; } humcConfig_t;   Humidity Service At minimum on humidity_service.c file, should have the following code. The service stores the device identification for the connected client. This value is changed on subscription and non-subscription events.   /*! Humidity Service - Subscribed Client*/ static deviceId_t mHums_SubscribedClientId;   The initialization of the service is made by calling the start procedure. This function is usually called when the application is initialized. In this case is on the BleApp_Config().   bleResult_t Hums_Start(humsConfig_t *pServiceConfig) { mHums_SubscribedClientId = gInvalidDeviceId_c; /* Set the initial value of the humidity characteristic */ return Hums_RecordHumidityMeasurement(pServiceConfig->serviceHandle, pServiceConfig->initialHumidity); }   On stop function, the unsubscribe function is called.   bleResult_t Hums_Stop(humsConfig_t *pServiceConfig) { /* Stop functionality by unsubscribing */ return Hums_Unsubscribe(); } bleResult_t Hums_Unsubscribe(void) { /* Unsubscribe by invalidating the client ID */ mHums_SubscribedClientId = gInvalidDeviceId_c; return gBleSuccess_c; }   The subscribe function will be used in the main file, to subscribe the GATT client to the Humidity service.   bleResult_t Hums_Subscribe(deviceId_t clientDeviceId) { /* Subscribe by saving the client ID */ mHums_SubscribedClientId = clientDeviceId; return gBleSuccess_c; }   Depending on the complexity of the service, the API will implement additional functions. For the Humidity Sensor only have a one characteristic. The measurement will be saving on the GATT database and send the notification to the client. This function will need the service handle and the new value as input parameters.   bleResult_t Hums_RecordHumidityMeasurement(uint16_t serviceHandle, int16_t humidity) { uint16_t handle; bleResult_t result; bleUuid_t uuid = Uuid16(gBleSig_Humidity_d); /* Get handle of Humidity characteristic */ result = GattDb_FindCharValueHandleInService(serviceHandle, gBleUuidType16_c, &uuid, &handle); if (result != gBleSuccess_c) return result; /* Update characteristic value */ result = GattDb_WriteAttribute(handle, sizeof(uint16_t), (uint8_t*) &humidity); if (result != gBleSuccess_c) return result; Hts_SendHumidityMeasurementNotification(handle); return gBleSuccess_c; }   After save the measurement on the GATT database with GattDb_WriteAttribute function we send the notification. To send the notification, first have to get the CCCD and after check if the notification is active, if is active send the notification.   static void Hts_SendHumidityMeasurementNotification ( uint16_t handle ) { uint16_t hCccd; bool_t isNotificationActive; /* Get handle of CCCD */ if (GattDb_FindCccdHandleForCharValueHandle(handle, &hCccd) != gBleSuccess_c) return; if (gBleSuccess_c == Gap_CheckNotificationStatus (mHums_SubscribedClientId, hCccd, &isNotificationActive) && TRUE == isNotificationActive) { GattServer_SendNotification(mHums_SubscribedClientId, handle); } }   Humidity Sensor Main file There are some modifications that have to be done, to use the new Humidity profile in our sensor example. First, we need to declare the humidity service:   static humsConfig_t humsServiceConfig = {(uint16_t)service_humidity, 0};   Then, we need to add or modify the following functions: BleApp_Start You need to modify this line:   /* Device is connected, send humidity value */ BleApp_SendHumidity();   BleApp_Config You need to start the Humidity Service, and to modify the PrintString line:   humsServiceConfig.initialHumidity = 0; (void)Hums_Start(&humsServiceConfig);     AppPrintString("\r\nHumidity sensor -> Press switch to start advertising.\r\n");   BleApp_ConnectionCallback There are some modifications required in two Connection Events. gConnEvtConnected_c   (void)Hums_Subscribe(peerDeviceId); gConnEvtDisconnected_c   gConnEvtDisconnected_c   (void)Hums_Unsubscribe();   BleApp_GattServerCallback   /* Notify the humidity value when CCCD is written */ BleApp_SendHumidity()   BleApp_SendHumidity And, we need to add this function:   static void BleApp_SendHumidity(void) { (void)TMR_StopTimer(appTimerId); /* Update with initial humidity */ (void)Hums_RecordHumidityMeasurement((uint16_t)service_humidity, (int16_t)(BOARD_GetTemperature())); #if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) /* Start Sleep After Data timer */ (void)TMR_StartLowPowerTimer(appTimerId, gTmrLowPowerSecondTimer_c, TmrSeconds(gGoToSleepAfterDataTime_c), DisconnectTimerCallback, NULL); #endif }   In this example, the Record Humidity uses the BOARD_GetTemperature, to use the example without any external sensor and to be able to see a change in the collector, but, in this section would be a GetHumidity function. Client (Collector)  First, we need to use the Temperature Collector project as a base, to create our Humidity Custom Profile Client (Collector). BLE SIG profiles The same applies for the Client. To know if the Profile or service is already defined in the specification, you have to look for in Bluetooth SIG profiles and check in the ble_sig_defines.h file (${workspace_loc:/${ProjName}/bluetooth/host/interface) if this is already declared in the code. In our case, the service is not declared, but the characteristic of the humidity is declared in the specification. Then, we need to check if the characteristic is already included in ble_sig_defines.h. Since, the characteristic is not included, we need to define it as shown next:   /*! Humidity Charactristic UUID */ #define gBleSig_Humidity_d 0x2A6F   GATT Database The Humidity Collector is going to have the GATT client; this is the device that will receive all information from  the GATT server. Demo provided in this post works like the Temperature Collector. When the Collector enables the notifications from the sensor, received notifications will be printed in the serial terminal. In order to create the demo we need to define or develop a service that has to be the same as in the GATT Server, this is declared in the gatt_uuid128.h.If the new service is not the same, they will never be able to communicate each other. All macros, function or structure in SDK have a common template which helps the application to act accordingly. Hence, we need to define this service in the gatt_uuid128.h as shown next:   /* Humidity */ UUID128(uuid_service_humidity, 0xfe ,0x34 ,0x9b ,0x5f ,0x80 ,0x00 ,0x00 ,0x80 ,0x00 ,0x10 ,0x00 ,0x02 ,0x00 ,0xfa ,0x10 ,0x10)   After that, copy the humidity profile folder from the Sensor project, to the Collector project ${workspace_loc:/${ProjName}/bluetooth/profiles. And also for this project, include the path of the new folder. Project properties>C/C+ Build>Settings>Tool Settings>MCU C Compiler>Includes: Humidity Collector Main file In the Collector source file, we need to do also some modifications, to use the Humidity Profile. First, we need to modify the Custom Information of the Peer device:   humcConfig_t humsClientConfig;   BleApp_StoreServiceHandles   static void BleApp_StoreServiceHandles ( gattService_t *pService ) { uint8_t i,j; if ((pService->uuidType == gBleUuidType128_c) && FLib_MemCmp(pService->uuid.uuid128, uuid_service_humidity, 16)) { /* Found Humidity Service */ mPeerInformation.customInfo.humsClientConfig.hService = pService->startHandle; for (i = 0; i < pService->cNumCharacteristics; i++) { if ((pService->aCharacteristics[i].value.uuidType == gBleUuidType16_c) && (pService->aCharacteristics[i].value.uuid.uuid16 == gBleSig_Humidity_d)) { /* Found Humudity Char */ mPeerInformation.customInfo.humsClientConfig.hHumidity = pService->aCharacteristics[i].value.handle; for (j = 0; j < pService->aCharacteristics[i].cNumDescriptors; j++) { if (pService->aCharacteristics[i].aDescriptors[j].uuidType == gBleUuidType16_c) { switch (pService->aCharacteristics[i].aDescriptors[j].uuid.uuid16) { /* Found Humidity Char Presentation Format Descriptor */ case gBleSig_CharPresFormatDescriptor_d: { mPeerInformation.customInfo.humsClientConfig.hHumDesc = pService->aCharacteristics[i].aDescriptors[j].handle; break; } /* Found Humidity Char CCCD */ case gBleSig_CCCD_d: { mPeerInformation.customInfo.humsClientConfig.hHumCccd = pService->aCharacteristics[i].aDescriptors[j].handle; break; } default: ; /* No action required */ break; } } } } } } }   BleApp_StoreDescValues   if (pDesc->handle == mPeerInformation.customInfo.humsClientConfig.hHumDesc) { /* Store Humidity format*/ FLib_MemCpy(&mPeerInformation.customInfo.humsClientConfig.humFormat, pDesc->paValue, pDesc->valueLength); }   BleApp_PrintHumidity   /*www.bluetooth.com/specifications/assigned-numbers/units */ if (mPeerInformation.customInfo.humsClientConfig.humFormat.unitUuid16 == 0x27ADU) { AppPrintString(" %\r\n"); } else { AppPrintString("\r\n"); }   BleApp_GattNotificationCallback   if (characteristicValueHandle == mPeerInformation.customInfo.humsClientConfig.hHumidity) { BleApp_PrintHumidity(Utils_ExtractTwoByteValue(aValue)); }    CheckScanEvent   foundMatch = MatchDataInAdvElementList(&adElement, &uuid_service_humidity, 16);   BleApp_StateMachineHandler mAppIdle_c   if (mPeerInformation.customInfo.humsClientConfig.hHumidity != gGattDbInvalidHandle_d)   mAppServiceDisc_c   if (mPeerInformation.customInfo.humsClientConfig.hHumDesc != 0U) mpCharProcBuffer->handle = mPeerInformation.customInfo.humsClientConfig.hHumDesc;   mAppReadDescriptor_c   if (mPeerInformation.customInfo.humsClientConfig.hHumCccd != 0U)   BleApp_ConfigureNotifications   mpCharProcBuffer->handle = mPeerInformation.customInfo.humsClientConfig.hHumCccd;   Demonstration Now, after connection, every time that you press the SW3 on KW38 Humidity Sensor is going to send the value to KW38 Humidity Collector.  
View full article
1 Introduction Two development boards transmit control information through ble. One development board connects to paj7620 and provides gesture information through IIC bus. The other development board uses ble and USB HID. Ble is used to receive data, and USB HID is used to simulate keyboard input and control ppt                  Figure  1 2 Preparation We need two development boards qn908x and gesture control device paj7620. We use IAR as development enviroment.The example we use is temperature_sensor, and temperature_ colloctor. The SDK version is 2.2.3   3 Code 3.1  temperature_sensor code We want to implement IIC to read gesture information from paj7620 and send data. The pins used by IIC are PA6 and PA7 Simply encapsulate the IIC reading and writing code in the code to create i2c_ operation.c and i2c_ operation.h. Realize IIC initialization and reading / writing register function in it                        Figure  2                        Figure  3   3.1.1 After having these functions, we begin to write gesture recognition code. First, we add two blank files paj7620.c and paj7620.h into our project.   Select bank register area                               Figure 4   Wake up paj7620 to read device state                    Figure 5   Initialize device                    Figure 6   Gesture test function                                   Figure 7   3.1.2 When you are ready to read the device information, You should initialize IIC and paj7620 in BleApp_Init function                                Figure 8 In principle, we need to create a custom service for the PAJ device, but we replace the temperature data as our gesture control data. If you want to create a custom service, refer to this link custom profile   3.1.3 Create a timer that sends gesture data regularly. In file temerature_sensor.c Define a timer,static tmrTimerID_t dataTimerId; Allocate a timer, dataTimerId = TMR_AllocateTimer(); Define the callback function of this timer                                           Figure 9 Start timer                                    Figure 10 Close the low power mode. #define cPWR_UsePowerDownMode 0 3.2 temperature_collector code The most important thing here is to port USB HID into our project. The USB  example we use is the USB keyboard and mouse. 3.2.1 Add the OSA and USB folder under the example to the project directory, and copy the file to the corresponding folder according to the file structure of the original example.                      Figure 11 3.2.2 Add header file directory after completion                                           Figure 12 At the same time, in this tab, add two macro definitions USB_STACK_FREERTOS_HEAP_SIZE=16384 USB_STACK_FREERTOS   3.2.3 Next, we need to modify the main function in usb example . Open composite.c file.                      Figure 13 It calls the APP_task. So this function also need to be modified.                                   Figure 14 3.2.4Find hid_mouse.c,Comment function USB_DeviceHidMouseAction Find hid_keyboard.h. Define the gesture information.                                  Figure 15 Find hid_keyboard.c. We need to modify the function USB_DeviceHidKeyboardAction as following figure.                                                  Figure 16   Among them, we also need to implement the following function. When the up hand gesture is detected, the previous ppt will be played. The down hand gesture will be the next PPT, the left hand gesture will exit PPT, and the forward hand gesture will play ppt                                                  Figure 17 It also refers to an external variable gesture_from_server. The variable definition is in file temperature_ collocation.c,.     3.2.5 After that, let's go to BleApp_Statemachinehandler function in temperature_colloctor.c. In case mApppRunning_c, we will call usb_main to initialize USB HID                                                  Figure 18 3.2.6 In BleApp_PrintTemperature, we will save the gesture data to gesture_from_server                                                         Figure 19 We finished the all steps.        
View full article
Introduction   This post explains how to create a BLE GATT database using FSCI commands sent to the BLE Server device. Additionally, this document explains how to set up the fields of each FSCI command used to create the BLE GATT database for the BLE Server.   Main FSCI commands to create the BLE GATT DB in the BLE Server device   The following, are the main commands to create, write and read the GATT DB from the BLE Server perspective. The purpose of this post is to serve as a reference and summary of the most important commands. The full list of commands FSCI commands can be found in the Framework Serial Connectivity Interface (FSCI) for Bluetooth Low Energy Host Stack documentation within your SDK package. GATT-InitRequest This command is used to initialize the GATT database at runtime, and it must be sent before any other command to declare a database in your BLE Server device. GATTServer-RegisterCallback.Request This command installs an application callback for the GATT Server module, enabling the device to respond to the FSCI request from the CPU application through an FSCI indication. GATTDBDynamic-AddPrimaryServiceDeclaration.Request It adds a primary service to the database. It has 3 parameters that should be configured, the desired handle, the UUID type (16 bits, 32 bits, 128 bits), and the UUID value. Usually, the desired handle should be set to zero and the stack will assign the handle of the primary service automatically.   If the GATT application callback was installed through the GATTServer-RegisterCallback.Request command, the GATT Server responds to the GATTDBDynamic-AddPrimaryServiceDeclaration.Request command with a GATTDBDynamic-AddPrimaryServiceDeclaration.Indication that contains the handle assigned to the primary service. The following example shows how to prepare this command to define the battery service in the database. GATTDBDynamic-AddCharacteristicDeclarationAndValue.Request It adds a characteristic and its value to the database. It has 7 parameters that should be configured, the UUID type (16 bits, 32 bits, 128 bits), the UUID value, characteristic properties, the maximum length of the value (only for variable-length values), the initial length of the value, the initial value of the characteristic and value access permissions. The characteristic declared using this command, belongs to the last primary service declared in the database. For values with a fixed length, the maximum length parameter should be set to 0, and the length is obtained from the initial length of the value parameter.   If the GATT application callback was installed, the response of this command is indicated by the GATTDBDynamic-AddCharacteristicDeclarationAndValue.Indication command. The following example shows how to prepare this command to define the battery level characteristic in the database with a fixed length of 1 byte and an initial value of 90%. GATTDBDynamic-AddCharacteristicDescriptor.Request It adds a characteristic descriptor to the database. It has 5 parameters that should be configured, the UUID type (16 bits, 32 bits, 128 bits), UUID value, length of the descriptor value, descriptor’s value, and descriptor access permissions. The descriptor declared using this command, belongs to the last characteristic declared in the database.   If the GATT application callback was installed, the response of this command is indicated by the GATTDBDynamic-AddCharacteristicDescriptor.Indication command. The following example shows how to prepare this command to add the characteristic presentation format descriptor of the battery level characteristic in the database.   GATTDBDynamic-AddCccd.Request It adds a CCDD into the database. This command does not have parameters. The CCCD declared using this command, belongs to the last characteristic declared in the database. The response of this command is indicated by GATTDBDynamic-AddCccd.Indication.   GATTDB-FindServiceHandle.Request This command is used to find the handle of a service previously declared in the database. It has 3 parameters that should be configured, the handle to start the search (should be 1 on the first call), the UUID type of the service to find (16 bits, 32 bits, 128 bits), and the UUID value of the service that you are searching.   If the GATT application callback was installed, the response of this command is indicated by the GATTDB-FindServiceHandle.Indication command, which contains the handle of the found service. The following example shows how to prepare this command to find the handle of the battery service declared in the previous examples. Notice that the result of the search corresponds to the handle returned by the GATTDBDynamic-AddPrimaryServiceDeclaration.Indication as expected.   GATTDB-FindCharValueHandleInService It finds the characteristic´s handle of a given service previously declared in the database. It has 3 parameters that should be configured, the handle of the service that contains the characteristic, the UUID type of the characteristic to find (16 bits, 32 bits, 128 bits), and the UUID value of the characteristic that you are searching for.   If the GATT application callback was installed, the response of this command is indicated by the GATTDB-FindCharValueHandleInService.Indication command, which contains the handle of the found characteristic’s value. The following example shows how to prepare this command to find the handle of the battery level value. Notice that the result of the search corresponds to the handle returned by the GATTDBDynamic-AddCharacteristicDeclarationAndValue.Indication plus one, because the AddCharacteristicDeclarationAndValueIndication command returns the handle of the characteristic and, on the other hand, FindCharValueHandleInService returns the handle of the characteristic’s value. GATTDB-FindDescriptorHandleForcharValueHandle.Request It finds the descriptor´s handle of a given characteristic previously declared in the database. It has 3 parameters that should be configured, the handle of the characteristic’s value that contains the descriptor, the UUID type of the descriptor to find (16 bits, 32 bits, 128 bits), and the UUID value of the descriptor that you are searching.   If the GATT application callback was installed, the response of this command is indicated by the GATTDB-FindDescriptorHandleForCharValueHandle.Indication command, which contains the handle of the found descriptor. The following example shows how to prepare this command to find the handle of the characteristic presentation format descriptor. The result corresponds to the handle returned by the GATTDBDynamic-AddCharacteristicDescriptor.Indication   GATTDB-FindCccdHandleForCharValueHandle.Request It finds the CCCD’s handle of a given characteristic previously declared in the database. It has only one parameter, the handle of the characteristic’s value that contains the CCCD.   If the GATT application callback was installed, the response of this command is indicated by the GATTDB-FindCccdHandleForCharValueHandle.Indication command, which contains the handle of the found CCCD. The following example shows how to prepare this command to find the handle of CCCD. The result corresponds to the handle returned by the GATTDBDynamic-AddCccd.Indication.   GATTDB-WriteAttribute.Request It writes the value of a given attribute from the application level. It has 3 parameters that should be configured, the handle of the attribute that you want to write, the length of the value in bytes, and the new value.   In the following example, we will modify the battery level characteristic’s value from 90% to 80%.   GATTDB-ReadAttribute.Request   It reads the value of a given attribute from the application level. It has 2 parameters that should be configured, the handle of the attribute that you want to read, and the maximum bytes that you want to read. The GATT application callback must be installed, since the response of this command indicated by the GATTDB-ReadAttribute.Indication command contains the value read from the database. In the following example, we will read the battery level characteristic’s value, the result is 80%.      
View full article
Introduction The goal of this example is to demonstrate automatic role switching between Central and Peripheral of BLE QN9080 SIP and indicate the proximity of another BLE module using RSSI value. The automatic Role Switching feature can be used for continuously scan the presence of other BLE device and also to advertise so that other BLE device can scan it. The use case is to maintain social distancing and trigger a warning if the two devices are closer than a threshold distance. RSSI stands for Received Signal Strength Indicator which shows the power of received radio signal. Bare metal ‘Wireless_UART’ example is used from ‘SDK_2.x_QN908xCDK’ version 2.2.2 Timer Configuration As the device needs to switch its role after every particular time interval, so a timer is required to be initialized as it can be seen in below screenshot. Next step is to allocate Timer ID to the declared variable and start the timer. In this case, the timer shall go to callback function after the time(seconds) defined by the macro 'gSwitchTime'. This is done in 'BleApp_Config' function. After the specified time interval, timer stops and enters the callback function where switching of roles takes place. The main point that needs to be highlighted here is that while going into scanning mode, advertising mode should be stopped and vice versa. In advertising, the LED will be turned off. In scanning, the LED glows based on the RSSI. Central Configuration While in Central mode, device scans the presence of other bluetooth devices. Here, we need to check the RSSI value of received signals from those devices. There is a register available in QN9080 where the RSSI can be read after a received signal. RSSI is always negative, so the register stores the 2's compliment of the actual value. Below formula can be used to get the actual value of RSSI:- Actual RSSI = NOT(RSSI) + 1; This formula will give the positive value which is inversely proportional to Signal strength. In the callback function of scanning 'BleApp_ScanningCallback', filtering is applied and following decisions are taken based on filtered value:- Red LED will glow if the filtered value is lesser than a threshold value. Green LED will glow if the filtered value is greater than a threshold value. Hysteresis of 6 counts is taken to nullify the effect of fluctuation. As there is no need to make connections with the available devices, so the function requesting to make connection with the scanned device will be deleted. Peripheral Configuration Advertising interval can be changed as per requirement by making changes in the following macros:- To advertise at a fixed interval, value of minimum and maximum interval should be same. Test Setup Flash the code in two BLE EVK's. Power ON the EVK's. Red LED blinks if the EVK's are closer than a certain distance. Green LED blinks if the distance between the EVK's is greater than a threshold value. During blinking, When the LED is off, it means that the EVK is in advertising mode and when LED is ON(Red/Green), it means that EVK is in scanning mode. Note:- RSSI varies with environment, surrounding etc., so the threshold value of distance may vary with variation in testing condition. Demo code is attached for out of the box testing.
View full article
Overview Bluetooth Low Energy offers the ability to broadcast data in format of non-connectable advertising packets while not being in a connection. This GAP Advertisement is widely known as a beacon and is used in today’s IoT applications in different forms. This article will present the current beacon format in our demo application from the KW40Z software package and how to create the most popular beacon formats on the market. The advertising packet format and payload are declared in the gAppAdvertisingData structure from app_config.c. This structure points to an array of AD elements, advScanStruct: static const gapAdStructure_t advScanStruct[] = {   {     .length = NumberOfElements(adData0) + 1,     .adType = gAdFlags_c,     .aData = (void *)adData0   },    {     .length = NumberOfElements(adData1) + 1,     .adType = gAdManufacturerSpecificData_c,     .aData = (void *)adData1   } }; Due to the fact that all beacons use the advertising flags structure and that the advertising PDU is 31 bytes in length (Bluetooth Low Energy v4.1), the maximum payload length is 28 bytes, including length and type for the AD elements. The AD Flags element is declared as it follows: static const uint8_t adData0[1] =  { (gapAdTypeFlags_t)(gLeGeneralDiscoverableMode_c | gBrEdrNotSupported_c) }; The demo application uses a hash function to generate a random UUID for the KW40Z default beacon. This is done in BleApp_Init: void BleApp_Init(void) {     sha1Context_t ctx;         /* Initialize sha buffer with values from SIM_UID */     FLib_MemCopy32Unaligned(&ctx.buffer[0], SIM_UIDL);     FLib_MemCopy32Unaligned(&ctx.buffer[4], SIM_UIDML);     FLib_MemCopy32Unaligned(&ctx.buffer[8], SIM_UIDMH);     FLib_MemCopy32Unaligned(&ctx.buffer[12], 0);          SHA1_Hash(&ctx, ctx.buffer, 16);         /* Updated UUID value from advertising data with the hashed value */     FLib_MemCpy(&gAppAdvertisingData.aAdStructures[1].aData[3], ctx.hash, 16); } When implementing a constant beacon payload, please bear in mind to disable this code section. KW40Z Default Beacon The KW40Z software implements a proprietary beacon with the maximum ADV payload and uses the following Manufacturer Specific Advertising Data structure of 26 bytes. This is the default implementation of the beacon demo example from the KW40Z Connectivity Software package. static uint8_t adData1[26] = {     /* Company Identifier*/     0xFF, 0x01     /* Beacon Identifier */     0xBC,     /* UUID */                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,                                   /* A */                     0x00, 0x00,     /* B */                     0x00, 0x00,     /* C */                     0x00, 0x00,     /* RSSI at 1m */            0x1E}; iBeacon iBeacon is a protocol designed by Apple. It uses a 20 byte payload that consists of the following identifying information [1] : To advertise an iBeacon packet, the user needs to change the second AD element, adData1, like below: static uint8_t adData1[25] = {                                0x4C, 0x00,                                   0x02, 0x15,         /* UUID */             0xD9, 0xB9, 0xEC, 0x1F, 0x39, 0x25, 0x43, 0xD0, 0x80, 0xA9, 0x1E, 0x39, 0xD4, 0xCE, 0xA9, 0x5C,         /* Major Version */    0x00, 0x01         /* Minor Version */    0x00, 0x0A,                                0xC5}; AltBeacon AltBeacon is an open specification designed for proximity beacon advertisements [2]. It also uses a Manufacturer Specific Advertising Data structure: To advertise an AltBeacon packet, the user needs to change the second AD element, like below: static uint8_t adData1[26] = {     /* MFG ID*/         0xFF, 0x01,     /* Beacon Code */   0xBE, 0xAC,     /* Beacon ID */     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,     /* Ref RSSI*/       0xC5,     /* MFG RSVD*/       0x00}; Eddystone™ Eddystone™ is an open Bluetooth® Smart beacon format from Google [3]. It offers three data type packets: Eddystone™-UID Eddystone™-URL Eddystone™-TLM Eddystone™ uses two advertising structures: Complete List of 16-bit Service UUIDs structure, which contains the Eddystone Service UUID (0xFEAA). Service Data structure, which also contains the Eddystone™ Service UUID (0xFEAA). Thus, advScanStruct will now have 3 elements: static const gapAdStructure_t advScanStruct[] = {   {     .length = NumberOfElements(adData0) + 1,     .adType = gAdFlags_c,     .aData = (void *)adData0   },    {     .length = NumberOfElements(adData1) + 1,     .adType = gAdComplete16bitServiceList_c,     .aData = (void *)adData1   },   {     .length = NumberOfElements(adData2) + 1,     .adType = gAdServiceData16bit_c,     .aData = (void *)adData2   } }; The complete List of 16-bit Service UUIDs element will look like: static const uint8_t adData1[2] =  { 0xAA, 0xFE }; Eddystone™-UID Eddystone™-UID broadcasts a unique 16-bit Beacon ID to identify a particular device in a group. The Service Data block has the following structure: To implement this, the user needs to add a third AD element, as follows: static uint8_t adData2[22] = {     /* ID */ 0xAA, 0xFE,     /* Frame Type */    0x00,     /* Ranging Data */  0xEE,     /* Namespace */     0x8B, 0x0C, 0xA7, 0x50, 0x09, 0x54, 0x77, 0xCB, 0x3E, 0x77,     /* Instance */      0x00, 0x00, 0x00, 0x00, 0x00, 0x01,     /* RFU */           0x00, 0x00}; Eddystone™-URL Eddystone™-URL broadcasts a compressed URL. The Service Data block has the following structure: In this example, we will implement a beacon which will advertise NXP’s webpage, http://www.nxp.com. To implement this, the user needs to add a third AD element, as follows: static const uint8_t adData2[9] = {     /* ID */ 0xAA, 0xFE,     /* Frame Type */    0x10,     /* TX Power */      0xEE,     /* URL scheme */    0x00,     /* Encode URL */    'n', 'x, 'p', 0x07}; Eddystone™-TLM Eddystone™-TLM broadcasts telemetry data about the beacon device operation. The Service Data block has the following structure: To implement this, the user needs to add a third AD element, as follows: static uint8_t adData2[16] = {     /* ID */ 0xAA, 0xFE,     /* Frame Type */    0x20,     /* TLM Version */   0x00,     /* VBATT */        0x00, 0x00,     /* TEMP */         0x00, 0x00,     /* ADV_CNT */      0x00, 0x00, 0x00, 0x00,     /* SEC_CNT */      0x00, 0x00, 0x00, 0x00};
View full article
Overview The Bluetooth specification defines 4 Generic Access Profile (GAP) roles for devices operating over a Low Energy physical transport [1]: Peripheral Central Broadcaster Observer The Bluetooth Low Energy Host Stack implementation on the Kinetis KW40Z offers devices the possibility to change between any of the 4 roles at run time. This article will present the interaction with the Bluetooth Low Energy Host API needed to implement a GAP multiple role device. General Procedure instructions Running the GAP roles requires the application to go through the following 3 steps: Configuration - Stack configuration for the desired GAP role The application needs to configure the stack parameters, e.g. advertising parameters, advertising data, scan parameters, callbacks. Note that configuration of the advertising parameters or scanning response and advertising data can be done only once if the values don’t change at runtime. The configuration is always made in the Link Layer Standby state. Start - Running the role The application needs to start advertising, scanning or initiate connection. Stop - Return to Standby state When changing between roles, the Link layer must always go through the Link Layer Standby state. Running as a GAP Broadcaster or GAP Peripheral The GAP Broadcaster or Peripheral sends advertising events. Additionally, the GAP Peripheral will accept the establishment of a LE link. This is why the GAP Observer will only support the Non Connectable Advertising mode (gAdvNonConnectable_c). Both roles requires configuration of advertising data, advertising parameters. The configuration (gAppAdvertisingData, gAppScanRspData and gAdvParams) usually resides in app_config.c. The confirmation events for setting these parameters is received in BleApp_GenericCallback. The confirmation event for the changing state of advertising is received in BleApp_AdvertisingCallback. Configuration /* Setup Advertising and scanning data */ Gap_SetAdvertisingData(&gAppAdvertisingData, &gAppScanRspData); /* Setting only for GAP Broadcaster role */ gAdvParams. advertisingType = gAdvNonConnectable_c; /* Set advertising parameters*/ Gap_SetAdvertisingParameters(&gAdvParams); Start App_StartAdvertising(BleApp_AdvertisingCallback, BleApp_ConnectionCallback); Stop Gap_StopAdvertising(); Running as a GAP Observer The GAP Observer receives advertising events. Unlike the GAP Peripheral or Broadcaster, it does not need to set scanning parameters separately. It passes the configuration with the start procedure. The configuration (gAppScanParams) usually resides in app_config.c. The confirmation event for the changing state of scanning is received in BleApp_ScanningCallback. Configuration and Start App_StartScanning(&gAppScanParams, BleApp_ScanningCallback); Stop Gap_StopScanning (); Running as a GAP Central The GAP Central initiates the establishment of the LE link. Like the GAP Observer, it passes the configuration with the start procedure. The configuration (gConnReqParams) usually resides in app_config.c. The confirmation event for the changing state of link is received in BleApp_ConnectionCallback. Configuration and Start Gap_Connect(&gConnReqParams, BleApp_ConnectionCallback); Stop Gap_Disconnect(deviceId); Example An out-of-the box example for multiple role is attached. The application named blood_pressure_multi_role implements a Blood Pressure GATT client and server and can switch between the following GAP roles: Peripheral, Observer and Central. The contents of the archive needs to be copied to the following location: <Installer Path>\KW40Z_Connectivity_Software_1.0.1\ConnSw\examples\bluetooth\ The application can be found at: <Install Path specified>\KW40Z_Connectivity_Software_1.0.1\ConnSw\examples\bluetooth\blood_pressure_multi_role\frdmkw40z\bare_metal\build\iar\blood_pressure_multi_role.eww Running as GAP Peripheral Press SW4. LED1 will start flashing and the console will show that the Link Layer enters Advertising. If the Link Layer was in a previous state, it will go through Standby. static void BleApp_Advertise(void) {     /* Ensure Link Layer is in Standby */     BleApp_GoToStandby();         shell_write(" GAP Role: Peripheral\n\r");     mGapRole = gGapPeripheral_c;         /* Start GAP Peripheral */     App_StartAdvertising(BleApp_AdvertisingCallback, BleApp_ConnectionCallback); } Running as GAP Observer Press SW3. A chasing LED pattern will start and the console will show that the Link Layer enters Scanning. If the Link Layer was in a previous state, it will go through Standby. static void BleApp_Scan(void) {     /* Ensure Link Layer is in Standby */     BleApp_GoToStandby();         shell_write(" GAP Role: Observer\n\r");     mGapRole = gGapObserver_c;         /* Start GAP Observer */     App_StartScanning(&gAppScanParams, BleApp_ScanningCallback); } Running as GAP Central If the Link Layer is in scanning and finds a Blood Pressure Sensor, it will go through Standby and initiate connection. static void BleApp_Connect(void) {     /* Ensure Link Layer is in Standby */     BleApp_GoToStandby();         shell_write(" GAP Role: Central\n\r");     mGapRole = gGapCentral_c;         /* Start GAP Central */     Gap_Connect(&gConnReqParams, BleApp_ConnectionCallback); } Returning to Standby Pressing SW3 for more than 2 seconds, brings the Link Layer back in Standby. static void BleApp_GoToStandby(void) {     /* Check if connection is on */     if (mPeerInformation.deviceId != gInvalidDeviceId_c)     {         /* Stop GAP Central or Peripheral */         Gap_Disconnect(mPeerInformation.deviceId);     }     if (mAdvOn)     {         /* Stop GAP Peripheral or Bradcaster */         Gap_StopAdvertising();     }         if (mScanningOn)     {         /* Stop GAP Observer */         Gap_StopScanning();     } } References [1] BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C], 2.2 PROFILE ROLES
View full article
Thread is a secure, wireless, simplified IPv6-based mesh networking protocol developed by industry leading technology companies, including Freescale, for connecting devices to each other, to the internet and to the cloud. Before starting a Thread Network implementation, users should be familiar with some concepts and how they are related to Thread protocol. IPv6 Addressing Devices in the Thread stack support IPv6 addressing IPv6 addresses are 128-bit identifiers (IPv4 is only 32-bit) for interfaces and sets of interfaces.  Thread supports the following types of addresses: Unicast:  An identifier for a single interface.  A packet sent to a unicast address is delivered to the interface identified by that address. Multicast: An identifier for a set of interfaces (typically belonging to different nodes).  A packet sent to a multicast address is delivered to all interfaces identified by that address. NOTES There are no broadcast addresses in IPv6, their function being superseded by multicast addresses. Each device joining the Thread Network is also assigned a 16-bit short address as specified in IEEE 802.15.4. 6LoWPAN All Thread devices use 6LoWPAN 6LoWPAN stands for “IPv6 over Low Power Wireless Personal Networks”. 6LoWPAN is a set of standards defined by the Internet Engineering Task Force (IETF), which enables the efficient use of IPv6 over low-power, low-rate wireless networks on simple embedded devices through an adaptation layer and the optimization of related protocols. Its main goal is to send/receive IPv6 packets over 802.15.4 links. Next figure compares IP and 6LoWPAN protocol stacks: The following concepts would explain the transport layer. ICMP Thread devices support the ICMPv6 (Internet Control Message Protocol version 6) protocol and ICMPv6 error messages, as well as the echo request and echo reply messages. The Internet Control Message Protocol (ICMP) is an error reporting and diagnostic utility and is considered a required part of any IP implementation. ICMPs are used by routers, intermediary devices, or hosts to communicate updates or error information to other routers, intermediary devices, or hosts. For instance, ICMPv6 is used by IPv6 nodes to report errors encountered in processing packets, and to perform other internet-layer functions, such as diagnostics. ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems, nor is it regularly employed by end-user network applications.  The ICMPv6 messages have the following general format: The type field indicates the type of the message.  Its value determines the format of the remaining data. The code field depends on the message type.  It is used to create an additional level of message granularity. The checksum field is used to detect data corruption in the ICMPv6 message and parts of the IPv6 header. ICMPv6 messages are grouped into two classes: error messages and informational messages.  Error messages are identified as such by a zero in the high-order bit of their message Type field values.  Thus,   error messages have message types from 0 to 127; informational messages have message types from 128 to 255. UDP The Thread stack supports UDP for messaging between devices. This User Datagram Protocol  (UDP)  is defined  to  make available  a datagram   mode of  packet-switched   computer communication  in  the environment  of an  interconnected  set  of  computer  networks, assuming that the Internet  Protocol (IP) is used as the underlying protocol. With UDP, applications can send data messages to other hosts on an IP network without prior communications to set up special transmission channels or data paths. UDP is suitable for purposes where error checking and correction is either not necessary or is performed in the application, avoiding the overhead of such processing at the network interface level. The UDP format is as follows: Source Port is an optional field, when meaningful, it indicates the port of the sending  process,  and may be assumed  to be the port  to which a reply should be addressed  in the absence of any other information.  If not used, a value of zero is inserted. Destination Port has a meaning within the context of a particular internet destination address. Length is the length in octets of this user datagram including this header and the data.   (This means the minimum value of the length is eight.) Checksum is the 16-bit one's complement of the one's complement sum of a pseudo header of information from the IP header, the UDP header, and the data, padded  with zero octets at the end (if  necessary)  to  make  a multiple of two octets. References White papers available at http://threadgroup.org/ “6LoWPAN: The Wireless Embedded Internet” by Zach Shelby and Carsten Bromann RFC 4291, RFC 4944, RFC 4443 and RFC 768 from https://www.ietf.org
View full article
Many applications make use of 32 kHz clocks to keep tracking of real-time or to have a low power time reference for the system. Most of the systems might use a 32.768 kHz XTAL for this purpose. However, there might be some exceptions in which the application requires compensate the frequency of this clock due to temperature changes, aging, or just because the clock provides from a source which frequency is close to the ideal 32.768 kHz, but it presents some variations. QN908x devices require a 32 kHz clock source for some applications like running the BLE stack in low power. 32.768 kHz XTALs are more accurate so they are used to generate a 32 kHz source by compensating for the ppm difference. This provides us with tools to compensate for any external 32 kHz source by first obtaining the ppm difference from the ideal frequency. The solution consists in determining how off is the external clock input frequency from the ideal 32 kHz by making a comparison with a trusted clock in the system, typically the 32 MHz / 16 MHz XTAL. This process is executed in the background in an interrupt-based system so the application can initialize or run other processes in the meantime. Then, the results of the ppm calculation are reported to the main application to compensate for the changes and provide for a more accurate clock source. This example makes use of the following peripherals in the QN908x RTC Seconds Timer CTIMER DMA The RTC Seconds Timer uses the 32 kHz clock source as a reference. It contains an internal 32000 cycles counter that increases each 32 kHz clock period. On overflow, it rises the SEC_INT flag to indicate that one second has elapsed. The CTIMER makes use of the APB clock which derives from the 32 MHz / 16 MHz clock. This timer is used in free-running mode with a Prescaler value of 1 to count the number of APB pulses. The algorithm consists of counting the amount of APB pulses (trusted clock reference) elapsed by the time the RTC SEC_INT flag is set. Ideally, if both clocks are in the right frequency, the number of APB pulses must be equal to the reference clock frequency. For example, if the APB clock is 16 MHz, by the time the SEC_INT flag sets, the CTIMER counter must have a value of 16 x 10 6 counts. Assuming our reference clock is ideal, the difference between the CTIMER counter value and 16 x 10 6 can be used to obtain the ppm difference given the following formula. Where f 0 is the ideal APB frequency (16 MHz) and f 1 is the real measured frequency (CTIMER counter value). Since the pulses counted using the CTIMER correspond to the time it took to the RTC Seconds Timer to count one second, we can extrapolate the obtained ppm value as a difference in the 32 kHz clock source from the ideal 32 kHz. To prevent from any application or task servicing latency, the algorithm makes use of the DMA to automatically capture the CTIMER Counter value when the SEC_INT flag is set. The program flow is described in the diagram below. As a way of demonstrating this algorithm, two APIs were implemented to calculate the ppm value and apply the compensation to the system. Both APIs are included in the file fsl_osc_32k_cal .c and .h files. OSC_32K_CAL_GetPpm (osc_32k_cal_callback_t pCallbackFnc): Initializes the required timers and DMA and starts with the CTIMER capture. A callback is passed so it can be executed once the ppm calculation sequence completes. OSC_32_CAL_ApplyPpm (int32_t ppmMeasurement): Uses the previously calculated ppm passed as an input parameter to compensate the RTC and the BLE timer used during sleep mode. OSC_32K_CAL_GetPpm is called every time the ppm value of the 32 kHz source clock needs to be calculated. It takes around one second to complete (depending on how off the 32 kHz source clock is from the ideal frequency) and the application cannot enter into low power state during this time. The registered callback function is executed once the calculation is complete. The ppm calculation is performed into the DMA callback. It consists of obtaining the CTIMER counter difference and use it as f 1 in the formula shown before. The ppm values are calculated using floating point unit. /* Calculate PPMs */ ppmResult = (float)((float)1-((float)ApbClockFreq/(float)ApbCountDiff)); ppmResult *= (float)1048576;‍‍‍‍‍‍ Then OSC_32_CAL_ApplyPpm must be called using the ppm value obtained after calling OSC_32K_CAL_GetPpm. This API programs the necessary values in the RTCàCAL register and the BLE Sleep timer registers to compensate for the differences in the 32 kHz source clock. Finally, the user must account for all those other APIs that make use of the 32 kHz clock frequency and update the values accordingly. For the particular case of the NXP BLE Stack, there are two APIs that need to be updated to return the clock frequency after the calibration has been applied. uint32_t PWRLib_LPTMR_GetInputFrequency(void) { uint32_t result = 32000; int32_t ppm = 0; if ( RTC->CTRL & RTC_CTRL_CAL_EN_MASK) /* is calibration enabled ? */ { /* Get the current calibration value */ if (RTC->CAL & RTC_CAL_DIR_MASK) { /* Backward calibration */ ppm -= (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } else { /* Forward calibration */ ppm += (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } /* Obtain the uncalibrated clock frequency using the formula * fUncal = 32000 - (ppm*0.03125) where 0.03125 is the number * of Hz per PPM digit obtained from (768 Hz/0x6000 PPM) */ result -= (float) ppm * (float) 0.03125; } else { #if (defined(BOARD_XTAL1_CLK_HZ) && (BOARD_XTAL1_CLK_HZ == CLK_XTAL_32KHZ)) result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,768Khz crystal is used */ #else result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,000Khz internal RCO is used */ #endif } return result; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ uint32_t StackTimer_GetInputFrequency(void) { uint32_t prescaller = 0; uint32_t refClk = 0; uint32_t result = 0; #if FSL_FEATURE_SOC_FTM_COUNT refClk = BOARD_GetFtmClock(gStackTimerInstance_c); prescaller = mFtmConfig.prescale; result = refClk / (1 << prescaller); #elif FSL_FEATURE_RTC_HAS_FRC int32_t ppm = 0; (void)prescaller; /* unused variables */ (void)refClk; /* suppress warnings */ result = 32000; if ( RTC->CTRL & RTC_CTRL_CAL_EN_MASK) /* is calibration enabled ? */ { /* Get the current calibration value */ if (RTC->CAL & RTC_CAL_DIR_MASK) { /* Backward calibration */ ppm -= (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } else { /* Forward calibration */ ppm += (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } /* Obtain the uncalibrated clock frequency using the formula * fUncal = 32000 - (ppm*0.03125) where 0.03125 is the number * of Hz per PPM digit obtained from (768 Hz/0x6000 PPM) */ result -= (float) ppm * (float) 0.03125; } else { #if (defined(BOARD_XTAL1_CLK_HZ) && (BOARD_XTAL1_CLK_HZ == CLK_XTAL_32KHZ)) result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,768Khz crystal is used */ #else result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,000Khz internal RCO is used */ #endif } #elif FSL_FEATURE_SOC_CTIMER_COUNT refClk = BOARD_GetCtimerClock(mCtimerBase[gStackTimerInstance_c]); prescaller = mCtimerConfig[gStackTimerInstance_c].prescale; result = refClk / (prescaller + 1); #else refClk = BOARD_GetTpmClock(gStackTimerInstance_c); prescaller = mTpmConfig.prescale; result = refClk / (1 << prescaller); #endif return result; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
View full article
Our customer is evaluating RF characteristics using FRDM-MKW24. Regarding Tx max power, they have one question. The spec of max tx power is +8dBm and I could verify the power using TWR-KW24d512 before. They observed tx power with tx un-modulated cnt transmission and informed that the power was about +2dBm. That is to say, "Power 31" in Connectivity_Test means to +2dBm. I feel that it is small... Would you comment regarding the spec of the max tx power on FRDM-MKW24? Regards, Koichi
View full article
The connectivity software is an add-on of the Kinetis SDK, therefore the demos are referenced to a KSDK path variable named "KSDK_PATH" in IAR. The KSDK_PATH variable contains the path of the installation folder for the KSDK version in your PC. Taking as an example the MRB-KW01 SMAC Connectivity Software, we can realize that this variable is used to reference for libraries. In particular, this SMAC software for the MRB-KW01 works with KSDK 1.2, that is why you could have troubles if the variable is referenced to another KSDK version (for example KSDK 1.1). Follow the next steps to modify the KSDK_PATH variable in your computer: 1. Right click on "computer", then click "properties" 2. A Control Panel window will be opened. Click on "Advanced system settings" 3. A system Properties windows will be opened. Select the "Advanced" tab, then click "Environment Variables". 4. Select the KSDK_PATH variable and assure that it stores the correct path needed for your project. In case that you need to modify the variable, then click "Edit" 5. Finally click "Ok" to close all tabs and you will be able to run your connectivity software without problems. Best regards, Luis Burgos.
View full article
Hello All, I designed a ultra low low cost evaluation board (ULC-Zigbee) based in Kinetis wireless MCUs, take a look at the attached PDF for the brief description.  I was able to build three of them at ~$10USD each. The ULC-Zigbee is covered under the GNU General Public License. The required files to build the board are attached, it measures 30 x 50mm. My partner AngelC   wrote a sample code. The software basically communicates wirelessly the ULC-Zigbee board with a USB-KW24D512. An FXOS8700 is externally connected through the prototype board connector and the magnetic and acceleration values are then wirelessly transmitted to the USB stick, then the values can be printed in a HyperTerminal. The attached zip file contains the following files: File name Description ULC-Zigbee-EBV_V10.pdf Brief description of the ULC-Zigbee board MKW2x_Eagle_library.lbr  Required EAGLE CADSOFT LIBRARY ULC-Zigbee-EBV_V10.brd EAGLE v6.5 Board ULC-Zigbee-EBV_V10.sch EAGLE v6.5 Schematic ULC-Zigbee-EBV_V10_SCH.pdf ULC-Zigbee board schematic ULC-Zigbee-EBV_V10_BOM.xlsx Bill of materials ULC-Zigbee-EBV_V10_GERBER_FILES.zip Gerber files WirelessUART_MKW2x_v1.3_eCompass_TX_v1.zip ULC-Zigbee board sample software WirelessUART_MKW2x_v1.3_eCompass_RX_v1.zip USB-KW24D512 sample software     Hope it helps!   -Josh   Este documento fue generado desde la siguiente discusión:Ultra Low Cost Zigbee Evaluation Board
View full article
This post explains the implementation to operate the KW36 MCU on VLPR when the clocking mode is BLPE or BLPI. It's also included the explanation on how to configure clocks for BLPE and BLPI modes. For this example, the beacon demo from the wireless examples of the FRDM-KW36 is used. FRDM-KW36 SDK can be downloaded from MCUXpresso webpage. A recommended option to configure clock modes is "Config Tools" from MCUXpresso. Config Tools is embedded to MCUXpresso IDE, or you can download Config Tools from this LINK if you are using other supported IDE for this tool. MCUXpresso IDE is used in this example. Configure BLPE or BLPI clocking modes Select your proyect on MCUXpresso IDE, then open the clocks configuration window from Config Tools by clicking the arrow next to Config Tools icon from your MCUXpresso IDE, and then select "Open Clocks" as shown in Figure 1. Figure 1. Open Clocks from Config Tools using MCUXpresso IDE. A clocks diagram window will be opened. To configure the clock modes just select your option "BLPI" or "BLPE" on MCG Mode as shown in Figure 2. Clock will be automatically configured. Figure 2. MCG Mode selection. Now let's configure the appropiate clocks for Core clock and Bus clock to run in VLPR. Figure 3 taken from KW36 Reference Manual shows achievables frequencies when MCU is on VLPR.  Figure 3. VLPR clocks. Core clock should be 4MHz for BLPE and BLPI clocking modes, and Bus clock should be 1MHz for BLPE and 800kHz for BLPI.  Figure 4 shows clocks distribution for BLPE and Figure 5 for BLPI to operate with discussed frequencies. Figure 4. Clock distribution - VLPR and BLPE. Figure 5. Clock distribution - VLPR and BLPI. Press "Update Project" (Figure 6) to apply your new clock configuration to your firmware, then change perspective to "Develop" icon on right corner up to go to your project (See Figure 7). Compile your project to apply the changes. Figure 6. Update Project button. Figure 7. Develop button. At this point your project is ready to work with BLPE or BLPI clocks modes. Now, let's configure MCU to go to VLPR power mode. Configure VLPR mode VLPR mode can be configured using Config Tools too, but you may have an error trying to configure it when BLPE mode, this is because CLKDIV1 register cannot be written when the device is on VLPR mode. For this example, let's configure MCU into VLPR mode by firmware. Follow next steps to configure KW36 into VLPR power mode: 1. Configure RF Ref Oscillator to operate in VLPR mode. By default, the RF Ref Osc it's configured to operate into RUN mode. To change it to operate on VLPR mode just change the bits RF_OSC_EN from Radio System Control from 1 (RUN) to 7 (VLPR). Figure 8 taken from KW36 Reference Manual shows RF_OSC_EN value options from Radio System Control.    Figure 8. RF_OSC_EN bits from Radio System Control register. Go to clock_config.c file in your MCUXpresso project and search for "BOARD_RfOscInit" function. Change the code line as shown in Figure 9 to configure RF Ref Osc to work into VLPR mode. You may see a window asking if you want to make writable the read-only file, click Yes. Figure 9. Code line to configure RF Ref Osc to work into VLPR mode Be aware that code line shown in Figure 9 may change with updates done in clocks using Config Tools. Note 2. Configure DCDC in continuous mode. According to KW36 Reference Manual, the use of BLPE in VLPR mode is only feasible when the DCDC is configured for continuous mode. First, let's define gDCDC_Enabled_d flag to 1 on preprocesor. With this implementation, the use of DCDC_Init function will be enabled, and it's where we going to add the code line to enable continuous mode. Right click on your project, select Properties, go to Settings under C/C++ Build, then Preprocessor under MCU C Compiler (Figure 10).   Figure 10. MCUXpresso Preprocessor   Click on add button from Defined symbols, write gDCDC_Enabled_d=1 and click OK to finish (Figure 11).  Re-compile your project. Figure 11. MCUXpresso Defined symbols   Now let's set VLPR_VLPW_CONFIG_DCDC_HP bits to 1 from DCDC_REG0 register. Figure 12 was taken from KW36 Reference Manual. Figure 12. VLPR_VLPW_CONFIG_DCDC_HP values. Go to DCDC_Init  function and add the next code line to enable continuous mode on DCDC: DCDC->REG0 |= DCDC_REG0_VLPR_VLPW_CONFIG_DCDC_HP_MASK; Figure 13 shows the previous code line implemented in firmware project inside of DCDC_Init function. Figure 13. Continuous mode for DCDC enabled. 3. Configure MCU into VLPR mode To finish, let's write the code to configure MCU into VLPR power mode. Copy and paste next code just after doing implementation described on step 1 and 2: #if (defined(FSL_FEATURE_SMC_HAS_LPWUI) && FSL_FEATURE_SMC_HAS_LPWUI) SMC_SetPowerModeVlpr(SMC, false); #else SMC_SetPowerModeVlpr(SMC); #endif while (kSMC_PowerStateVlpr != SMC_GetPowerModeState(SMC)) { } It may be needed to add the SMC library: #include "fsl_smc.h" The code is configuring MCU into VLPR mode with bits RUNM from SMC_PMCTRL register (Figure 14) and then check if it was correctly configured by reading status bits PMSTAT from SMC_PMSTAT register (Figure 15) Figure 14. RUNM bits from SMC_PMCTRL register. Figure 15. PMSTAT bits from  SMC_PMSTAT register. KW36 is ready to operate and BLPE or BLPI clocking modes with VLPR power mode.
View full article
The KW41Z has support for an external 26 MHz or 32 MHz reference oscillator. This oscillator is used, among other things, as the clock for the RF operation. This means that the oscillator plays an important role in the RF operation and must be tuned properly to meet wireless protocol standards. The KW41Z has adjustable internal load capacitors to support crystals with different load capacitance needs. For proper oscillator function, it is important that these load capacitors be adjusted such that the oscillator frequency is as close to the center frequency of the connected crystal (either 26 MHz or 32 MHz in this case). The load capacitance is adjusted via the BB_XTAL_TRIM bit field in the ANA_TRIM register of the Radio block. The KW41Z comes preprogrammed with a default load capacitance value. However, since there is variance in devices due to device tolerances, the correct load capacitance should be verified by verifying that the optimal central frequency is attained.  You will need a spectrum analyzer to verify the central frequency. To find the most accurate value for the load capacitance, it is recommended to use the Connectivity Test demo application. This post is aimed at showing you just how to do that.   In this case, the Agilent Technologies N9020A MXA Signal Analyzer was used to measure, configured with the following parameters: FREQ (central frequency): 2405 MHz (test will be conducted on channel 11) SPAN (x-axis): 100 KHz AMPTD (amplitude, y-axis): 5 dBm To perform the test, program the KW41Z with the Connectivity Test application. The project, for both IAR and KDS, for this demo application can be found in the following folder: <KW41Z_connSw_1.0.2_install_dir>\boards\frdmkw41z\wireless_examples\smac\connectivity_test\FreeRTOS NOTE:  If you need help programming this application onto your board, consult your Getting Started material for the SMAC applications.  For the FRDM-KW41Z, it is located here. Once the device is programmed, make sure the device is connected to a terminal application in your PC. When you start the application, you're greeted by this screen: Press 'ENTER' to start the application. Press '1' to select the continuous tests mode. Press '4' to start a continuous unmodulated transmission. Once the test is running, you should be able to see the unmodulated signal in the spectrum analyzer. Press 'd' and 'f' to change the XTAL trim value, thus changing the central frequency. Now, considering the test in this example is being performed in 802.15.4 channel 11, the central frequency should be centered exactly in 2.405 GHz, but on this board, it is slightly above (2.4050259 GHz) by default. In order to fix this, the XTAL trim value was adjusted to a value that moves the frequency to where it should be centered. Once the adequate XTAL trim value is found, it can be programmed to be used by default. This other post explains how to do this process.
View full article