Wireless Connectivity Knowledge Base

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

Wireless Connectivity Knowledge Base

Discussions

Sort by:
High level description to enable a Linux + KW41Z Border Router. Similar to how it’s shown for the K64 solution in the Kinetis Thread Stack Application Development Guide.   Configure the OpenWrt router to assign the IPv6 ULA prefix 2001:2002:2003::/48. On the LAN network, the router distributes addresses from range 2001:2002:2003::/60 Plug an Ethernet cable between the OpenWrt router and the Linux box. Before creating the Thread network, the Linux box has a global address on its eth interface from range 2001:2002:2003::/60. After creating the Thread network, the BR configures on its Serial TAP interface an address from range 2001:2002:2003::/60. On its 6LoWPAN interface, the BR configures an address from range 2001:2002:2003:c::/64. This is achieved with DHCPv6 prefix delegation - the router is requested to assign a new prefix space to be used by the Thread network. The forth segment in the IPv6 range might be 2, 4, 8 or c, depending of the number of DHCP-PD requests made to the router. After 4 attempts, the router will not lease any other prefixes for some time. In order to force that, you'd require to restart the odhcpd deamon in the OpenWrt router with the following command: /etc/init.d/odhcpd restart . Join the router eligible device, which configures an address in 2001:2002:2003::1/60. We then ping the "Internet" (the LAN interface on the OpenWrt router) and it works. “threadtap0” interface must be bridged with an uplink interface connected to an OpenWrt DHCPv6-PD enabled router; it will act identically as the K64F solution.   Setup Linux PC (Ubuntu) OpenWrt AP/Router with DHCPv6-PD support (OpenWrt version used in this guide: OpenWrt Chaos Calmer 15.05.1) For reference, hardware used on this guide: TP-Link Model TL-WR741ND 150Mbps Wireless N Router OpenWRT firmware supports multiple hardware available at https://openwrt.org/ 1 FRDM-KW41Z (Host Controlled Device, connected to Linux) 1 FRDM-KW41Z (Router Eligible Device or any joiner device) Thread version 1.1.1.20 (from SDK builder at mcuxpresso.nxp.com)   Host Controlled Device firmware, make sure the following macros are enabled: THR_SERIAL_TUN_ROUTER                       /source/config.h     -> Enables TAP interface by default (not TUN) THR_SERIAL_TUN_ENABLE_ND_HOST     /app/common/app_serial_tun.h   OpenWRT router Configure IPv6 ULA-Prefix:   Linux Copy HSDK folder Create 'threadtap0' TAP interface: …/host_sdk/hsdk/demo#   sudo bash make_tap.sh Use "Thread_Shell" or modify “Thread_KW_Tun” demo to enable the SERIAL_TAP macro …/host_sdk/hsdk/demo#   nano Thread_KW_Tun.c #define SERIAL_TAP 0   modify to:  #define SERIAL_TAP  1        Note: For demo purposes, the "Thread_Shell" demo is recommended, it already uses TAP by default and allows input commands. If this is not required and only the TAP bridge is to be used, use the Thread_KW_Tun demo. Bridge the interfaces; assuming eno1 is the interface connected directly to OpenWrt: # brctl addbr br0 # brctl addif br0 eno1 # brctl addif br0 threadtap0 # ifconfig br0 up Note: (Optional) Addresses on the bridged interfaces are lost and need to be reconfigured on the actual bridge. In this example, after bridging eno1 (interface to OpenWrt router), you’d have to run #dhclient br0 to get an IPv4 address on br0 for SSH to the router and/or #dhclient -6 br0 to get an IPv6 address to the br0 interface. There's a note here https://wiki.archlinux.org/index.php/Network_bridge#With_bridge-utils  about this.   Build C demos …/host_sdk/hsdk/demo#   make Run Thread_Shell or Thread_KW_Tun demo. …/host_sdk/hsdk/demo#   sudo ./bin/Thread_Shell /dev/ttyACM0 threadtap0 25 or …/host_sdk/hsdk/demo#   sudo ./bin/Thread_KW_Tun /dev/ttyACM0 threadtap0         Note: Try to run the demo without parameters to get some help on the input parameters   ifconfig Thread_Shell demo Thread_KW_Tun demo Joiner FRDM-KW41Z (shell) Join the Thread network Verify IP addresses Ping Eth LAN interface on OpenWrt router to verify “Internet” connectivity  Regards, JC
View full article
Development environment Hardware: i.MX6Q SabreSD connecting rtl8188cus or rtl8192cus wifi dongle Software: FSL JB 4.2.2-1.1.0-GA release   Advantage brought by JB4.2.2 As we may know that in JB4.0.x, Wifi-Direct is exclusive to normal Wifi access AP, so means that you have to turn off  Wifi normal AP access, then turn on Wifi-Direct. But in JB4.2.x, it can support the following topologies in use scene as following: So that means you can keep p2p connection meanwhile access internet throught AP.     Feature verified 1. Wifi connection support internet surf, and DLNA. 2. Wifi-Direct can support files transmission like Gallery sharing based on Wifi-Direct Demo.apk from FSL. 3. Particial support Wifi-Display, but due to unavailability of Wifi-Display sink module, so cannot be verified fully.   Usage: untar the attached file, then "patch -p1 <" in corresponding subdirectories. It would be better to untar the file in an empty directory, so you can understand which subdirectories are newly created (ex. hardware/realtek is newly created), then within these newly created subdirectoies, you need to "git init" first, then do "patch -p1<" to adopt all newly added files and subdirectories. Original Attachment has been moved to: WiFiDirectDemo.apk.zip Original Attachment has been moved to: patch4rtl8188_8192_on_jb4_2_2-ga.tar.gz
View full article
This document and the attached files are maintained up to date in collaboration with Dragos Musoiu. This document is a supplement for USB MSC device bootloader revision for FRDM-KL25Z (IAR) written by Kai Liu and describes the bootloader support for USB-KW24D512. How to use 1) Connect the USB-KW24D512 to the PC USB port; 2) Download the attached file ‘USB_KW24D512_MSD_Bootloader.bin’ to the flash memory of the MKW24D512 SiP following the next steps: Connect a J-Link programmer to the PC USB port (other than the one used for the USB-KW24D512 dongle); Navigate to your J-Link driver folder using a command console and type ‘jlink.exe’ followed by enter; After the apparition of the J-Link prompter, type ‘unlock kinetis’ followed by enter; Wait for the unlock command confirmation and after, type ‘device mkw24d512xxx5’ followed by enter; After the J-Link prompter appears type ‘loadbin USB_KW24D512_MSD_Bootloader.bin 0’ followed by enter; (Be sure you copied the ‘USB_KW24D512_MSD_Bootloader.bin’ file in the same directory with jlink.exe otherwise, type the command specifying the full path of the binary file); After the flashing process successfully finished type ‘exit’ followed by enter. 3) Reset or reconnect the USB-KW24D512; 4) The OS will prompt MSD device connecting and then BOOTLOADER drive will appear. The bootloader software was tested on Microsoft Windows 10, Microsoft Windows 8.1, Microsoft Windows 7, Ubuntu 14.04 and MAC operating systems. 5) Copy and paste any user application .SREC or .bin file into BOOTLOADER drive; 6) If a valid .SREC or .bin file was given, the board restarts and starts to run the user application. Please refer to the Notes section in order to create valid .SREC or .bin files. Note:            The bootloader has conditional jump to user application. The condition is the state of the SW1 button (PTC4). If the button is pressed (PTC4 grounded) during reset, the bootloader sequence will start, installing BOOTLOADER drive, as described before. Else if the button is released during reset, the SP and PC will be updated from address 0xC000. This means, the user application has to use a linker file which forces the application start address to 0xC000. If a valid SP and PC value is found at address 0xC000, the user application is launched. The bootloader application is located in the flash memory of the MKW24D512 SiP, from address 0x0000 to 0xBFFF, so the user application should not put any code in this memory region. Avoid using .SREC or .bin files having program bytes or fill patterns in the bootloader section. Attached files: USB_KW24D512_MSD_Bootloader.bin – bootloader binary file for USB-KW24D512; Pflash_512KB_0xC000.icf – IAR linker file for user application development; 802.15.4SnifferOnUSB.bin – user application demo binary file for KW24D512-USB. Be aware that the file ‘802.15.4SnifferOnUSB.srec’ is linked according to the above memory restrictions and is working only with the bootloader presented in this document.
View full article
There are two patches for HDMI Dongle JB4.2, one is remove the warning message, the other is fix to that sleep will not recover. Jack Mao
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
HCI Application is a Host Controller Interface application which provides a serial communication to interface with the KW40/KW41 BLE radio part. It enables the user to have a way to control the radio through serial commands. In this section will be discussed how user could send serial commands to the KW40/KW41 device. “HCI app” file is given to test the BLE functionality. User needs to open the COM port with the configuration 115200 8N1N. Then, it is needed to send commands in Hex format, user can make use of Docklight application. Once HCI application is downloaded to the board, next steps need to be followed:         Open the COM port.       Send the next command in Hex format “01 03 0C 00”. It is to perform a Reset to the radio.       Send the next command in Hex format “01 1E 20 03 26 20 00”. It is to set the radio in Transmit test mode. The number 26 specifies the number of the channel in which user wants to see the signal(valid range is from 0x00 to 0x27, this means from BLE Channel 0 to BLE Channel 39). Number 00 specifies the type of the signal that will be sent, in this case, it is a PBRS9 format. (valid range are from 0x00 to 0x07). Refer to the next table to know the meanings of each type of signal.  Finally, 20 is the number that specifies the length that will be sent in the packet or the payload, in this case, it is configured to 20 (32 bytes), VALID RANGE is from 0x00 to 0x25.       In order to set the radio in Receiver Test Mode. The next command in hex format need to be used "01 1D 20 01 04", this command means that radio would be listening in channel 04. Hence, values "01 1D 20 01" is the command to set the radio in Rx mode, the last value "04' defines the channel in which device is going to listen. As an additional example, if channel 06 is desired, command "01 1D 20 01 06" should be used.     If there is a need to change the output power of the radio. The NXP connectivity software provides the Controller_SetTxPowerLevel() which is called inside of the Controller_TaskInit(). Controller_SetTxPowerLevel() function make use of the following defines to determine the default power output in the application:   mAdvertisingDefaultTxPower_c and mConnectionDefaultTxPower_c. The value range for both is from 0 to 31. The range might be different for each device, so, it needs to be corroborated. This range is applicable only for KW41Z device. For example, for KW40Z, range is from 0 to 15.     The defines are defined in the file ble_controller_task_config.h. Finally, HCI applications can be found in the connectivity software package of your desired device. If the KW40Z is the device under test (DUT), the HCI application is called "hci_app", it can be found in the next path: "<insllation_path>\KW40Z_Connectivity_Software_1.0.1\ConnSw\examples\bluetooth\hci_app"   If the KW41Z is the device under test (DUT), the HCI application is called "hci_black_box", it can be found in the next path: "<insllation_path>\MKW41Z_ConnSw_1.0.2\boards\frdmkw41z\wireless_examples\bluetooth\hci_black_box"
View full article
Introduction This document guides to load a new software image in a KW41 device through Over The Air Programming bootloader. Also, are explained the details of how to set up the client software to change the storage method of the image. Software Requirements IAR Embedded Workbench IDE or MCUXpresso IDE Download both, SDK FRDM-KW41Z and SDK USB-KW41Z. Hardware Requirements FRDM-KW41Z board OTAP Memory Management During the Update Process The KW41 has a 512KB Program Flash with a flash address range from 0x0000_0000 to 0x0007_FFFF.     The OTAP application splits the flash into two independent parts, the OTAP Bootloader, and the OTAP Client. The OTAP Bootloader verifies if there is a new image available at the OTAP Client to reprogram the device. The OTAP Client software provides the Bluetooth LE custom service needed to communicate the OTAP Client device with the OTAP Server that contains the new image file (The OTAP Server device could be another FRDM-KW41Z connected to a PC with Test Tool or a Smartphone with IoT Toolbox app). Therefore, the OTAP Client device needs to be programmed twice, first with the OTAP Bootloader, then with the Bluetooth LE application supporting OTAP Client. The mechanism created to have two different software coexisting in the same device is storing each one in different memory regions. This functionality is implemented by the linker file. In the KW41 device, the bootloader has reserved a 16 KB slot of memory from 0x0000_0000 to 0x0003_FFFF, thus the left memory is reserved among other things, by the OTAP Client demo. To create a new image file for the client device, the developer needs to specify to the linker file that the code will be built with an offset of 16 KB since the first addresses must be reserved for the OTAP Bootloader. In connection state, the OTAP server sends the image packets (known as chunks) to the OTAP Client device via Bluetooth LE. The OTAP Client device can store these chunks, in first instance, at the external SPI flash or the On-Chip Flash. The destination of the code is selectable in the OTAP Client software. When the connection has finished and all chunks were sent from the OTAP Server to the OTAP Client device, the OTAP Client software writes information, such as the source of the image update (external flash or internal flash) in a portion of memory known as Bootloader Flags and then resets the MCU to execute the OTAP Bootloader code. The OTAP Bootloader reads the Bootloader Flags to get the information needed to program the device and triggers a commando to reprogram the MCU with the new application. Due to the new application was built with an offset of 16 KB, the OTAP Bootloader programs the device starting from the 0x0000_4000 address and the OTAP Client application is overwritten by the new image, therefore, after the device has been reprogrammed through this method, cannot be programmed a second time as same. Finally, the OTAP Bootloader triggers a command to start the execution of the new code automatically.     Preparing the Software to Test the OTAP Client for KW41Z Device Using IAR Embedded Workbench Program the OTAP Bootloader on the FRDM-KW41Z. Program the OTAP Bootloader software from the project included in the SDK FRDM-KW41Z at the following path, or you can simply drag and drop the pre-built binary from the following path.           OTAP Bootloader Project:          <SDK_2.2.0_FRDM-KW41Z_download_path>\boards\frdmkw41z\wireless_examples\framework\bootloader_otap\bm\iar\bootloader_otap_bm.eww            OTAP Bootloader pre-built binary:            <SDK_2.2.0_FRDM-KW41Z_download_path>\tools\wireless\binaries\bootloader_otap_frdmkw41z.bin   Open the OTAP Client project included in the SDK FRDM-KW41Z located in the following path.          <SDK_2.2.0_FRDM-KW41Z_download_path>\boards\frdmkw41z\wireless_examples\bluetooth\otap_client_att\freertos\iar\otap_client_att_freertos.eww   Customize the OTAP Client software to select the storage method. Locate the app_preinclude.h header file inside the source folder at the workspace. To select the External Flash storage method, set the "gEepromType_d" define to "gEepromDevice_AT45DB041E_c"                      To select the Internal Flash storage method, set the "gEepromType_d" define to "gEepromDevice_InternalFlash_c"   Configure the linker flags. Open the project options window (Alt + F7). In "Linker->Config" window, locate the "Configuration file symbol definitions" pane. To select the External Flash storage method, remove the "gUseInternalStorageLink_d=1" linker flag To select the Internal Flash storage method, add the "gUseInternalStorageLink_d=1" linker flag     Load the OTAP Client software on the FRDM-KW41Z board (Ctrl + D). Stop the debug session (Ctrl + Shift + D). The default linker configurations of the project allow the OTAP Client application to be stored with the proper memory offset.   Preparing the Software to Test the OTAP Client for KW41Z Device Using MCUXpresso IDE Program the OTAP Bootloader on the FRDM-KW41Z. Program the OTAP Bootloader software from the project included in the SDK FRDM-KW41Z at the following path, or you can simply drag and drop the pre-built binary from the following path.           OTAP Bootloader Project:          wireless_examples->framework->bootloader_otap->bm            OTAP Bootloader pre-built binary:            <SDK_2.2.0_FRDM-KW41Z_download_path>\tools\wireless\binaries\bootloader_otap_frdmkw41z.bin   Click on "Import SDK examples(s)" option in the "Quickstart Panel" view. Click twice on the frdmkw41z icon.     Open the OTAP Client project included in the SDK FRDM-KW41Z located in the following path.wireless_examples->bluetooth->otap_client_att->freertos     Customize the OTAP Client software to select the storage method. Locate the app_preinclude.h header file inside the source folder at the workspace. To select the External Flash storage method, set the "gEepromType_d" define to "gEepromDevice_AT45DB041E_c"                      To select the Internal Flash storage method, set the "gEepromType_d" define to "gEepromDevice_InternalFlash_c"   Configure the linker file. To select the External Flash storage method, are not required any changes in the project from this point. You can skip this step. To select the Internal Flash storage method, search the linker file located in the SDK USB-KW41Z at the following path and replace instead of the default linker file at the source folder in the OTAP Client project. You can copy (Ctrl + C) the linker file from SDK USB-KW41Z and paste (Ctrl + V) on the workspace directly. A warning message will be displayed, select "Overwrite".           Linker file at the SDK USB-KW41Z:        <SDK_2.2.0_USB-KW41Z_download_path>\boards\usbkw41z_kw41z\wireless_examples\bluetooth\otap_client_att\freertos\MKW41Z512xxx4_connectivity.ld     Save the changes in the project. Select "Debug" in the "Quickstart Panel". Once the project is already loaded on the device, stop the debug session.   Creating an S-Record Image File for FRDM-KW41Z OTAP Client in IAR Embedded Workbench Open the connectivity project that you want to program using the OTAP Bootloader from your SDK FRDM-KW41Z. This example will make use of the glucose sensor project, this is located at the following path. <SDK_2.2.0_FRDM-KW41Z_download_path>\boards\frdmkw41z\wireless_examples\bluetooth\glucose_sensor\freertos\iar\glucose_sensor_freertos.eww   Open the project options window (Alt+F7). In Linker->Config window, add the following linker flag in the “Configuration file symbol definitions” textbox.         gUseBootloaderLink_d=1     Go to the “Output Converter” window. Deselect the “Override default" checkbox, expand the “Output format” combo box and select Motorola S-records format. Click the OK button.     Rebuild the project. Search the S-Record file (.srec) in the following path.<SDK_2.2.0_FRDM-KW41Z_download_path>\boards\frdmkw41z\wireless_examples\bluetooth\glucose_sensor\freertos\iar\debug   Creating an S-Record Image File for FRDM-KW41Z OTAP Client in MCUXpresso IDE Open the connectivity project that you want to program using the OTAP Bootloader from MCUXpresso IDE. This example will make use of the glucose sensor project, this is located at the following path.        wireless_examples->bluetooth->glucose_sensor->freertos   Search the linker file located in the SDK FRDM-KW41Z at the path below and replace instead of the default linker file at the source folder in the Glucose Sensor project. You can copy (Ctrl + C) the linker file from SDK FRDM-KW41Z and paste (Ctrl + V) on the workspace directly. A warning message will be displayed, select "Overwrite".          Linker file at the SDK FRDM-KW41Z:        <SDK_2.2.0_FRDM-KW41Z_download_path>\boards\frdmkw41z\wireless_examples\bluetooth\otap_client_att\freertos\MKW41Z512xxx4_connectivity.ld     Open the new "MKW41Z512xxx4_connectivity.ld" linker file. Locate the section placement of the figure below and remove the "FILL" and the "BYTE" statements.         Build the project. Deploy the “Binaries” icon in the workspace. Click the right mouse button on the “.axf” file. Select the “Binary Utilities/Create S-Record” option. The S-Record file will be saved at “Debug” folder in the workspace with “.s19” extension.     Testing OTAP Client Demo Using IoT Toolbox App Save the S-Record file created with the steps in the last section in your smartphone at a known location. Open the IoT Toolbox App and select OTAP demo. Press “SCAN” to start scanning for a suitable advertiser. Press the “SW4” button on the FRDM-KW41Z board to start advertising. Create a connection with the found device. Press “Open” and search the S-Record file. Press “Upload” to start the transfer. Once the transfer is complete, wait a few seconds until the bootloader has finished programming the new image. The new application will start automatically. 
View full article
I got a question related to best practices to configure a GPIO if the pin is not used. To make it short, the recommendation is to leave the GPIO floating on the PCB and leave the GPIO in its "Default" state as shown in the Signal Multiplexing table in the Reference Manual. The Default state is either “Disabled” or an analog function.   Some Kinetis devices have analog only pins (PGAx/ADCx) while most have GPIO pins with analog functions (PTx/ADCx) or digital GPIO pins   Unused pins, whether analog only or GPIO, should be left floating. Analog only pins do not have input buffers that will cause shoot-through currents when the input floats. GPIO pins with analog functions default to analog functions, which disables the digital input buffer – no shoot-through current.   The digital GPIO pins default to "Disabled", which disables the input buffers - no shoot-through currents with floating inputs.   Finally, unused pins shall not be tied to VDD or VSS. Hence, when designing your board and there are some unused pins, leave them floating on the PCB and then make sure that the software leaves the GPIO in its Default state in the MUX register. 
View full article
For this example, the BLE stack VERSION was configure to create a Custom Profile with the KW40Z. The Custom to create is the Humidity Sensor and is based on the Temperature Sensor. The First thing to know is that the 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.    Figure 1. GATT Client-Server       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 are defined attributes that describe a characteristic value. To define a GATT Database several macros are provided by the GATT_DB API. Figure 2. GATT database      To know if the Profile or service is already defined on the specification, you have to look for on Bluetooth SIG profiles and check on the ble_sig_define module if is already declared on the code. In our case the Service is not declared(because is a Custom Profile) but the characteristic of the humidity it is on the specification but not on ble_sig_define. /*! Humidity Charactristic UUID */ #define gBleSig_Humidity_d                      0x2A6F 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. The Application works like the Temperature Sensor, every time that you press the SW1 on USB is going to send the value. On the Temperature Sensor demo have the Battery Service and Device Information, so you only have to change the Temperature Service to Humidity Service. Figure 3. GATT database of Humidity Sensor      First thing to do is define the Humidity Server that has 16 bytes. To define a new Server or a Characteristic is in gatt_uuid128.h which is located in the application folder. All macros, function or structure in SDK have a common template which helps the application to act accordingly. /* 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 C:\....\KW40Z_BLE_Software_1.1.2\ConnSw\bluetooth\profiles. Found the temperature folder, copy the temperature_service and paste inside of the humidity folder with another name (humidity_service) Then go back and look for the interface folder, copy temperature_interface and change the name (humidity_interface) in the same path.      On the humidity_interface 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; The next configuration structure is for the Client; in this case we don’t need it. /*! Humidity Client - Configuration */ typedef struct humcConfig_tag {     uint16_t    hService;     uint16_t    hHumidity;     uint16_t    hHumCccd;     uint16_t    hHumDesc;     gattDbCharPresFormat_t  humFormat; } humcConfig_t;      At minimum on humidity_service 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(). On stop function, the unsubscribe function is called. bleResult_t Hums_Start (humsConfig_t *pServiceConfig) {        mHums_SubscribedClientId = gInvalidDeviceId_c;         return Hums_RecordHumidityMeasurement (pServiceConfig->serviceHandle, pServiceConfig->initialHumidity); } bleResult_t Hums_Stop (humsConfig_t *pServiceConfig) {     return Hums_Unsubscribe(); }      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);     } }      Steps to include the files into the demo. 1. Create a clone of the Temperature_Sensor with the name of Humidity_Sensor 2. Unzip the Humidity_Sensor folder. 3. In the fallowing path <kw40zConnSoft_intall_dir>\ConnSw\bluetooth\profiles\interface save the humidity_interface file. 4. In the <kw40zConnSoft_intall_dir>\ConnSw\bluetooth\profiles save the humidity folder 5. In the next directory <kw40zConnSoft_intall_dir>\ConnSw\examples\bluetooth\humidity_sensor\common replaces with the common folder.           Steps to include the paths into the demo using IAR Embedded Workbench​ Once you already save the folders in the corresponding path you must to indicate in the demo where are they. 1. Drag the files into the corresponding folder. The principal menu is going to see like this. Figure 4. Principal Menu 2. Then click Option Figure 5. Option 3. Click on the C/C++ Compiler and then on the Preprocessor     Figure 6. Preposcessor Window 4. After that click on  "..." button to edit the include directories and then click to add a new path.      Add the <kw40zConnSoft_intall_dir>\ConnSw\bluetooth\profile\humidity path. Figure 7. Add a path Finally compile and enjoy the demo! NOTE: If you want to probe the demo using another board you must to run the humidity_collector demo too. Figure 8. Example of the Humidity Sensor using the Humidity Collector demo.
View full article
This document describes a simple process for enabling the user controls the radio through serial commands. Hardware requirements: • FRDM-KW41Z/QN902x board or a board programmed with HCI black box application. Software requirements: • Test Tool 12 application. It can be downloaded from the NXP web page. • HCI Black Box binary.   Running Demo 1. Load the board with hci_black_box example. 2. Open the Test Tool 12 software 3. Set up the correct Serial Configuration. If there were no changes in the application the default configuration will correspond to the one showed in the following figure. 4. Double click on the active device that you want to test, this will open the COM port in the command console. 5. Set the command set to the BLE_HCI.xml. This file has a list of the HCI commands that the user can send to the device, some of the commands have some options to be configured if necessary or some data to be filled. 6. To make easier the use of frequent commands, there is the option to add a shortcut to the command and the chosen behavior will be added to the panel. 7. Once you add the shortcut or choose the command or your preference, just double click over it and the tool will send the command to the device. In this case, we will send a reset on the board, this command does not receive any extra parameters, data or need any extra configuration.   8. If successful there will be a response or acknowledge of the behavior that will be shown in the right panel. Hope it helps. Regards, Mario
View full article
FreeRTOS keeps track of the elapsed time in the system by counting ticks. The tick count increases inside a periodic interrupt routine generated by one of the timers available in the host MCU. When FreeRTOS is running the Idle task hook, the microcontroller can be placed into a low power mode. Depending on the low power mode, one or more peripherals can be disabled in order to save the maximum amount of energy possible. The FreeRTOS tickless idle mode allows stopping the tick interruption during the idle periods. Stopping the tick interrupt allows the microcontroller to remain in a deep power saving state until a wake-up event occurs. The application needs to configure the module (timer, ADC, etc…) that will wake up the microcontroller before the next FreeRTOS task needs to be executed. For this purpose, during the execution of vPortSuppressTicksAndSleep, a function called by FreeRTOS when tickless idle is enabled, the maximum amount of time the MCU can remain asleep is passed as an input parameter in order to properly configure the wake-up module. Once the MCU wakes up and the FreeRTOS tick interrupt is restarted, the number of tick counts lost while the MCU was asleep must be restored. Tickless mode is not enabled by default in the Connectivity Software FreeRTOS demos. In this post, we will show how to enable it. For this example, we will use QN9080x to demonstrate the implementation. lowpower‌ freertos tickless‌ tickless‌ Changes where implemented in the following files: \framework\LowPower\Source\QN908XC\PWR.c \framework\LowPower\Interface\QN908XC\PWR_Interface.h \freertos\fsl_tickless_generic.h \source\common\ApplMain.c The following file was removed from the project fsl_tickless_qn_rtc.c PWR.C and PWR_Interface.h Changes in this files are intended to prepare the QN9080 for waking up using the RTC timer. Other parts, like MKW41Z, might enable other modules for this purpose (like LPTMR) and changes on this files might not be necessary. *** PWR.c *** Add the driver for RTC. This is the timer we will use to wake up the QN908x /*Tickless: Add RTC driver for tickless support */ #include "fsl_rtc.h"‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Add local variables uint64_t mLpmTotalSleepDuration;        //Tickless uint8_t mPWR_DeepSleepTimeUpdated = 0;  //Tickless: Coexistence with TMR manager‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Add private functions uint32_t PWR_RTCGetMsTimeUntilNextTick (void);         //Tickless void PWR_RTCSetWakeupTimeMs (uint32_t wakeupTimeMs);   //Tickless void PWR_RTCWakeupStart (void);                        //Tickless‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Make the following changes in PWR.C. All the required changes are marked as comments with "Start" where the change starts, and with "End where the change ends" #if (cPWR_UsePowerDownMode && (cPWR_EnableDeepSleepMode_1 || cPWR_EnableDeepSleepMode_2 || cPWR_EnableDeepSleepMode_3 || cPWR_EnableDeepSleepMode_4)) static void PWR_HandleDeepSleepMode_1_2_3_4(void) { #if cPWR_BLE_LL_Enable     uint8_t   power_down_mode = 0xff;     bool_t    enterLowPower = TRUE;     __disable_irq(); /****************START***********************************/     /*Tickless: Configure wakeup timer */     if(mPWR_DeepSleepTimeUpdated){       PWR_RTCSetWakeupTimeMs(mPWR_DeepSleepTimeMs);       mPWR_DeepSleepTimeUpdated = FALSE;        // Coexistence with TMR Manager     }         PWR_RTCWakeupStart(); /*****************END**************************************/     PWRLib_ClearWakeupReason();     //Try to put BLE in deep sleep mode     power_down_mode = BLE_sleep();     if (power_down_mode < kPmPowerDown0)     {         enterLowPower = false; // BLE doesn't allow deep sleep     }     //no else - enterLowPower is already true     if(enterLowPower)     { /****************START**************************/         uint32_t freeRunningRtcPriority; /****************END****************************/         NVIC_ClearPendingIRQ(OSC_INT_LOW_IRQn);         NVIC_EnableIRQ(OSC_INT_LOW_IRQn);         while (SYSCON_SYS_STAT_OSC_EN_MASK & SYSCON->SYS_STAT) //wait for BLE to enter sleep         {             POWER_EnterSleep();         }         NVIC_DisableIRQ(OSC_INT_LOW_IRQn);         if(gpfPWR_LowPowerEnterCb != NULL)         {             gpfPWR_LowPowerEnterCb();         } /* Disable SysTick counter and interrupt */         sysTickCtrl = SysTick->CTRL & (SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk);         SysTick->CTRL &= ~(SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk);         ICSR |= (1 << 25); // clear PendSysTick bit in ICSR, if set /************************START***********************************/         NVIC_ClearPendingIRQ(RTC_FR_IRQn);         freeRunningRtcPriority = NVIC_GetPriority(RTC_FR_IRQn);         NVIC_SetPriority(RTC_FR_IRQn,0); /***********************END***************************************/         POWER_EnterPowerDown(0); //Nighty night! /************************START**********************************/         NVIC_SetPriority(RTC_FR_IRQn,freeRunningRtcPriority); /************************END************************************/         if(gpfPWR_LowPowerExitCb != NULL)         {             gpfPWR_LowPowerExitCb();         }         /* Restore the state of SysTick */         SysTick->CTRL |= sysTickCtrl;         PWRLib_UpdateWakeupReason();     }     __enable_irq(); #else     PWRLib_ClearWakeupReason(); #endif /* cPWR_BLE_LL_Enable */ } #endif /* (cPWR_UsePowerDownMode && cPWR_EnableDeepSleepMode_1) */ ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ void PWR_SetDeepSleepTimeInMs(uint32_t deepSleepTimeMs) { #if (cPWR_UsePowerDownMode)     if(deepSleepTimeMs == 0)     {         return;     }     mPWR_DeepSleepTimeMs = deepSleepTimeMs; /****************START******************/     mPWR_DeepSleepTimeUpdated = TRUE; /****************END*********************/ #else     (void) deepSleepTimeMs; #endif /* (cPWR_UsePowerDownMode) */ }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Add/replace the following function definitions at the end of the file /*--------------------------------------------------------------------------- * Name: PWR_GetTotalSleepDurationMS * Description: - * Parameters: - * Return: - *---------------------------------------------------------------------------*/ uint32_t PWR_GetTotalSleepDurationMS(void) {     uint32_t time;     uint32_t currentSleepTime;     OSA_InterruptDisable();     currentSleepTime = RTC_GetFreeRunningInterruptThreshold(RTC);     if(currentSleepTime >= mLpmTotalSleepDuration){     time = (currentSleepTime-mLpmTotalSleepDuration)*1000/CLOCK_GetFreq(kCLOCK_32KClk);     }     else{     time = ((0x100000000-mLpmTotalSleepDuration)+currentSleepTime)*1000/CLOCK_GetFreq(kCLOCK_32KClk);     }     OSA_InterruptEnable();     return time; } /*--------------------------------------------------------------------------- * Name: PWR_ResetTotalSleepDuration * Description: - * Parameters: - * Return: - *---------------------------------------------------------------------------*/ void PWR_ResetTotalSleepDuration(void) {     OSA_InterruptDisable();     mLpmTotalSleepDuration = RTC_GetFreeRunningCount(RTC);     OSA_InterruptEnable(); } /*--------------------------------------------------------------------------- * Name: PWR_RTCGetMsTimeUntilNextTick * Description: - * Parameters: - * Return: Time until next tick in mS *---------------------------------------------------------------------------*/ uint32_t PWR_RTCGetMsTimeUntilNextTick (void) {     uint32_t time;     uint32_t currentRtcCounts, thresholdRtcCounts;     OSA_InterruptDisable();     currentRtcCounts = RTC_GetFreeRunningCount(RTC);     thresholdRtcCounts = RTC_GetFreeRunningResetThreshold(RTC);     if(thresholdRtcCounts > currentRtcCounts){     time = (thresholdRtcCounts-currentRtcCounts)*1000/CLOCK_GetFreq(kCLOCK_32KClk);     }     else{     time = ((0x100000000-currentRtcCounts)+thresholdRtcCounts)*1000/CLOCK_GetFreq(kCLOCK_32KClk);     }     OSA_InterruptEnable();     return time; } /*--------------------------------------------------------------------------- * Name: PWR_RTCSetWakeupTimeMs * Description: - * Parameters: wakeupTimeMs: New wakeup time in milliseconds * Return: - *---------------------------------------------------------------------------*/ void PWR_RTCSetWakeupTimeMs (uint32_t wakeupTimeMs){     uint32_t wakeupTimeTicks;     uint32_t thresholdValue;     wakeupTimeTicks = (wakeupTimeMs*CLOCK_GetFreq(kCLOCK_32KClk))/1000;     thresholdValue = RTC_GetFreeRunningCount(RTC);     thresholdValue += wakeupTimeTicks;     RTC_SetFreeRunningInterruptThreshold(RTC, thresholdValue); } /*--------------------------------------------------------------------------- * Name: PWR_RTCWakeupStart * Description: - * Parameters: - * Return: - *---------------------------------------------------------------------------*/ void PWR_RTCWakeupStart (void){   if(!(RTC->CNT2_CTRL & RTC_CNT2_CTRL_CNT2_EN_MASK)){     RTC->CNT2_CTRL |= 0x52850000 | RTC_CNT2_CTRL_CNT2_EN_MASK | RTC_CNT2_CTRL_CNT2_WAKEUP_MASK | RTC_CNT2_CTRL_CNT2_INT_EN_MASK;   }   else{     RTC->CNT2_CTRL |= 0x52850000 | RTC_CNT2_CTRL_CNT2_WAKEUP_MASK | RTC_CNT2_CTRL_CNT2_INT_EN_MASK;   } } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍  *** PWR_Interface.h *** Add the following function declarations at the end of the file /*--------------------------------------------------------------------------- * Name: PWR_GetTotalSleepDurationMS * Description: - * Parameters: - * Return: - *---------------------------------------------------------------------------*/ uint32_t PWR_GetTotalSleepDurationMS(void); /*--------------------------------------------------------------------------- * Name: PWR_ResetTotalSleepDuration * Description: - * Parameters: - * Return: - *---------------------------------------------------------------------------*/ void PWR_ResetTotalSleepDuration(void); #ifdef __cplusplus } #endif #endif /* _PWR_INTERFACE_H_ */ ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ FSL_TICKLESS_GENERIC The following changes have the purpose of preparing the system for recovering the missed ticks during the low power period. Make the following changes in fsl_tickless_generic.h. All the required changes are marked as comments with "Start" where the change starts, and with "End where the change ends" /* QN_RTC: The RTC free running is a 32-bit counter. */ #define portMAX_32_BIT_NUMBER (0xffffffffUL) #define portRTC_CLK_HZ (0x8000UL) /* A fiddle factor to estimate the number of SysTick counts that would have occurred while the SysTick counter is stopped during tickless idle calculations. */ #define portMISSED_COUNTS_FACTOR (45UL) /* * The number of SysTick increments that make up one tick period. */ /****************************START**************************/ #if configUSE_TICKLESS_IDLE == 1     static uint32_t ulTimerCountsForOneTick; #endif /* configUSE_TICKLESS_IDLE */ /************************END*********************************/ /* * Setup the timer to generate the tick interrupts. */ void vPortSetupTimerInterrupt(void); #ifdef __cplusplus } #endif #endif /* FSL_TICKLESS_GENERIC_H */ ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ApplMain.c This is the main application file. Here is where we will call the proper APIs to enter the MCU in low power mode and perform the tick recovery sequence. Include RTC and FreeRTOS header files needed /*Tickless: Include RTC and FreeRTOS header files */ #include "fsl_rtc.h" #include "fsl_tickless_generic.h" #include "FreeRTOS.h" #include "task.h"‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ QN9080 includes several low power modes. Sleep mode maintains most of the modules active. Power Down modes turn off most of the modules but allow the user to configure some modules to remain active to wake the MCU up when necessary. Using tickless FreeRTOS involves having to wake-up by some timer before the next ready task has to execute. For QN908x this timer will be the RTC which requires the 32.768kHz oscillator to remain active. We will change the Connectivity Software Power Lib to use Deep Sleep mode 3 (Power Down mode 0 for QN908x) which maintains the 32.768kHz oscillator on. This change is implemented in the main_task function. #if !defined(MULTICORE_BLACKBOX)         /* BLE Host Stack Init */         if (Ble_Initialize(App_GenericCallback) != gBleSuccess_c)         {             panic(0,0,0,0);             return;         } #endif /* MULTICORE_BLACKBOX */ /*************** Start ****************/ #if (cPWR_UsePowerDownMode)     PWR_ChangeDeepSleepMode(3); #endif /*************** End ****************/     }         /* Call application task */     App_Thread( param ); }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍   Also, tickless FreeRTOS requires a special Idle function which takes as an input parameter the amount of RTOS ticks the MCU can remain asleep before the next task needs to be executed. The following changes disable the default Idle function provided in the Connectivity Software demos when the tickless mode is enabled. /************************************************************************************ ************************************************************************************* * Private prototypes ************************************************************************************* ************************************************************************************/ #if (cPWR_UsePowerDownMode || gAppUseNvm_d) #if (mAppIdleHook_c)     #define AppIdle_TaskInit()     #define App_Idle_Task() #else #if (!configUSE_TICKLESS_IDLE)     static osaStatus_t AppIdle_TaskInit(void);     static void App_Idle_Task(osaTaskParam_t argument); #endif // configUSE_TICKLESS_IDLE #endif #endif‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ /************************************************************************************ ************************************************************************************* * Private memory declarations ************************************************************************************* ************************************************************************************/ /******************************** Start ******************************/ #if ((cPWR_UsePowerDownMode || gAppUseNvm_d) && !configUSE_TICKLESS_IDLE) /******************************** End ******************************/ #if (!mAppIdleHook_c) OSA_TASK_DEFINE( App_Idle_Task, gAppIdleTaskPriority_c, 1, gAppIdleTaskStackSize_c, FALSE ); osaTaskId_t gAppIdleTaskId = 0; #endif #endif  /* cPWR_UsePowerDownMode */‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ #if !gUseHciTransportDownward_d         pfBLE_SignalFromISR = BLE_SignalFromISRCallback; #endif /* !gUseHciTransportDownward_d */ /**************************** Start ************************/ #if ((cPWR_UsePowerDownMode || gAppUseNvm_d) && !configUSE_TICKLESS_IDLE) /**************************** End ************************/ #if (!mAppIdleHook_c)         AppIdle_TaskInit(); #endif #endif‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ /***************************START**************************/ #if (cPWR_UsePowerDownMode && !configUSE_TICKLESS_IDLE) /******************************END***************************/ static void App_Idle(void) {     PWRLib_WakeupReason_t wakeupReason;     if( PWR_CheckIfDeviceCanGoToSleep() )     {         /* Enter Low Power */         wakeupReason = PWR_EnterLowPower(); #if gFSCI_IncludeLpmCommands_c         /* Send Wake Up indication to FSCI */         FSCI_SendWakeUpIndication(); #endif #if gKBD_KeysCount_c > 0         /* Woke up on Keyboard Press */         if(wakeupReason.Bits.FromKeyBoard)         {             KBD_SwitchPressedOnWakeUp();             PWR_DisallowDeviceToSleep();         } #endif     }     else     {         /* Enter MCU Sleep */         PWR_EnterSleep();     } } #endif /* cPWR_UsePowerDownMode */ #if (mAppIdleHook_c) void vApplicationIdleHook(void) { #if (gAppUseNvm_d)     NvIdle(); #endif /*******************************START****************************/ #if (cPWR_UsePowerDownMode && !configUSE_TICKLESS_IDLE) /*********************************END*******************************/     App_Idle(); #endif } #else /* mAppIdleHook_c */ /******************************* START ****************************/ #if ((cPWR_UsePowerDownMode || gAppUseNvm_d) && !configUSE_TICKLESS_IDLE) /******************************* END ****************************/ static void App_Idle_Task(osaTaskParam_t argument) {     while(1)     {   #if gAppUseNvm_d         NvIdle(); #endif         #if (cPWR_UsePowerDownMode)         App_Idle(); #endif         /* For BareMetal break the while(1) after 1 run */         if (gUseRtos_c == 0)         {             break;         }     } } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Once the default Idle function has been disabled, the special Idle function must be implemented. Add the following code at the end of the ApplMain.c file. /*Tickless: Implement Tickless Idle */ #if (cPWR_UsePowerDownMode && configUSE_TICKLESS_IDLE) extern void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) {     uint32_t time_ms = xExpectedIdleTime * portTICK_PERIOD_MS;     uint32_t tmrMgrExpiryTimeMs;     ulTimerCountsForOneTick = 160000;//VALUE OF THE SYSTICK 10 ms #if (cPWR_UsePowerDownMode)     PWRLib_WakeupReason_t wakeupReason;         //TMR_MGR: Get next timer manager expiry time     tmrMgrExpiryTimeMs = TMR_GetFirstExpireTime(gTmrAllTypes_c);     // TMR_MGR: Update RTC Threshold only if RTOS needs to wakeup earlier     if(time_ms<tmrMgrExpiryTimeMs){       PWR_SetDeepSleepTimeInMs(time_ms);     }         PWR_ResetTotalSleepDuration();     if( PWR_CheckIfDeviceCanGoToSleep() )     {         wakeupReason = PWR_EnterLowPower();                 //Fix: All the tick recovery stuff should only happen if device entered in DSM         xExpectedIdleTime = PWR_GetTotalSleepDurationMS() / portTICK_PERIOD_MS;     // Fix: ticks = time in mS asleep / mS per each tick (portTICK_PERIOD_MS)         /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG         again, then set portNVIC_SYSTICK_LOAD_REG back to its standard         value. The critical section is used to ensure the tick interrupt         can only execute once in the case that the reload register is near         zero. */         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;         portENTER_CRITICAL();         portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;         vTaskStepTick( xExpectedIdleTime );         portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;         portEXIT_CRITICAL(); #if gKBD_KeysCount_c > 0         /* Woke up on Keyboard Press */         if(wakeupReason.Bits.FromKeyBoard)         {           KBD_SwitchPressedOnWakeUp();           PWR_DisallowDeviceToSleep();         } #endif     }     else     {       /* Enter MCU Sleep */       PWR_EnterSleep();     } #endif /* cPWR_UsePowerDownMode */ } #endif  //cPWR_UsePowerDownMode && configUSE_TICKLESS_IDLE ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ From the previous function, the value of ulTimerCountsForOneTick is used to restore the count of the RTOS tick timer after waking up. This value depends on the RTOS Tick interval defined in FreeRTOSConfig.h and is calculated using the following formula: SYST_RNR  =  F_Systick_CLK(Hz) * T_FreeRTOS_Ticks(ms) Where:       F_Systick_CLK(Hz) = AHB or 32KHz of the SYST_CSR selection       T_FreeRTOS_Ticks(ms) = tick count value. FreeRTOSConfig.h Finally, on the FreeRTOSConfig.h file, make sure that configUSE_TICKLESS_IDLE is set to 1 * See http://www.freertos.org/a00110.html. *----------------------------------------------------------*/ #define configUSE_PREEMPTION                    1 #define configUSE_TICKLESS_IDLE                 1 //<--- /***** Start *****/ #define configCPU_CLOCK_HZ                      (SystemCoreClock) #define configTICK_RATE_HZ                      ((TickType_t)100) #define configMAX_PRIORITIES                    (18) #define configMINIMAL_STACK_SIZE                ((unsigned short)90)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Testing Tickless RTOS In order to test if tickless support was successfully added, an example application that toggles an LED is implemented. This application configures an RTOS timer to toggle the LED once every 500mS and enter the MCU in DSM3 during the idle time. The Power Profiling demo was used for this purpose. power_profiling.c Make sure you have included the following header files #include "FreeRTOS.h" #include "task.h"‍‍‍‍ Create an RTOS task for blinking the LED every 500mS. First, declare the task function, task ID and the task itself. void vfnTaskLedBlinkTest(void* param); //New Task Definition OSA_TASK_DEFINE(vfnTaskLedBlinkTest, 1, 1, 500, FALSE ); osaTaskId_t gAppTestTask1Id = 0; // TestTask1 Id‍‍‍‍‍‍ Create the new task inside the BleApp_Init function void BleApp_Init(void) {     PWR_AllowDeviceToSleep();     mPowerState = 0;   // Board starts with PD1 enabled     /******************* Start *****************/     gAppTestTask1Id = OSA_TaskCreate(OSA_TASK(vfnTaskLedBlinkTest), NULL); //Task Creation     /*******************  End  *****************/ }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Finally, add the task function definition at the end of the file. void vfnTaskLedBlinkTest(void* param) {     uint16_t wTimeValue = 500; //500ms     while(1)     {         LED_BLUE_TOGGLE();         vTaskDelay(pdMS_TO_TICKS(wTimeValue));     } }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ We can monitor the power consumption in MCUXpresso IDE, with the Power Measurement Tool. With it, we can see the current that is been consumed and prove that the implementation is working as the expected. Configure the Power Measurement Tool Consumed current
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
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 there are currently different beacon formats on the market.   This guide will help you to create your own beacon scanner to detect from which type of device is the beacon received from. This guide it’s based on the frdmkw41z_wireless_examples_bluetooth_temperature_collector_freertos  demo in MCUXpresso  The first thing we will do it’s to disable the low power to make the development easier in the app_preinclude.h /* Enable/Disable PowerDown functionality in PwrLib */ #define cPWR_UsePowerDownMode 0‍‍‍‍‍‍   The following changes will be all performed in the temperature_collector.c file We will disable the timer so it keeps scanning the packets received   /* Start advertising timer TMR_StartLowPowerTimer(mAppTimerId, gTmrLowPowerSecondTimer_c, TmrSeconds(gScanningTime_c), ScanningTimeoutTimerCallback, NULL); */‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍   Then we will define some of the data we want to use as a reference. static uint8_t NXPAd[3] = { /* Company Identifier*/ mAdvCompanyId, /* Beacon Identifier */ 0xBC }; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍   static uint8_t iBeaconAd[2] = { 0x4C, 0x00 };‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ static uint8_t EddyStoneUIDAd2[3] = { /* ID */ 0xAA, 0xFE, /* Frame Type */ 0x00 }; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍     static const uint8_t EddyStoneURLAd2[3] = { /* ID */ 0xAA, 0xFE, /* Frame Type */ 0x10 };‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍     static const uint8_t EddyStoneTLMAd2[3] = { /* ID */ 0xAA, 0xFE, /* Frame Type */ 0x20 };‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍   Once we have those definitions of the beacon structure of each of the types wanted we will change the function static bool_t CheckScanEvent(gapScannedDevice_t* pData) static bool_t CheckScanEvent(gapScannedDevice_t* pData) { uint8_t index = 0; bool_t foundMatch = FALSE; bool_t EddyfoundMatch = FALSE; while (index < pData->dataLength) { gapAdStructure_t adElement; adElement.length = pData->data[index]; adElement.adType = (gapAdType_t)pData->data[index + 1]; adElement.aData = &pData->data[index + 2]; /*DESIRED BEACON SCANNER PARSER CODE */ /* Move on to the next AD elemnt type */ index += adElement.length + sizeof(uint8_t); } if (foundMatch) { SHELL_NEWLINE(); shell_write("\r\Address : "); shell_writeHex(pData->aAddress, 6); } return foundMatch; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍   As you can see, there is a comment in the function that mentions the need to add the scanner parser code, depending on the beacon you want to see  will be the code to use there  NXP if (FLib_MemCmp(NXPAD, (adElement.aData), 2)) { shell_write("\r\nFound NXP device!"); SHELL_NEWLINE(); shell_write("\r\nData Received: "); shell_writeHex(adElement.aData, adElement.length); foundMatch=TRUE; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍   iBeacon if (FLib_MemCmp(iBeaconAd, (adElement.aData), 2)) { shell_write("\r\nFound iBeacon device!"); SHELL_NEWLINE(); shell_write("\r\nData Received: "); shell_writeHex(adElement.aData, adElement.length); foundMatch=TRUE; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Eddystone if (FLib_MemCmp(EddyStoneUIDAd1, (adElement.aData), 2)) { shell_write("\r\nFound EddyStone device!"); if (!EddyfoundMatch) { EddyfoundMatch=TRUE; } else{ if(TRUE==EddyfoundMatch && FLib_MemCmp(EddyStoneUIDAd2, (adElement.aData), 3)) { SHELL_NEWLINE(); shell_write("\r\n[UID type] Data Received: "); shell_writeHex(adElement.aData, adElement.length); foundMatch=TRUE; EddyfoundMatch=FALSE; } else if(TRUE==EddyfoundMatch && FLib_MemCmp(EddyStoneURLAd2, (adElement.aData), 3)) { SHELL_NEWLINE(); shell_write("\r\n[URL type] Data Received: "); hell_writeHex(adElement.aData, adElement.length); foundMatch=TRUE; EddyfoundMatch=FALSE; } else if(TRUE==EddyfoundMatch && FLib_MemCmp(EddyStoneTLMAd2, (adElement.aData), 3)) { SHELL_NEWLINE(); shell_write("\r\n[TLM type] Data Received: "); shell_writeHex(adElement.aData, adElement.length); foundMatch=TRUE; EddyfoundMatch=FALSE; } else { EddyfoundMatch=TRUE; } } }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
View full article
1. Introduction of ZigBee and popular solutions in the market. 2. Introduction of Freescale ZigBee solution
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
The Thread Low Power End Device is preconfigured to have both the MCU in low power state and the radio turned off most of the time to preserve battery life. The device wakes up periodically and polls its parent router for data addressed to it or optionally initiates sending data to the network by means of the parent router. The low-power module (LPM) from the connectivity framework simplifies the process of putting a Kinetis-based wireless network node into the low-power or sleep modes. For the MKW41Z there are six low-power modes available. By default, the Thread Low Power End Device uses Deep sleep mode 3, where: MCU in LLS3 mode. Link layers remain idle. RAM is retained. The wake-up sources are: GPIO (push buttons). DCDC power switch (In buck mode). LPTMR with the 32kHz oscillator as clock source. The LPTMR timer is also used to measure the time that the MCU spends in deep sleep to synchronize low-power timers at wake-up. See the Connectivity Framework Reference Manual and PWR_Configuration.h for more information about the sleep deep modes. To change the polling time on deep sleep mode 3, we need to understand two macros:    1. The cPWR_DeepSleepDurationMs macro in \framework\LowPower\Interface\MKW41Z\PWR_Configuration.h. #ifndef cPWR_DeepSleepDurationMs   #define cPWR_DeepSleepDurationMs                3000 #endif ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ This macro determines how long the MCU will go to low power mode (deep sleep). The maximum value is 65535000 ms (18.2 h). 2. The THR_SED_POLLING_INTERVAL_MS macro in \source\config.h. /*! The default value for sleepy end device (SED) polling interval */ #ifndef THR_SED_POLLING_INTERVAL_MS     #define THR_SED_POLLING_INTERVAL_MS                     3000     /* Milliseconds */ #endif ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ This macro determines how often the Low Power End Device will send a poll message to its parent. NOTE: This value does not determine how often the MCU wakes up. The polling interval should be a multiple of the Deep sleep duration value, otherwise the poll will be sent at the next deep sleep time out. As an example, let's say we configure the polling interval to 4000ms and the deep sleep duration to 3000ms. The MCU will wake up every 3000ms but the poll message will be sent every 2 deep sleep timeouts = 6000ms because the timers are synchronized when the MCU wakes up. The following figure shows the behavior of this example. It is recommended that the polling interval is the same as the deep sleep duration, so the MCU doesn't wake up unnecessarily. The following figure shows this behavior. Another macro to keep in mind is THR_SED_TIMEOUT_PERIOD_SEC in app_thread_config.h. #ifndef THR_SED_TIMEOUT_PERIOD_SEC     #define THR_SED_TIMEOUT_PERIOD_SEC                 ((4*THR_SED_POLLING_INTERVAL_MS)/1000 + 3) #endif ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ This value is the timeout period used by the parent to consider a sleepy end device (SED) disconnected. By default, this value is configured to be 4 times the polling interval + 3s. It is recommended to leave this macro as it is. This value is sent to the parent node during the commissioning.
View full article
Certification is the process of testing radio hardware to demonstrate that it meets the stated regulations in the country that it will operate in. A certification is needed generally when electronic hardware will be sold in a country, the certification requirements of that country must be met. If you require changes in your certificated hardware that will affects your RF performance, then you need to re-certificate the device. Most common regions and certification's institutes are (it applies for 2.4GHz & SubGHz): FCC for USA IC for Canada ETSI (CE) for Europe ARIB for Japan Other countries generally follow FCC or ETSI standars. The institute in charge of certifications depends on the region. It's the same institute to certificate your device in 2.4GHz or SubGHz in a certain region, the only difference are the articles of each institute to operate in the different frequencies. For operating in the 2.4GHZ band (worldwide): - In the U.S, CFR 47 FCC Part 15 203, 15.209 and 15.247 - In Canada, IC RSS-210 which closely follows FCC Part 15 - In EU, ETSI EN 300, 301 - In Japan, ARIB STD-T66 For SubGHz depends on the frequency you want to operate in. Taking Japan as an example: In Japan you can operate in the 920MHz band or in the 400MHz band for SubGHz. For both frequencies, ARIB is the institute in charge of the certifications but to operate in the 400MHz band the article that you will need is the ARIB STD-T67, and to operate in the 920MHz you will need to certificate your hardware with ARIB STD-T108 article. Freescale's MRB-KW019032 is certificated to operate in the following SubGHz ISM bands: The firmware used to certificate our KW products is the Radio Utility or the Connectivity Test, it allows the user in changing some RF parameters needed to pass the certification process. If you are thinking in certificate a product, contact an expert! There are Telecommunication Certification Body (TCB) companies which can give you guidance in the processes you need to follow to achieve a certification. To know more about FCC certification requirements and processes, refer to the reference manual “Freescale IEEE 802.15.4 / ZigBee Node RF Evaluation and Test Guidelines” in the Freescale's website. Best regards, Burgos. This document was generated from the following discussion: Certifications
View full article
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
When developing portable applications using batteries, it is important to keep track of the remaining battery level to inform the user and take action when it drops to a level that might be critical for the correct device functionality. A common measurement method consists of taking a sample of the current battery voltage and correlate it to a percentage depending on its capacity. Then this value is reported to the user in a visual manner. MKW40 is a system on chip (SoC) that embeds a processor and a Bluetooth® Low Energy (BLE)/802.15.4 radio for wireless communications. This posts describes how to obtain the current battery level and report it via BLE using this part. Hardware considerations Typically, the battery voltage is regulated so the MCU has a stable power supply across the whole battery life. This causes the ADC supply voltage to be lower than the actual battery voltage. To address this, a voltage divider is used to adequate the battery voltage to levels that can be read by the ADC. Figure 1 Typical battery level divider circuit The MKW40 includes a voltage divider on its embedded DC-DC converter removing the need to add this voltage divider externally. It is internally connected to the ADC0 channel 23 so reading this channel obtains the current level of the power source connected to the DC-DC converter in. Figure 2 DC-DC converter with battery voltage monitor Software implementation Software implementation consists in acquiring the ADC value, correlate it with a percentage level and transmit it using BLE. The connectivity software includes functions to perform all those actions. A voltage divider connected to the battery and internally wired to an ADC channel is embedded in the SoC. For the MKW40Z it is the ADC0 single ended channel 23 (ADC0_CH23) . There are some examples in the Kinetis Software Development Kit (KSDK) documentation explaining how to configure the ADC module. The connectivity software includes a function named BOARD_InitAdc in the file app.c where this is initialized. void BleApp_Init(void) {     /* Initialize application support for drivers */     BOARD_InitAdc(); <-- Initialization function         /* Initialize Software-timer */     SwTimer_Init();           /* Status Indicator fade initialization */     status_indicator_fade_init();     /* Initialise ECG Acquisition system */     ecg_acquisition_init();     /* Initialize battery charger pin configuration */     power_manager_init();     /* Create Advertising Timer */     advertisingTimerId = SwTimer_CreateTimer(TimerAdvertisingCallback); } Once initialized, this ADC channel must be read to obtain the current voltage present in the divisor. There are also some cool examples in the KSDK documentation on how to do this. The obtained value is a digital representation of the voltage in the divisor and is relative to the VDDA or VREFH voltage (depending on what is used as reference for the ADC). Since the battery voltage varies over the time (unless you use a voltage regulator or use the DC-DC converter in buck mode), the most accurate way to get the battery voltage is to obtain the actual voltage that is referencing the ADC first. For this, the MKW40Z includes a 1V reference voltage channel wired to another ADC channel: ADC0_CH27. Reading this ADC channel obtains the number of counts that correspond to 1V, and VREF can be calculated using the next formula. Once the VRef voltage has been obtained, it is possible to determine the voltage present in the battery voltage divisor by using the following formula. The obtained voltage is still only a portion of the actual battery voltage. To obtain the full voltage, the obtained value must be multiplied by the divisor relation. This relation is selected in the DC-DC register DCDC_REG0:DCDC_VBAT_DIV_CTRL and can be: VBATT, VBATT/2 or VBATT/4. After the full VBAT voltage is obtained, it must be correlated to a percentage depending on the values set for 0% and 100%. Using the slope method is a good approach to correlate the voltage value. For this, the slope m must be calculated using the formula. Where V100% is the voltage in the battery when it is fully charged, and V0% is the voltage in the battery when it is empty. Once m has been calculated, the battery percentage can be obtained using the formula: The Connectivity Software includes a function that obtains the current battery voltage connected to the DC-DC input and returns the battery percentage. It is included in the board.c file. uint8_t BOARD_GetBatteryLevel(void) {     uint16_t batVal, bgVal, batLvl, batVolt, bgVolt = 100; /*cV*/         bgVal = ADC16_BgLvl();     DCDC_AdjustVbatDiv4(); /* Bat voltage  divided by 4 */     batVal = ADC16_BatLvl() * 4; /* Need to multiply the value by 4 because the measured voltage is divided by 4*/         batVolt = bgVolt * batVal / bgVal;         batLvl = (batVolt - MIN_VOLT_BUCK) * (FULL_BAT - EMPTY_BAT) / (MAX_VOLT_BUCK - MIN_VOLT_BUCK);     return ((batLvl <= 100) ? batLvl:100);    } Reporting battery level After the battery level has been determined it can be now reported via BLE. The Connectivity Software includes predefined profile files to be included in custom applications. Battery profile is included in the files battery_service.c and .h, under the Bluetooth folder structure. To make use of them, make sure that they are included in your project. Then, include the file battery_interface.h in your BLE application file. An example using the included BLE applications is shown. In app.c (Connectivity Software examples application file) include the battery service interface #include "battery_interface.h" In the variable declaration section, create a new basConfig_t variable. This is needed to configure a new service. static basConfig_t      basServiceConfig = {service_battery, 0}; The new service needs to be created after the BLE stack has been initialized. When this happens, the function BleApp_Config is executed. Inside this function, the battery service is started.    /* Start services */ hrsServiceConfig.sensorContactDetected = mContactStatus; #if gHrs_EnableRRIntervalMeasurements_d    hrsServiceConfig.pUserData->pStoredRrIntervals = MEM_BufferAlloc(sizeof(uint16_t) * gHrs_NumOfRRIntervalsRecorded_c); #endif    Hrs_Start(&hrsServiceConfig);     Bas_Start(&basServiceConfig);         /* Allocate application timers */     mAdvTimerId = TMR_AllocateTimer(); mMeasurementTimerId = TMR_AllocateTimer(); mBatteryMeasurementTimerId = TMR_AllocateTimer(); Function Bas_Start is used for this purpose. This function starts the battery service functionality indicating that it needs to be reported by the BLE application. After a central has successfully connected to the peripheral device, the battery service must be subscribed so it’ measurements can be reported to the central. For this, the function Bas_Suscribe is used inside the connection callback. Following code shows its implementation in the connectivity software. It takes place in the connection callback function BleApp_ConnectionCallback in app.c switch (pConnectionEvent->eventType) {         case gConnEvtConnected_c:         {             mPeerDeviceId = peerDeviceId;             /* Advertising stops when connected */             mAdvState.advOn = FALSE; #if gBondingSupported_d                /* Copy peer device address information */             mPeerDeviceAddressType = pConnectionEvent->eventData.connectedEvent.peerAddressType;             FLib_MemCpy(maPeerDeviceAddress, pConnectionEvent->eventData.connectedEvent.peerAddress, sizeof(bleDeviceAddress_t)); #endif  #if gUseServiceSecurity_d                        {                 bool_t isBonded = FALSE ;                                if (gBleSuccess_c == Gap_CheckIfBonded(peerDeviceId, &isBonded) &&                     FALSE == isBonded)                 { Gap_SendSlaveSecurityRequest(peerDeviceId, TRUE, gSecurityMode_1_Level_3_c);                 }             } #endif                        /* Subscribe client*/             Bas_Subscribe(peerDeviceId);                    Hrs_Subscribe(peerDeviceId);                                                         /* UI */                        LED_StopFlashingAllLeds();                         /* Stop Advertising Timer*/             mAdvState.advOn = FALSE;             TMR_StopTimer(mAdvTimerId);                        /* Start measurements */ TMR_StartLowPowerTimer(mMeasurementTimerId, gTmrLowPowerIntervalMillisTimer_c, TmrSeconds(mHeartRateReportInterval_c), TimerMeasurementCallback, NULL);               } Once the service has been subscribed, a new measurements can be registered by using the Bas_RecordBatteryMeasurement function at any time. Bas_RecordBatteryMeasurement(basServiceConfig.serviceHandle, basServiceConfig.batteryLevel); This function receives the battery service handler previously defined (static basConfig_t basServiceConfig = {service_battery, 0}) and the current battery level percentage as input parameters. When a disconnection occurs, the battery service must be unsubscribed so no further updates are performed during disconnection. For this, the Bas_Unsuscribe function must be used after a disconnection event. case gConnEvtDisconnected_c:         {             /* Unsubscribe client */             Bas_Unsubscribe();             Hrs_Unsubscribe();             mPeerDeviceId = gInvalidDeviceId_c; Now, updated battery levels can be reported by the BLE device letting the user know when a battery must be replaced or recharged.
View full article
Our customer, who is considering MKW40, is asking NXP regarding max input voltage of PSWITCH and DCDC_CFG pins. Especially they plan to use buck mode with input voltage 4.2[v] as shown below. Would you comment if max voltage of PSWITCH and DCDC_CFG pins is 4.2[v] as well as DCDC_IN pin? Regards, Koichi
View full article