Wireless Connectivity Knowledge Base

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

Wireless Connectivity Knowledge Base

Discussions

Sort by:
The MCU in the KW40/30Z has various available very low power modes. In these power modes, the chip goes to sleep to save power, and it is not usable during this time (it can however receive different kinds of interruptions that could wake it up). The very low power modes supported by the microcontroller are: The KW40Z connectivity software stack has 6 predetermined deep sleep modes. These deep sleep modes have different configurations for the microcontroller low power mode, the BLE Link Layer state and in which ways the device can be awaken. These predetermined DSM (Deep Sleep Modes) are: * VLLS0 if DCDC is bypassed. VLLS1 with either Buck or Boost. ** Available in Buck mode only. Having said that, if you want the lowest possible consumption by the MCU, while also being able to wake up your application automatically with a timer (achieved with VLSS1), there is no DSM available. You can, however, create your own Deep Sleep Mode with low power timers enabled. Please note that VLSS1 has the lowest possible consumption when using a DCDC converter. When in bypass mode, the lowest possible consumption is achieved with VLSS0. To create your Deep Sleep Mode, you should start with the function that will actually handle the board going into deep sleep. This should be done in the PWR.c file, along with the rest of the DSM handler functions. This function is quite similar to the ones already made for the other deep sleep modes. Link layer interruptions, timer settings and the low power mode for the MCU are handled here. /* PWR.c */ #if (cPWR_UsePowerDownMode) static void PWR_HandleDeepSleepMode_7(void) {   #if cPWR_BLE_LL_Enable   uint16_t bleEnabledInt; #endif   uint8_t clkMode;   uint32_t lptmrTicks;   uint32_t lptmrFreq;     PWRLib_MCU_WakeupReason.AllBits = 0;   #if cPWR_BLE_LL_Enable    if(RSIM_BRD_CONTROL_BLE_RF_OSC_REQ_STAT(RSIM)== 0) // BLL in DSM   {     return;   bleEnabledInt = PWRLib_BLL_GetIntEn();   PWRLib_BLL_ClearInterrupts(bleEnabledInt);      PWRLib_BLL_DisableInterrupts(bleEnabledInt); #endif     if(gpfPWR_LowPowerEnterCb != NULL)   {     gpfPWR_LowPowerEnterCb();   }     /* Put the device in deep sleep mode */ #if cPWR_DCDC_InBypass    PWRLib_MCU_Enter_VLLS0(); #else   PWRLib_MCU_Enter_VLLS1(); #endif     if(gpfPWR_LowPowerExitCb != NULL)   {     gpfPWR_LowPowerExitCb();   }   #if cPWR_BLE_LL_Enable    PWRLib_BLL_EnableInterrupts(bleEnabledInt);        #endif      PWRLib_LPTMR_ClockStop();   } #endif /* #if (cPWR_UsePowerDownMode) */ ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Remember to add this function to the deep sleep handler function array: /* PWR.c */ const pfHandleDeepSleepFunc_t maHandleDeepSleep[]={PWR_HandleDeepSleepMode_1,                                                     PWR_HandleDeepSleepMode_2,                                                     PWR_HandleDeepSleepMode_3,                                                     PWR_HandleDeepSleepMode_4,                                                     PWR_HandleDeepSleepMode_5,                                                     PWR_HandleDeepSleepMode_6,                                                     PWR_HandleDeepSleepMode_7                                                    }; ‍‍‍‍‍‍‍‍‍‍ This function should allow your device to go to sleep. It does the strictly necessary things before the device goes to sleep: disables link layer interruptions, gets the configuration for the low power timer and it starts the timer. Please note that when the board is in either Buck or Boost DCDC mode, only VLSS1 is supported. When the device is in bypass mode, VLSS0 can be chosen. Now that the deep sleep handler is done, there are some changes that have to be made to have a proper execution. In the PWR_Configuration.h file, for example, there is an error message when the parameter cPWR_DeepSleepMode is larger than 6 (the default DSM modes), but, since you have added a new deep sleep mode, this number should be changed to 7: #if (cPWR_DeepSleepMode > 7 )  // default: 6   #error "*** ERROR: Illegal value in cPWR_DeepSleepMode" #endif ‍‍‍ Other changes that have to be made are the Low Leakage Wake Up unit and the deep sleep mode configurations. To change the LLWU configuration, you should add a case for the new deep sleep mode in the PWRLib_ConfigLLWU() function: /* PWRLib.c */ void PWRLib_ConfigLLWU( uint8_t lpMode ) {   switch(lpMode)   {   case 1:     LLWU_ME = gPWRLib_LLWU_WakeupModuleEnable_BTLL_c | gPWRLib_LLWU_WakeupModuleEnable_LPTMR_c;   break;   case 2:     LLWU_ME = gPWRLib_LLWU_WakeupModuleEnable_BTLL_c;   break;   case 3:     LLWU_ME = gPWRLib_LLWU_WakeupModuleEnable_LPTMR_c | gPWRLib_LLWU_WakeupModuleEnable_DCDC_c;   break;   case 4:   case 5:     LLWU_ME = gPWRLib_LLWU_WakeupModuleEnable_DCDC_c;    break;   case 6:     LLWU_ME = 0;   break;   case 7: /* The new deep sleep mode can be awaken through a Low Power Timer timeout */     LLWU_ME = gPWRLib_LLWU_WakeupModuleEnable_LPTMR_c;   break;   } }  } #endif /* #if (cPWR_UsePowerDownMode) */ ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Once this case has been added, you should change the function that calls PWRLib_ConfigLLWU(), PWRChangeDeepSleepMode(): /* PWR.c */ bool_t PWR_ChangeDeepSleepMode (uint8_t dsMode) { #if (cPWR_UsePowerDownMode)   if(dsMode > 7) //Since you’ve added an extra DSM, this is now 7 (default: 6)   {      return FALSE;   }    PWRLib_SetDeepSleepMode(dsMode); PWRLib_ConfigLLWU(dsMode); #if (cPWR_BLE_LL_Enable)    PWRLib_BLL_ConfigDSM(dsMode);   PWRLib_ConfigRSIM(dsMode); #endif    return TRUE;   #else   return TRUE; #endif  /* #if (cPWR_UsePowerDownMode) */ } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Now, since you’ll be using a Low Power Timer, you should modify the maLPModeUseLPTMR[] constant in the PWRLib.c file, indicating that you will use a low power timer: /* PWRLib.c */ const uint8_t maLPModeUseLPTMR[]={0,1,1,1,0,0,1,1}; //We add the last 1. default: {0,1,1,1,0,0,1} ‍‍‍ You should add a case for your new low power mode in the PWRLib_ConfigRSIM(). Here you will handle the BLE link layer whilst the device is in low power mode. This function can be found in the PWRLib.c file: /* PWRLib.c */ void PWRLib_ConfigRSIM( uint8_t lpMode ) {   switch(lpMode)   {   case 1:   case 2:       RSIM_BWR_CONTROL_STOP_ACK_OVRD_EN(RSIM, 0);       RSIM_CONTROL |= RSIM_CONTROL_BLE_RF_OSC_REQ_EN_MASK | RSIM_CONTROL_BLE_RF_OSC_REQ_INT_EN_MASK | RSIM_CONTROL_BLE_RF_OSC_REQ_INT_MASK;     break;   case 3:   case 4:   case 5:       RSIM_CONTROL &= ~(RSIM_CONTROL_STOP_ACK_OVRD_EN_MASK | RSIM_CONTROL_BLE_RF_OSC_REQ_EN_MASK | RSIM_CONTROL_BLE_RF_OSC_REQ_INT_EN_MASK);       RSIM_CONTROL |= RSIM_CONTROL_BLE_RF_OSC_REQ_INT_MASK;     break;   case 6:       RSIM_CONTROL &= ~(RSIM_CONTROL_STOP_ACK_OVRD_EN_MASK  | RSIM_CONTROL_BLE_RF_OSC_REQ_INT_EN_MASK);       RSIM_CONTROL |= RSIM_CONTROL_BLE_RF_OSC_REQ_INT_MASK | RSIM_CONTROL_BLE_RF_OSC_REQ_EN_MASK;     break;   case 7: //@PNN       RSIM_CONTROL &= ~(RSIM_CONTROL_STOP_ACK_OVRD_EN_MASK | RSIM_CONTROL_BLE_RF_OSC_REQ_EN_MASK | RSIM_CONTROL_BLE_RF_OSC_REQ_INT_EN_MASK);       RSIM_CONTROL |= RSIM_CONTROL_BLE_RF_OSC_REQ_INT_MASK;     break;   } } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Your low power mode awaken by a low power timer should now be ready. To change the deep sleep mode and the time the device will be in deep sleep mode before it is awaken, use these functions in your application: PWR_ChangeDeepSleepMode(7);                                     /* Change deep sleep mode */ PWR_SetDeepSleepTimeInMs(YOUR_DEEP_SLEEP_TIME_IN_MS);           /* Time the device will spend on deep sleep mode */ PWR_AllowDeviceToSleep();                                      /* Allows the device to go to deep sleep mode */ PWR_DisallowDeviceToSleep();                                   /* Does not allows the device to go to deep sleep mode */ ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
View full article
Hello all, let me share a video demonstration of the Thread Smart Home model. See the link below: Thread Smart Home model Best regards, Karel
View full article
As mentioned in this other post, its important to have the correct trim on the external XTAL. However, once you have found the required trim to properly adjust the frequency, it is not very practical to manually adjust it in every device. So here is where changing the default XTAL trim comes in handy. KW41Z With the KW41 Connecitivity Software 1.0.2, it is a pretty straightforward process. In the hardware_init.c file, there is a global variable mXtalTrimDefault. To change the default XTAL trim, simply change the value of this variable. Remember it is an 8 bit register, so the maximum value would be 0xFF. KW40Z With the KW40, it is a similar process; however, it is not implemented by default on the KW40 Connectivity Software 1.0.1, so it should be implemented manually, following these steps: Create a global variable in hardware_init.c to store the default XTAL trim, similar to the KW41:  /* Default XTAL trim value */ static const uint8_t mXtalTrimDefault = 0xBE;‍‍‍‍‍‍‍‍ Overwrite the default XTAL trim in the hardware_init() function, adding these lines after NV_ReadHWParameters(&gHardwareParameters):    if(0xFFFFFFFF == gHardwareParameters.xtalTrim)   {       gHardwareParameters.xtalTrim = mXtalTrimDefault;   }‍‍‍‍‍‍‍‍‍‍‍‍ Add this define to allow XTAL trimming in the app_preinclude.h file:  /* Allows XTAL trimming */ #define gXcvrXtalTrimEnabled_d  1‍‍‍‍‍‍‍ Once you have found the appropriate XTAL trim value, simply change it in the global variable declared in step 1.
View full article
The KW40Z has support for a 32 MHz reference oscillator. This oscillator is used, among other things, as the clock for the RF operation. To properly adjust the frequency provided by this oscillator, there is a register that can be written, and this register (XTAL_TRIM) adjusts the capacitance provided by the internal capacitor bank to which the oscillator is connected. The KW40Z comes preprogramed with a default value (0x77) in the XTAL_TRIM register. However, since there is probably some variance when using different HW, the central frequency should be verified using a spectrum analyzer. Depending on the value measured, the XTAL_TRIM register can be modified to adjust the frequency. The Connectivity Test application provided here was modified, adding support to change the XTAL_TRIM register. In this case, the Agilent Technologies N9020A MXA Signal Analyzer was used, configured with the following parameters: FREQ (central frequency): 2405 MHz (test will be conducted on channel 11) SPAN (x-axis): 100 KHz AMPTD (amplitude, y-axis): 5 dBm   To perform the test, program the KW40Z device with the Connectivity Test application, using the provided .bin file, or using IAR and replacing the files in the project with the ones provided. To replace the files, unzip the provided .zip file in the KW40Z Connectivity Software folder and when asked, select to replace the existing files with the new ones. To measure and adjust the trimming, run the Connectivity Test application. Press ENTER to start the application. Press 1 to select the continuous tests mode. Press 4 to start a continuous unmodulated transmission. Once the test is running, you should be able to see the unmodulated signal in the spectrum analyzer. Use D and F to change the XTAL_TRIM value, thus changing the central frequency. Now, considering the test is being performed in channel 11, the central frequency should be centered exactly in 2.405 GHz, but on this board, for example, it is slightly above (2.4050259 GHz) by default. In order to fix this, you will need to adjust the value of the XTAL_TRIM register. As you change the XTAL_TRIM value, the central frequency changes too. Adjust the trim value until you find a value that moves the frequency to where it should be centered. For this particular board, a trimming value of 189 (0xBD) was used. Once you have found the trimming value that best adjusts the frequency, you can use it in other projects using the following function, included in the KW4xXcvrDrv.h file: XcvrSetXtalTrim(<YOUR 8 BIT XTAL_TRIM VALUE>)‍‍‍‍‍‍
View full article
Thread provides basic services required for application frameworks implementation with the usage of Unicast and Multicast transmissions over UDP. Thread specification is only focused on the network layer; many application layers can be designed to run without any problem as it is application layer agnostic.  In this laboratory the user will work with the Constrain Application Protocol (CoAP) for this application layer as the Thread stack uses CoAP for most of the multi-hop network management and commissioning messages. The Constrained Application Protocol (CoAP) is a specialized web transfer protocol to use with constrained nodes and constrained networks in the Internet of Thing.  It uses a binary RESTful protocol with four methods POST GET PUT DELETE CoAP also uses ACK responses; CONfirmable (ACK requested) and NONconfirmable messages. The Thread stack uses CoAP for the majority of multi-hop network management and commissioning messages   Objectives Through this laboratory the user will modify the firmware to achieve the following list: Add 2 new COAP URI resources “/resource1” and “/resource2”. Send an ACK message in “/resource1” in case a CON request was received as specified by the CoAP standard. Include a default payload in the ACK message. All packets destined to “/resource1” will trigger a NON POST packet reply (independent from the expected ACK packet) destined to “/resource2” URI path with a default payload. Print in shell all CoAP transactions to fully understand when a request was sent and when a response was received, indicating the method and the resource, e.g. If a CON POST was received, print on shell “‘NON’ packet received, ‘POST’ with payload of ‘<payload>’ If a NON POST was sent, print on shell “‘NON’ packet sent, ‘POST’ with payload ‘<payload>’ The process desired behavior by the laboratory is shown in figure 1.   Figure 1 Diagram showing the desired behavior of the laboratory   Setup In the following list, the components with a dash (—) will be the ones used to create this laboratory.   2 FRDM-KW41Z       — Rev.  A Connectivity Software from the latest NXP release.       — Thread Router Eligible Device project Serial Terminal       — TeraTerm   Figure 2 FRDM-KW41Z    Modifying Firmware       The following changes will be made in the router_eligible_device_app.c file.  1. Define the URI path names that will be used in the shell to access the resources. #define APP_RESOURCE1_URI_PATH                       "/resource1" #define APP_RESOURCE2_URI_PATH                       "/resource2" 2. Declare the URI resources with coapUriPath_t. When using this struct the user must enter the length of the URI path and the path created in the last step. const coapUriPath_t gAPP_RESOURCE1_URI_PATH = {SizeOfString(APP_RESOURCE1_URI_PATH), APP_RESOURCE1_URI_PATH}; const coapUriPath_t gAPP_RESOURCE2_URI_PATH = {SizeOfString(APP_RESOURCE2_URI_PATH), APP_RESOURCE2_URI_PATH}; 3. Create the callbacks for the resources. This callbacks will handle the packet received and perform the desired action depending on the type of COAP method received. static void APP_CoapResource1Cb(coapSessionStatus_t sessionStatus, void *pData, coapSession_t *pSession, uint32_t dataLen); static void APP_CoapResource2Cb(coapSessionStatus_t sessionStatus, void *pData, coapSession_t *pSession, uint32_t dataLen); 4. Add the callback handler for the packet received, in this function it will be defined which action will be performed depending on the type of COAP method received. APP_CoapResource1Cb static void APP_CoapResource1Cb ( coapSessionStatus_t sessionStatus, void *pData, coapSession_t *pSession, uint32_t dataLen ) {   static uint8_t pMySessionPayload[3]={0x31,0x32,0x33};   static uint32_t pMyPayloadSize=3;   coapSession_t *pMySession = NULL;   pMySession = COAP_OpenSession(mAppCoapInstId);   COAP_AddOptionToList(pMySession,COAP_URI_PATH_OPTION, APP_RESOURCE2_URI_PATH,SizeOfString(APP_RESOURCE2_URI_PATH));     if (gCoapConfirmable_c == pSession->msgType)   {     if (gCoapGET_c == pSession->code)     {       shell_write("'CON' packet received 'GET' with payload: ");     }     if (gCoapPOST_c == pSession->code)     {       shell_write("'CON' packet received 'POST' with payload: ");     }     if (gCoapPUT_c == pSession->code)     {       shell_write("'CON' packet received 'PUT' with payload: ");     }         if (gCoapFailure_c!=sessionStatus)     {       COAP_Send(pSession, gCoapMsgTypeAckSuccessChanged_c, pMySessionPayload, pMyPayloadSize);     }   }   else if(gCoapNonConfirmable_c == pSession->msgType)   {     if (gCoapGET_c == pSession->code)     {       shell_write("'NON' packet received 'GET' with payload: ");     }     if (gCoapPOST_c == pSession->code)     {       shell_write("'NON' packet received 'POST' with payload: ");     }     if (gCoapPUT_c == pSession->code)     {       shell_write("'NON' packet received 'PUT' with payload: ");     }      }   shell_writeN(pData, dataLen);   shell_write("\r\n");   pMySession -> msgType=gCoapNonConfirmable_c;   pMySession -> code= gCoapPOST_c;   pMySession -> pCallback =NULL;   FLib_MemCpy(&pMySession->remoteAddr,&gCoapDestAddress,sizeof(ipAddr_t));   COAP_SendMsg(pMySession,  pMySessionPayload, pMyPayloadSize);   shell_write("'NON' packet sent 'POST' with payload: ");   shell_writeN((char*) pMySessionPayload, pMyPayloadSize);   shell_write("\r\n"); } There can be one COAP instance per UDP port, in case the application only uses one port, one instance will be enough. There can be multiple COAP sessions per instance, a COAP session is per packet/transaction. In this case as the desired result was to have a different response of the ACK, it will be necessary to create a new session with the new resource. APP_CoapResource2Cb   static void APP_CoapResource2Cb ( coapSessionStatus_t sessionStatus, void *pData, coapSession_t *pSession, uint32_t dataLen ) {   if (gCoapNonConfirmable_c == pSession->msgType)   {       shell_write("'NON' packet received 'POST' with payload: ");        shell_writeN(pData, dataLen);       shell_write("\r\n");   }  } 5. After creating the callbacks, those must be registered in the CoAP callback array in the function APP_InitCoapDemo(void) {APP_CoapResource1Cb, (coapUriPath_t*)&gAPP_RESOURCE1_URI_PATH}, {APP_CoapResource2Cb, (coapUriPath_t*)&gAPP_RESOURCE2_URI_PATH},   There are some things to mention of the usage of the CoAP library that were not used for this laboratory but might be useful for other types of applications. When using COAP_SendMsg() the session will close automatically by default unless it is indicated with the usage of pSession->autoClose. There are two options while sending the message: Confirmable (CON): It waits for an ACK reply and until it gets the message it will close the session or it will close the session when retransmissions are exhausted. Non-confirmable (NON): For NON, immediately after sending the message. In case a message was sent and there was no response a retransmission will be sent each COAP_ACK_TIMEOUT (in miliseconds), the retransmissions are sent exponentially: first after random (2, 3) seconds, next doubles the timeout and so on, until COAP_MAX_RETRANSMIT is reached. After retransmissions stop, the session is automatically closed and informs the application of failure the application callback will be called with status gCoapFailure_c. When the callback is called the current session is still valid, but CoAP session will close it after exiting the function. There are two different work this out: A new session must be created Set pSession->autoClose = FALSE. If autoClose is set to FALSE, without forgetting to close the session from application, using COAP_CloseSession().     Running the demo    1. Download the modified firmware in the boards 2. Open a serial terminal for each board with a baud rate of 115200 Figure 3 Serial terminal and its configuration  3. In one of the board’s terminal type “thr create”, this board will be the leader. Figure 4 Board 1 with command "thr create" Figure 5 Board 1 after the command "thr create"   4. Once the network has been created type “thr join” in the second board’s terminal. Figure 6 Board 2 with command "thr join" Figure 7 Board 2 after command "thr join" 5. In both serial terminals type the command “ifconfig”. This command will display all the addresses of the board. Figure 8 Board 1 after command "ifconfig" Figure 9 Board 2 after command "ifconfig"   6. To test the callbacks created, a CoAP message must be sent. The following command must be typed; coap <type> <method> <address> <URI> <payload>                                                                                      coap CON POST fe80::5df0:2bf0:d69b:1b3c  /resource1 hello                                                                                      Figure 10 CoAP command to send 7. The result of sending must look like : — Board 1 The board 1 will request the board 2 the resource1 Figure 11 Board 1 before sending the CoAP command As it was coded the other board will send an ACK and print the message. Figure 12 Board 1 after sending the CoAP command — Board 2 Figure 13 Board 2 after receiving the CoAP command If using the CON message the requester board will receive a response, while if the message is a NON type it will not have the response.   When using this types of messages independently of the package type when sending a message a new session will be open and it will send a NON type of message.
View full article
The FRDM-KW40Z includes an RTC module with a 32 kHz crystal oscillator. This module generates a 32 kHz clock source for the MCU whilst running on very low power mode. This oscillator includes a set of programmable capacitors used as the C LOAD . Changing the value of these capacitors can modify the frequency the oscillator provides. This configurable capacitance ranges from 1 pF (which is effectively two 2 pF capacitors in series) all the way to 15 pF (30 pF capacitors in series). These values are obtained by combining the enabled capacitors. The values available are 2 pF, 4 pF, 8 pF and 16 pF. Any combination between these four can be done. It is recommended that these internal capacitors are disabled if the external capacitors are available. Figure 1. External capacitors for the 32 kHz crystal To adjust the frequency provided by the oscillator, you must first be able to measure the frequency. Using a frequency counter would be ideal, as it provides a more precise measurement than an oscilloscope. You will also need to output the oscillator frequency. To output the oscillator frequency, using any of the Bluetooth demo applications as an example, you should do the following: 1. Since the RTC module is going to be used to output the oscillator frequency, the RTC_CLKOUT will be the output signal. The output pin for RTC_CLKOUT is PTB3. To configure PTB3 as the oscillator output use the function configure_rtc_pins(RTC instance). Port B clock must be enabled first. Figure 2. PTB3 pin mux   /* hardware_init.c */     /* enable clock for PORTs */   CLOCK_SYS_EnablePortClock(PORTA_IDX);   CLOCK_SYS_EnablePortClock(PORTB_IDX);   CLOCK_SYS_EnablePortClock(PORTC_IDX);   /* RTC CLKOUT */   configure_rtc_pins(0);     //This function changes the pin mux to select RTC_CLKOUT. It is included in the pin_mux.c file. 2.  Modify the System Options Register 1 (SIM_SOPT1) to select the clock source and to allow the selected clock source to be output in PTB3. The field you should change is OSC32KOUT. To select the clock source to be output on PTB3, use the function CLOCK_HAL_SetExternalRefClock32kSrc(). Remember to include the fsl_sim_hal.h file. Figure 3. SIM_SOPT1 register fields /* hardware_init.c */ /* RTC CLKOUT */ configure_rtc_pins(0); SIM_Type *simBase = g_simBase[0];     SIM_SOPT1 = SIM_SOPT1_OSC32KOUT(kClockRtcoutSrc32kHz);                // This field in register SIM_SOPT1 allows a clock source to be output to PTB3 CLOCK_HAL_SetExternalRefClock32kSrc(simBase, kClockEr32kSrcOsc0);     // This function chooses the clock source for the RTC 3.  Make sure the oscillator is enabled. The RTC external clock configurations can be found in the board.h file. This is also where the internal capacitors are enabled. /* board.h */ /* RTC external clock configuration. */ #define RTC_XTAL_FREQ                32768U #define RTC_SC2P_ENABLE_CONFIG       false      // 2 pF capacitors enable #define RTC_SC4P_ENABLE_CONFIG       false      // 4 pF capacitors enable #define RTC_SC8P_ENABLE_CONFIG       false      // 8 pF capacitors enable #define RTC_SC16P_ENABLE_CONFIG      false      // 16 pF capacitors enable #define RTC_OSC_ENABLE_CONFIG        true       // Oscillator enable 4.  You should now be able to measure the oscillator frequency through the PTB3 pin. Measurements should be done with a frequency counter, as change in the output can be very subtle, and an oscilloscope might not be able to pick it up. Remember that these capacitors give you the option to use the 32 kHz oscillator when you do not have the external capacitors. They are not supposed to be used when the external capacitors are being used. Now, to change the internal capacitance, you can simply change the macros contained in the board.h file (step 4). It is important that the oscillator is disabled before making any changes to the enabled capacitors. The fsl_clock_manager.c file already contains the function CLOCK_SYS_RtcOscInit() that configures the oscillator with the values established in the previously mentioned macros, however, the oscillator is not disabled before attempting to change the capacitors (and therefore, no changes are made). To fix this, you can use the RTC_HAL_SetOscillatorCmd() function to disable the oscillator before making changes with the capacitors. /* fsl_clock_manager.c */     // Disable the oscillator in case any changes are made to the capacitors RTC_HAL_SetOscillatorCmd(RTC, false);     // If the oscillator is not enabled and should be enabled. if ((!RTC_HAL_IsOscillatorEnabled(RTC)) && (config->enableOsc)) {     /* Enable the desired capacitors */     RTC_HAL_SetOsc2pfLoadCmd(RTC, config->enableCapacitor2p);     RTC_HAL_SetOsc4pfLoadCmd(RTC, config->enableCapacitor4p);     RTC_HAL_SetOsc8pfLoadCmd(RTC, config->enableCapacitor8p);     RTC_HAL_SetOsc16pfLoadCmd(RTC, config->enableCapacitor16p);         /* Re-enable the oscillator */     RTC_HAL_SetOscillatorCmd(RTC, config->enableOsc); } The fsl_clock_manager.c file can be found in: <KW40Z_connSw_install_dir>\KSDK_1.3.0\platform\system\src\clock Some reference measurements with different values for the internal capacitance: With external capacitors (internal capacitors disabled) Board Revision C LOAD Measured Frequency KW40Z – rev. C C46 & C47 32,769.03 Hz KW40Z – rev. B C46 & C47 32,769.27 Hz With internal capacitors (external capacitors removed) Enabled Capacitors C LOAD Measured Frequency SC2P 1 pF 32,773.21 Hz SC4P 2 pF 32,772.06 Hz SC2P, SC4P 3 pF 32,771.2 Hz SC4P, SC8P 6 pF 32,769.39 Hz SC2P, SC4P, SC8P 7 pF 32,769 Hz SC16P 8 pF 32,768.6 Hz SC2P, SC16P 9 pF 32,768.31 Hz SC4P, SC16P 10 pF 32,768.05 Hz SC2P, SC4P, SC16P 11 pF 32,767.83 Hz SC4P, SC8P, SC16P 14 pF 32,767.27 Hz SC2P, SC4P, SC8P, SC16P 15 pF 32,767.11 Hz Please note that the capacitance is not only composed of the enabled internal capacitance, but also the parasitic capacitances found in the package, bond wires, bond pad and the PCB traces. So, while the reference measurements given before should be close to the actual value, you should also make measurements with your board, to ensure that the frequency is trimmed specifically to your board and layout.
View full article
The KW41Z has support for an external 26 MHz or 32 MHz reference oscillator. This oscillator is used, among other things, as the clock for the RF operation. This means that the oscillator plays an important role in the RF operation and must be tuned properly to meet wireless protocol standards. The KW41Z has adjustable internal load capacitors to support crystals with different load capacitance needs. For proper oscillator function, it is important that these load capacitors be adjusted such that the oscillator frequency is as close to the center frequency of the connected crystal (either 26 MHz or 32 MHz in this case). The load capacitance is adjusted via the BB_XTAL_TRIM bit field in the ANA_TRIM register of the Radio block. The KW41Z comes preprogrammed with a default load capacitance value. However, since there is variance in devices due to device tolerances, the correct load capacitance should be verified by verifying that the optimal central frequency is attained.  You will need a spectrum analyzer to verify the central frequency. To find the most accurate value for the load capacitance, it is recommended to use the Connectivity Test demo application. This post is aimed at showing you just how to do that.   In this case, the Agilent Technologies N9020A MXA Signal Analyzer was used to measure, configured with the following parameters: FREQ (central frequency): 2405 MHz (test will be conducted on channel 11) SPAN (x-axis): 100 KHz AMPTD (amplitude, y-axis): 5 dBm To perform the test, program the KW41Z with the Connectivity Test application. The project, for both IAR and KDS, for this demo application can be found in the following folder: <KW41Z_connSw_1.0.2_install_dir>\boards\frdmkw41z\wireless_examples\smac\connectivity_test\FreeRTOS NOTE:  If you need help programming this application onto your board, consult your Getting Started material for the SMAC applications.  For the FRDM-KW41Z, it is located here. Once the device is programmed, make sure the device is connected to a terminal application in your PC. When you start the application, you're greeted by this screen: Press 'ENTER' to start the application. Press '1' to select the continuous tests mode. Press '4' to start a continuous unmodulated transmission. Once the test is running, you should be able to see the unmodulated signal in the spectrum analyzer. Press 'd' and 'f' to change the XTAL trim value, thus changing the central frequency. Now, considering the test in this example is being performed in 802.15.4 channel 11, the central frequency should be centered exactly in 2.405 GHz, but on this board, it is slightly above (2.4050259 GHz) by default. In order to fix this, the XTAL trim value was adjusted to a value that moves the frequency to where it should be centered. Once the adequate XTAL trim value is found, it can be programmed to be used by default. This other post explains how to do this process.
View full article
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
What is a BLE Beacon? A BLE Beacon is a hardware including a MCU, a BLE radio, an antenna and a power source. Things like Freescale Beacon, iBeacon, AltBeacon or Eddystone are software protocols with their own characteristics. How it works? A BLE Beacon is a non-connectable device that uses Bluetooth Low Energy (BLE or Bluetooth Smart) to broadcast packets that include identifying information and each packet receives the name of Advertising Packet. The packet structure and the information broadcasted by a Beacon depend on the protocol, but, the basic structure is conformed by: UUID. This is a unique identifier that allows identifying a beacon or a group of beacons from other ones. Major number. Used to identify a group of beacons that share a UUID. Minor number. Used to identify a specific beacon that share UUID and Major number. Example UUID Major Minor AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA 1 1 These Beacons share the same UUID and Major number, and are differentiated by Minor number. AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA 1 2 AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA 2 1 This Beacon shares the same UUID as the previous ones, but has a different Major number, so it belongs to a different group. BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB 1 1 This Beacon is completely different from the previous ones, since it doesn’t share the same UUID. These packets need to be translated or interpreted in order to provide the beacon a utility. There are applications that can interact with beacons, usually developed to be used with smartphones and/or tablets. These applications require being compliant with the protocol used by the beacon in order to be able to perform an action when a beacon is found. Use Cases Beacons can be used on different places to display different content or perform different actions, like: Restaurants, Coffee Shops, Bars Virtual Menu Detailed information Food source Suggested wine pairings Museums Contextual information. Analytics Venue check-in (entry tickets) Self-guided tours. Educational excursions Event Management and Trade Shows Frictionless Registration Improved Networking Sponsorship Navigation and Heat Mapping Content Delivery Auto Check-in Stadiums Seat finding and seat upgrading Knowing the crowded locations Promotions, offers and loyalty programs Sell Merchandise Future implementations Retail and Malls Shopping with digital treasure hunts Gather digital up-votes and down-votes from visitors Allow retailers to join forces when it comes to geo-targeted offers Use time-sensitive deal to entice new shoppers to walk in Help in navigation Engage your customers with a unified mall experience.
View full article
In this document we will be seeing how to create a BLE demo application for an adopted BLE profile based on another demo application with a different profile. In this demo, the Pulse Oximeter Profile will be implemented.  The PLX (Pulse Oximeter) Profile was adopted by the Bluetooth SIG on 14th of July 2015. You can download the adopted profile and services specifications on https://www.bluetooth.org/en-us/specification/adopted-specifications. The files that will be modified in this post are, app.c,  app_config.c, app_preinclude.h, gatt_db.h, pulse_oximeter_service.c and pulse_oximeter_interface.h. A profile can have many services, the specification for the PLX profile defines which services need to be instantiated. The following table shows the Sensor Service Requirements. Service Sensor Pulse Oximeter Service Mandatory Device Information Service Mandatory Current Time Service Optional Bond Management Service Optional Battery Service Optional Table 1. Sensor Service Requirements For this demo we will instantiate the PLX service, the Device Information Service and the Battery Service. Each service has a source file and an interface file, the device information and battery services are already implemented, so we will only need to create the pulse_oximeter_interface.h file and the pulse_oximeter_service.c file. The PLX Service also has some requirements, these can be seen in the PLX service specification. The characteristic requirements for this service are shown in the table below. Characteristic Name Requirement Mandatory Properties Security Permissions PLX Spot-check Measurement C1 Indicate None PLX Continuous Measurement C1 Notify None PLX Features Mandatory Read None Record Access Control Point C2 Indicate, Write None Table 2. Pulse Oximeter Service Characteristics C1: Mandatory to support at least one of these characteristics. C2: Mandatory if measurement storage is supported for Spot-check measurements. For this demo, all the characteristics will be supported. Create a folder for the pulse oximeter service in  \ConnSw\bluetooth\profiles named pulse_oximeter and create the pulse_oximeter_service.c file. Next, go to the interface folder in \ConnSw\bluetooth\profiles and create the pulse_oximeter_interface.h file. At this point these files will be blank, but as we advance in the document we will be adding the service implementation and the interface macros and declarations. Clonate a BLE project with the cloner tool. For this demo the heart rate sensor project was clonated. You can choose an RTOS between bare metal or FreeRTOS. You will need to change some workspace configuration.  In the bluetooth->profiles->interface group, remove the interface file for the heart rate service and add the interface file that we just created. Rename the group named heart_rate in the bluetooth->profiles group to pulse_oximeter and remove the heart rate service source file and add the pulse_oximeter_service.c source file. These changes will be saved on the actual workspace, so if you change your RTOS you need to reconfigure your workspace. To change the device name that will be advertised you have to change the advertising structure located in app_config.h. /* Scanning and Advertising Data */ static const uint8_t adData0[1] = { (gapAdTypeFlags_t)(gLeGeneralDiscoverableMode_c | gBrEdrNotSupported_c) }; static const uint8_t adData1[2] = { UuidArray(gBleSig_PulseOximeterService_d)}; static const gapAdStructure_t advScanStruct[] = { { .length = NumberOfElements(adData0) + 1, .adType = gAdFlags_c, .aData = (void *)adData0 }, { .length = NumberOfElements(adData1) + 1, .adType = gAdIncomplete16bitServiceList_c, .aData = (void *)adData1 }, { .adType = gAdShortenedLocalName_c, .length = 8, .aData = "FSL_PLX" } }; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ We also need to change the address of the device so we do not have conflicts with another device with the same address. The definition for the address is located in app_preinclude.h and is called BD_ADDR. In the demo it was changed to: #define BD_ADDR 0xBE,0x00,0x00,0x9F,0x04,0x00 ‍‍‍ Add the definitions in ble_sig_defines.h located in Bluetooth->host->interface for the UUID’s of the PLX service and its characteristics. /*! Pulse Oximeter Service UUID */ #define gBleSig_PulseOximeterService_d 0x1822 /*! PLX Spot-Check Measurement Characteristic UUID */ #define gBleSig_PLXSpotCheckMeasurement_d 0x2A5E /*! PLX Continuous Measurement Characteristic UUID */ #define gBleSig_PLXContinuousMeasurement_d 0x2A5F /*! PLX Features Characteristic UUID */ #define gBleSig_PLXFeatures_d 0x2A60 ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ We need to create the GATT database for the pulse oximeter service. The requirements for the service can be found in the PLX Service specification. The database is created at compile time and is defined in the gatt_db.h.  Each characteristic can have certain properties such as read, write, notify, indicate, etc. We will modify the existing database according to our needs. The database for the pulse oximeter service should look something like this. PRIMARY_SERVICE(service_pulse_oximeter, gBleSig_PulseOximeterService_d) CHARACTERISTIC(char_plx_spotcheck_measurement, gBleSig_PLXSpotCheckMeasurement_d, (gGattCharPropIndicate_c)) VALUE_VARLEN(value_PLX_spotcheck_measurement, gBleSig_PLXSpotCheckMeasurement_d, (gPermissionNone_c), 19, 3, 0x00, 0x00, 0x00) CCCD(cccd_PLX_spotcheck_measurement) CHARACTERISTIC(char_plx_continuous_measurement, gBleSig_PLXContinuousMeasurement_d, (gGattCharPropNotify_c)) VALUE_VARLEN(value_PLX_continuous_measurement, gBleSig_PLXContinuousMeasurement_d, (gPermissionNone_c), 20, 3, 0x00, 0x00, 0x00) CCCD(cccd_PLX_continuous_measurement) CHARACTERISTIC(char_plx_features, gBleSig_PLXFeatures_d, (gGattCharPropRead_c)) VALUE_VARLEN(value_plx_features, gBleSig_PLXFeatures_d, (gPermissionFlagReadable_c), 7, 2, 0x00, 0x00) CHARACTERISTIC(char_RACP, gBleSig_RaCtrlPoint_d, (gGattCharPropIndicate_c | gGattCharPropWrite_c)) VALUE_VARLEN(value_RACP, gBleSig_RaCtrlPoint_d, (gPermissionFlagWritable_c), 4, 3, 0x00, 0x00, 0x00) CCCD(cccd_RACP) ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ For more information on how to create a GATT database you can check the BLE Application Developer’s Guide chapter 7. Now we need to make the interface file that contains all the macros and declarations of the structures needed by the PLX service. Enumerated types need to be created for each of the flags field or status field of every characteristic of the service. For example, the PLX Spot-check measurement field has a flags field, so we declare an enumerated type that will help us keep the program organized and well structured. The enum should look something like this: /*! Pulse Oximeter Service - PLX Spotcheck Measurement Flags */ typedef enum { gPlx_TimestampPresent_c = BIT0, /* C1 */ gPlx_SpotcheckMeasurementStatusPresent_c = BIT1, /* C2 */ gPlx_SpotcheckDeviceAndSensorStatusPresent_c = BIT2, /* C3 */ gPlx_SpotcheckPulseAmplitudeIndexPresent_c = BIT3, /* C4 */ gPlx_DeviceClockNotSet_c = BIT4 } plxSpotcheckMeasurementFlags_tag; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ The characteristics that will be indicated or notified need to have a structure type that contains all the fields that need to be transmitted to the client. Some characteristics will not always notify or indicate the same fields, this varies depending on the flags field and the requirements for each field. In order to notify a characteristic we need to check the flags in the measurement structure to know which fields need to be transmitted. The structure for the PLX Spot-check measurement should look something like this: /*! Pulse Oximeter Service - Spotcheck Measurement */ typedef struct plxSpotcheckMeasurement_tag { ctsDateTime_t timestamp; /* C1 */ plxSpO2PR_t SpO2PRSpotcheck; /* M */ uint32_t deviceAndSensorStatus; /* C3 */ uint16_t measurementStatus; /* C2 */ ieee11073_16BitFloat_t pulseAmplitudeIndex; /* C4 */ uint8_t flags; /* M */ }plxSpotcheckMeasurement_t; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ The service has a configuration structure that contains the service handle, the initial features of the PLX Features characteristic and a pointer to an allocated space in memory to store spot-check measurements. The interface will also declare some functions such as Start, Stop, Subscribe, Unsubscribe, Record Measurements and the control point handler. /*! Pulse Oximeter Service - Configuration */ typedef struct plxConfig_tag { uint16_t serviceHandle; plxFeatures_t plxFeatureFlags; plxUserData_t *pUserData; bool_t procInProgress; } plxConfig_t; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ The service source file implements the service specific functionality. For example, in the PLX service, there are functions to record the different types of measurements, store a spot-check measurement in the database, execute a procedure for the RACP characteristic, validate a RACP procedure, etc. It implements the functions declared in the interface and some static functions that are needed to perform service specific tasks. To initialize the service you use the start function. This function initializes some characteristic values. In the PLX profile, the Features characteristic is initialized and a timer is allocated to indicate the spot-check measurements periodically when the Report Stored Records procedure is written to the RACP characteristic. The subscribe and unsubscribe functions are used to update the device identification when a device is connected to the server or disconnected. bleResult_t Plx_Start (plxConfig_t *pServiceConfig) { mReportTimerId = TMR_AllocateTimer(); return Plx_SetPLXFeatures(pServiceConfig->serviceHandle, pServiceConfig->plxFeatureFlags); } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ All of the services implementations follow a similar template, each service can have certain characteristics that need to implement its own custom functions. In the case of the PLX service, the Record Access Control Point characteristic will need many functions to provide the full functionality of this characteristic. It needs a control point handler, a function for each of the possible procedures, a function to validate the procedures, etc. When the application makes a measurement it must fill the corresponding structure and call a function that will write the attribute in the database with the correct fields and then send an indication or notification. This function is called RecordMeasurement and is similar between the majority of the services. It receives the measurement structure and depending on the flags of the measurement, it writes the attribute in the GATT database in the correct format. One way to update a characteristic is to create an array of the maximum length of the characteristic and check which fields need to be added and keep an index to know how many bytes will be written to the characteristic by using the function GattDb_WriteAttribute(handle, index, &charValue[0]). The following function shows an example of how a characteristic can be updated. In the demo the function contains more fields, but the logic is the same. static bleResult_t Plx_UpdatePLXContinuousMeasurementCharacteristic ( uint16_t handle, plxContinuousMeasurement_t *pMeasurement ) { uint8_t charValue[20]; uint8_t index = 0; /* Add flags */ charValue[0] = pMeasurement->flags; index++; /* Add SpO2PR-Normal */ FLib_MemCpy(&charValue[index], &pMeasurement->SpO2PRNormal, sizeof(plxSpO2PR_t)); index += sizeof(plxSpO2PR_t); /* Add SpO2PR-Fast */ if (pMeasurement->flags & gPlx_SpO2PRFastPresent_c) { FLib_MemCpy(&charValue[index], &pMeasurement->SpO2PRFast, sizeof(plxSpO2PR_t)); index += sizeof(plxSpO2PR_t); } return GattDb_WriteAttribute(handle, index, &charValue[0]); } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ The app.c handles the application specific functionality. In the PLX demo it handles the timer callback to make a PLX continuous measurement every second. It handles the key presses and makes a spot-check measurement each time the SW3 pushbutton is pressed. The GATT server callback receives an event when an attribute is written, and in our application the RACP characteristic is the only one that can be written by the client. When this event occurs, we call the Control Point Handler function. This function makes sure the indications are properly configured and check if another procedure is in progress. Then it calls the Send Procedure Response function, this function validates the procedure and calls the Execute Procedure function. This function will call one of the 4 possible procedures. It can call Report Stored Records, Report Number of Stored Records, Abort Operation or Delete Stored Records. When the project is running, the 4 LEDs will blink indicating an idle state. To start advertising, press the SW4 button and the LED1 will start flashing. When the device has connected to a client the LED1 will stop flashing and turn on. To disconnect the device, hold the SW4 button for some seconds. The device will return to an advertising state. In this demo, the spot-check measurement is made when the SW3 is pressed, and the continuous measurement is made every second. The spot-check measurement can be stored by the application if the Measurement Storage for spot-check measurements is supported (bit 2 of Supported Features Field in the PLX Features characteristic). The RACP characteristic lets the client control the database of the spot-check measurements, you can request the existing records, delete them, request the number of stored records or abort a procedure. To test the demo you can download and install a BLE Scanner application to your smartphone that supports BLE. Whit this app you should be able to discover the services in the sensor and interact with each characteristic. Depending on the app that you installed, it will parse known characteristics, but because the PLX profile is relatively new, these characteristics will not be parsed and the values will be displayed in a raw format. In Figure 1, the USB-KW40Z was used with the sniffer application to analyze the data exchange between the PLX sensor and the client. You can see how the sensor sends the measurements, and how the client interacts with the RACP characteristic. Figure 1. Sniffer log from USB-KW40Z
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
During last week I receive a question about identify a way to notice when the 32kHz oscillator is ready to be able to use it as clock source. In other words, when the 32kHz oscillator is stable to be used as reference clock for the MCG module. Then, system can switch over it. Kinetis devices starts up using its internal clock which is called FEI mode, then, the applications change to a different mode which require an external clock source (i.e. FEE mode). Normally, we have two options which are: Main reference clock. Talking specifically to KW devices, there is the 32MHz external crystal for the main reference clock. The 32kHz external crystal for the 32kHz oscillator which is driven through the RTC registers.  For the first option, there is a register which could be monitored to know when oscillator is ready (RSIM_CONTROL_RF_OSC_READY). So, it can be polled to notice when the oscillator is up and ready.  About the second option, there is no “OSCINIT” bit for the 32 kHz oscillator. However, there is a way to know when the 32kHz Oscillator is running, it is to simply enable the RTC OSC, and configure the RTC to count. After doing that immediately poll (read) the RTC_TPR register and check it until it is greater than 4096. It will roll over once it reaches 32767 so, it is important to the poll this register in a loop doing nothing else or the register could potentially be read when it is less than 4096 but had already rolled over. Once it is greater than 4096, it can be determined that oscillator is running well. If the RTC is not required, the counter can be disabled. Now that the 32kHz clock is available, the application can switch to FEE mode. So, in order to perform the above description, I modified the “CLOCK_CONFIG_EnableRtcOsc()” as shown next: static void CLOCK_CONFIG_EnableRtcOsc(uint32_t capLoad) {        rtc_config_t rtc_basic_config;        uint32_t u32cTPR_counter=0;        /* RTC clock gate enable */     CLOCK_EnableClock(kCLOCK_Rtc0);     if ((RTC->CR & RTC_CR_OSCE_MASK) == 0u)     {       /* Only if the Rtc oscillator is not already enabled */       /* Set the specified capacitor configuration for the RTC oscillator, "capLoad" parameter shall be set          to the value specific to the customer board requirement*/       RTC_SetOscCapLoad(RTC, capLoad);          /*Init the RTC with default configuration*/       RTC_GetDefaultConfig(&rtc_basic_config);       RTC_Init(RTC, &rtc_basic_config);       /* Enable the RTC 32KHz oscillator */       RTC->CR |= RTC_CR_OSCE_MASK;       /* Start the RTC time counter */       RTC_StartTimer(RTC);             /* Verify TPR register reaches 4096 counts */       while(u32cTPR_counter < 4096)       {          u32cTPR_counter= RTC->TPR;       }       /* 32kHz Oscillator is ready. Based on the application requirements, it can let the RTC enabled or disabled.           In this case, we can disable RTC since it is not needed by this application */       RTC_Deinit(RTC);     }     /* RTC clock gate disable  since RTC is not needed anymore*/     CLOCK_DisableClock(kCLOCK_Rtc0); }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ Then, using the above function, it can be noticed when the 32kHz oscillator is ready to be used. Hope this helps....
View full article
This document describes how to update and sniff Bluetooth LE wireless applications on the USB-KW41 Programming the USB-KW41 as sniffer   It was noticed that there are some issues trying to follow a Bluetooth LE connection, even if the sniffer catches the connection request. These issues have been fixed in the latest binary file which can be found in the Test Tool for Connectivity Products 12.8.0.0 or newest.   After the Test Tool Installation, you’ll find the sniffer binary file at the following path. C:\NXP\Test Tool 12.8.1.0\images\KW41_802.15.4_SnifferOnUSB.bin   Programming Process. 1. Connect the USB-KW41Z to your PC, and it will be enumerated as Mass Storage Device 2. Drag and drop the "KW41_802.15.4_SnifferOnUSB.bin" included in Test tool for Connectivity Products.    "C:\NXP\Test Tool 12.8.0.0\images\KW41_802.15.4_SnifferOnUSB.bin"   3. Unplug the device and hold the RESET button of the USB-KW41Z, plug to your PC and the K22 will enter in bootloader mode. 4. Drag and drop the "sniffer_usbkw41z_k22f_0x8000.bin" included in Test tool for Connectivity Products.    "C:\NXP\Test Tool 12.8.5.9\images\sniffer_usbkw41z_k22f_0x8000.bin"   5. Then, unplug and plug the USB-KW41Z to your PC.                                                                                                          Note: If the USB-KW41 is not enumerated as Mass Storage Device, please look at the next thread https://community.nxp.com/thread/444708   General Recommendations   Software Tools  Kinetis Protocol Analyzer Wireshark version (2.4.8) Hardware Tools 1 USB-KW41 (updated with KW41_802.15.4_SnifferOnUSB.bin from Test Tool 12.8 or later)   The Kinetis Protocol Analyzer provides the ability to monitor the Bluetooth LE Advertisement Channels. It listens to all the activity and follows the connection when capturing a Connection Request.   Bluetooth LE Peripheral device transmits packets on the 3 advertising channels one after the other, so the USB-KW41 will listen to the 3 channels one by one and could or not catch the connection request.   Common use case The USB-KW41 will follow the Bluetooth LE connection if the connection request happens on the same channel that It is listening. If is listening to a different channel when the connection request is sent, it won't be able to follow it.   A Simple recommendation is the Bluetooth LE Peripheral should be set up to send the adv packets only to one channel and the sniffer just capturing on the same channel.   Improvement Use 3 USB-KW41, each of them will be dedicated to one channel and will catch the connection request.   Configure Kinetis Protocol Analyzer and Wireshark Network Analyzer   Note: For better results, address filter can be activated. When you are capturing all the packets in the air, you will notice 3 adv packets. Each packet will show the adv channel that is getting the adv frame.       One of the three sniffers will capture the Connection Request. In this case, it happens on channel 38.       You will be able to follow the connection, see all the data exchange.   For a better reference, you can look at the USB-KW41 Getting Started     Hope it helps   Regards, Mario
View full article
Please, find the important link to build a PCB using a KW38 and all concerning the radio performances, low power and radio certification (CE/FCC/IC). Your first task before to send any inquiry to NXP support is to fill the KW38 Design In CHECK LIST available in this ticket.   KW38 product NXP web page: KW39/38/37 32-bit Bluetooth 5.0 Long-Range MCUs|NXP | NXP Semiconductors   FRDM-KW38 getting started NXP web page Getting Started with the FRDM-KW38 | NXP Semiconductors   HW: FRDM-KW38 User Guide: FRDM-KW38 Freedom Development Board User’s Guide (nxp.com.cn) Hardware design consideration: Hardware Design Considerations for MKW39A/38A/37A/38Z/37Z Bluetooth LE Devices (nxp.com) Minimum BoM: KW37_38_39 Minimum BoM Presentation.pdf - NXP Community DCDC management guide : MKW4xZ/3xZ/3xA/2xZ DC-DC Power Management (nxp.com)          Migration guide: KW36 to KW38: Migration Guide from MKW36A512xxx4 to MKW38A512xxx4 (nxp.com)          Design-In check list: attached excel file         Configuration for Unused Pins/GPIOs on Kinetis Radio: RF report: https://www.nxp.com.cn/docs/en/application-note/AN12517.pdf Annex: MIIT (China) sharpened Homologation on FRDM-KW38 &... - NXP Community          Radio co-existance: FRDM-KW38 Co-existence with RF System Evaluation Report for Bluetooth® Low Energy Application (nxp.com) Low Power Consumption: https://www.nxp.com/docs/en/application-note/AN12459.pdf Distance performances: KW37_38_39_Bluetooth LE Range Performance.pdf - NXP Community Antenna: https://www.nxp.com/docs/en/application-note/AN2731.pdf          Generic FSK Link Layer Quick Start: Connectivity test SW user guide in attached pdf file          Binary file attached: Connectivity test frdmkw38.bin          Return loss (S11) measurement: attached file          Loadpull: attached file Low Power:          Low power estimator tool link: https://community.nxp.com/t5/Connectivity-Support-QN-JN-KW/BLE-power-profile-calculator-v0p3-xlsx/ta-p/1107083 SW tools:          IoT Tool box          Connectivity test tool for connectivity products KW39/38/37 32-bit Bluetooth 5.0 Long-Range MCUs|NXP | NXP Semiconductors          DTM: How to use the HCI_bb on Kinetis family products a... - NXP Community https://community.nxp.com/t5/Wireless-Connectivity-Knowledge/BLE-HCI-Application-to-set-transmitter-receiver-test-commands/ta-p/1126093 Certification:          Zip attached file and the community link: KW39 KW38 KW37 Radio certification documents - NXP Community
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
All FSCI packets contain a checksum field to verify data integrity. Every time a FSCI packet is created (by the Host or a Kinetis device) a new CRC is calculated based on every data byte in the FSCI frame. Compute CRC for TX packet The CRC field is calculated by XORing each byte contained in the FSCI command (opcode group, opcode, payload length and payload data). Checksum field then, accumulates the result of every XOR instruction.    In the firmware, the CRC is calculated in the 'FSCI_transmitPayload()' function wich is located in '<HSDK project>/framework/FSCI/Source/FsciCommunication.c' file. See FSCI_computeChecksum(). Example: TX: AspSetXtalTrim.Request 02 95 0A 01 30 AE    Sync            [1 byte] = 02    OpGroup     [1 byte] = 95    OpCode      [1 byte] = 0A    Length         [1 byte] = 01    trimValue     [1 byte] = 30    CRC            [1 byte] = AE     <------- (0x95) XOR (0A) XOR (0x01) XOR (0x30) = 0xAE Disable CRC field validation Every time a FSCI packet is received, the device verifies the checksum value.  The next changes will allow the board to receive FSCI packets without verifying the CRC field. However, the board will send the FSCI responses to the Host with this CRC field. Go to 'FsciCommunication.c' file. Search for 'fsci_packetStatus_t FSCI_checkPacket( clientPacket_t *pData, uint16_t bytes, uint8_t* pVIntf )' function. Comment all line codes related to checksum verifying. The image below shows what has to be commented. Compile project and load it to the board. Verify functionality with Test Tool. Select any command and check Raw Data checkbox. Delete the CRC data field and send the FSCI message pressing Send Raw. The loaded command set will vary depending on the demo you are using (Thread, ZigBee, BLE, etc.). The FSCI message is sent without a CRC field and the board responses to the command successfully.
View full article
By default the clock configuration on the KW2xD demos is set to PLL Engaged External (PEE). In this mode the system clock is derived from the output of the PLL and controlled by an external reference clock. The modem provides a programmable clock source output CLK_OUT that can be used as the external reference clock for the PLL. In the Figure 1 we can see that the CLK_OUT modem signal is internally connected to EXTAL0 in the MCU.   The CLK_OUT output frequency is controlled by programming the modem 3-bit field CLK_OUT_DIV [2:0] in the CLK_OUT_CTRL Register. The default frequency is either 32.787 kHz or 4 MHz depending on the state of the modem GPIO5 at reset determined by the MCU. See section 4.4.2 and 5.6.2 from the MKW2xD Reference Manual for more information on the clock output feature. If the GPIO5 modem pin is low upon POR, then the frequency will be 4 MHz. If this GPIO5 modem pin is high upon POR, then the frequency will be 32.78689 kHz.   In the KW2xD demos, the GPIO5 (PTC0) is held low during the modem reset so the CLK_OUT has a frequency of 4MHz. The clock configuration structure g_defaultClockConfigRun is defined in board.c. Figure 1. Internal Functional Interconnects   In this example project, another clock configuration will be added to the Connectivity Test Project: FLL Engaged Internal (FEI). In this mode, the system clock is derived from the FLL clock that is controlled by the 32kHz Internal reference clock.   In FEI mode the MCU doesn’t need the clock source output CLK_OUT from the modem, so we can disable the radio’s clock output and then set the radio to Hibernate to save power when we are not using the radio.   If the low-power module from the connectivity framework is used to go to a low-power mode, the clock configuration is changed automatically when entering a sleep mode (See the Connectivity Framework Reference Manual for more information about the low-power library).   System Requirements Kinetis MKW2xD and MCR20A Connectivity Software (REV 1.0.0) TWR-KW24D512 IAR Embedded Workbench for ARM 7.60.1 or later Attached project files Application Description The clock configuration can be changed with shortcuts on the serial console: Press “c” to use the PEE clock configuration (default). Press “v” to use the FEI clock configuration and set the radio to Autodoze. Press “b” to use the FEI clock configuration and set the radio to Hibernate.   You must be in the main menu in order to change the radio mode, the mode automatically changes to Autodoze when entering a test menu.   Hibernate mode can only be changed when in FEI mode. This is because in hibernate the radio disables the CLK_OUT and the PEE configuration needs this clock.   Current Measurements The following measurements were done in a TWR-KW24D256 through J2 5-6 to measure the radio current. Table 1. Radio Current Measurements Clock mode/Radio mode Radio Current PEE/Autodoze 615µA FEI/Autodoze 417µA FEI/Hibernate 0.3µA   Code Modifications The following modifications to the source files were made: \boards\twrkw24d512\Board.c Added clock user configuration Added array of clock configs and configuration struct for clock callback   \boards\twrkw24d512\Board.h Include for fsl_clock_manager.h Declaration of clock callback and configuration array used in CLOCK_SYS_Init() function.   \boards\twrkw24d512\Hardware_init.c Added calibration code after BOARD_ClockInit(), this is to calibrate internal clock using the bus clock.   \examples\smac\Connectivity_Test\common\Connectivity_TestApp.c Initialize the clock manager. Disable PTC0 because it is only used at modem reset to select the CLK_OUT default frequency (4MHz). Return clock configuration on idle state. Prepare radio to go to Autodoze when entering a test menu.   \examples\smac\Connectivity_Test\twrkw24d512\common\Connectivity_Test_Platform.c Changed length of the lines to be erased in PrintTestParameters() from 65 to 80 Added clock config and radio mode to be printed in the test parameters. Added the cases in the shortcut parser to change the clock and radio configuration with the keys “c”, “v” and “b”. Added functions at end of file (Explained in the next section).   \examples\smac\Connectivity_Test\twrkw24d512\common\Connectivity_Test_Platform.h Macros for the clock and radio modes. Function prototypes from the source file.   \examples\smac\Connectivity_Test\twrkw24d512\common\ConnectivityMenus.c Shortcuts descriptions.   The modified source files can be found attached to this document.   Functions added The functions PWRLib_Radio_Enter_Hibernate() and PWRLib_Radio_Enter_AutoDoze() were taken from the file PWRLib.c located at <Connectivity_Software_Path>\ConnSw\framework\LowPower\Source\KW2xD. The PWRLib.c file is part of the low-power library from the connectivity framework.   The Clock_Callback() function was implemented to handle when the clock configuration is updated. Inside the function there is a case to handle before and after the clock configuration is changed. Before the clock configuration is changed, the UART clock is disabled and if the clock configuration is PEE, the radio is set to AutoDoze and the CLK_OUT is enabled. After the clock configuration has changed, the Timer module is notified that the clock has changed, the UART is re-initialized and if the clock configuration is FEI, the CLK_OUT is disabled. This behavior is shown in Figure 2. Figure 2. Clock callback diagram   The prepareRadio() function is used when entering a test mode to make sure the radio is set to AutoDoze in case it was in hibernate. The restoreRadio() function is used when leaving the test menu and going to hibernate if it was previously set.
View full article
Brief Description NXP Tire Pressure Monitoring Sensors (TPMS) were preloaded the firmware libraries and test software for a variety of customer use cases. The preloaded TPMS bootloader provides wireless software update function for the aftermarket. This demo uses Kinetis KW01 and Low Frequency emitter to accomplish TPMS over-the-air software update.   Reference Picture   Block Diagram   Features 315 MHz RF 125 KHz LF FSK modulation Manchester Encoding Timer/PWM Modules IAR Embedded Workbench for ARM 7.40 CodeWarrior V6.3   NXP Parts Used MRB-KW019032 (MKW01Z128CHN) TPMS870911 (FXTH870911DT1) LF Emitter Board   Get Software MKW01_TPMS_bootloader.rar MPXY8702_TPMS_bootloader.rar TPMS-MKW01-IAR7v4-Project.zip   General Stage Prototype Launched for Alpha customers     Demo Setup   Hardware Requirements MRB-KW019032 x 2         MRB-KW019032 Board A: Connected with LF Emitter Board         MRB-KW019032 Board B: Standalone TPMS879011 x 1 LF Emitter Board x 1   Hardware Connection   Pin function MRB-KW019032 LF Emitter Board TPM1_CH0 PTB0 (J15-9) J5-20 TPM1_CH1 PTB1 (J14-8) J5-28 GND GND (J15-2) J6-4   Demo Description A prebuild TPMS870911 firmware is stored in MRB-KW019032 Board A and this firmware will be sent to TPMS870911 via 125kHz LF signal. After TPMS870911 completes the firmware update, TPMS870911 will send the information of pressure sensor to MRB-KW019032 Board B via 315 MHz RF signal.   Demo Procedure Download MKW01_TPMS_bootloader into MRB-KW019032 Board A with IAR 7.40 Download TPMS-MKW01-IAR7v4-Project into MRB-KW019032 Board B with IAR 7.40 Download MPXY8702_TPMS_bootloader into TPMS870911 with CodeWarrior V6.3 Connect USB cable between PC and both of MRB-KW019032 boards, and open the terminal with the following settings • 115200 baud rate • 8 data bits • No parity • One stop bit • No flow control    5. Press the reset button on both of MRB-KW019032 boards and then the demo message will be shown on the terminal.     6. Short Pin19 of J15 (PTD6) on MRB-KW019032 Board A as SW3 press to start TPMS870911 over-the-air software update. 7. After TPMS870911 completes software update, MRB-KW019032 Board B will print the received RF message which was sent from TPMS870911 on the terminal.                         Original Attachment has been moved to: TPMS-MKW01-IAR7v4-Project.zip Original Attachment has been moved to: MPXY8702_TPMS_bootloader.rar Original Attachment has been moved to: MKW01_TPMS_bootloader.rar
View full article
A network is basically a set of devices connected to one another and communicating using wired or wireless mediums. There are several standard network frameworks defined for wired and wireless communication by IEEE. This post provides information about the IEEE 802 standard and network modes.   802 Standard The 802 standard is a family of IEEE standards dealing with local and metropolitan area networks. The protocol specified in the 802 standard covers lower two layers of the OSI model that are Physical and Data Link layers. In the 802 standard, the Data link layer (Layer 2 of the OSI model) has been divided into two parts Logical Link Control (LLC) and Media Access Control (MAC) as shown in figure below.   Figure 1. Layer architecture   The active 802 standards are listed below.   Table 1. 802 standards description Standard Name Description 802.1 Internetworking It ensures the management of the Local Area Network (LAN) / Metropolitan Area Network (MAN) network and monitors network capabilities. MAC bridging, data encryption/encoding, and network traffic management services are also provided. 802.3 Ethernet Ethernet based technology that is primarily used for LAN, it can also be used for MAN and Wide Area Network (WAN).     802.3 defines the Physical and MAC sublayer of the Data Link layer that is used in wired networks. Uses Carrier Sense Multiple Access with Collision Detection (CSMA/CD) for collision detection. Data rates can be from 10Mbps to 10Gbps. 802.11 WLAN, Wi-Fi Wireless LAN uses high radio frequencies instead of cables to connect the devices in the network. Portability and setup cost is cheaper compared to wired networks but speed and security are better in wired communication. It uses Carrier Sense Multiple Access with Collision Avoidance (CSMA/CA) for collision avoidance. 802.15 WPAN This covers various protocol definitions for the personal area network like Bluetooth, ZigBee & sensors networks.   WLAN and Wi-Fi Introduction Wireless Local Area Network (WLAN) or Wireless LAN, is a network that links two or more devices using wireless communication to form a local area network within a limited area such as a home, campus, and office building. A WLAN can be built on various wireless technologies i.e. Wi-Fi, Infrared. Wi-Fi is a type of WLAN that follows IEEE 802.11 standards and one of the most commonly used WLAN today. Wi-Fi as a name for the standard is a trademark of the Wi-Fi Alliance. Wi-Fi or WLAN networks use radio waves to exchange information between devices. These radio waves are transmitted on specific frequencies - 2.4 GHz and 5 GHz, depending on the 802.11 standard (IEEE 802.11a/b/g/n/ac/ax) that the device uses. A Wi-Fi connection is established using a wireless adapter to create hotspots – areas in the vicinity of a wireless router that is connected to the network and allow users to access internet services. All Wi-Fi versions uses license free bands (ISM bands) across the globe.   Network Modes Ad-Hoc Mode In this mode wireless nodes communicate to peer nodes directly. It does not use Access Point (AP) instead it uses Mesh topology. It is also called peer to peer mode. An ad-hoc wireless network is more cost-effective than its alternative, since it does not require the installation of an AP to operate. In addition, it also needs less time to set up. Figure 2. Ad-Hoc mode   Infrastructure Mode In this mode, devices can communicate with each other first going through AP. In infrastructure mode, the wireless devices can communicate with each other or can communicate with a wired network as it’s communicating through AP. This mode is the most commonly used network mode. Compared to Ad-Hoc wireless networks, infrastructure mode offers the advantages of scale, centralized security management, and improved reach. Infrastructure mode has half throughput compared to Ad-Hoc mode.   Figure 3. Infrastructure mode   Repeater Mode When two wireless host devices have to be connected and the distance between them is long for the direct connection or obstruction is present, at that time repeater mode is used to bridge the gap. Repeater operates at the physical layer of the OSI model. As a Wireless Repeater, an AP node extends the range of the wireless network by repeating the wireless signal of the remote AP. The Ethernet MAC address of the remote AP is required for the AP to act as a wireless range extender. The repeater mode has certain drawbacks. Throughput is reduced by at least 50% as wireless interference is at least doubled. The bandwidth of any device connected to it is halved. This is due to the repeater receiving the signal, processing it, and then rebroadcasting it in both directions, from the router to the device and vice versa. The Repeater must be kept in the range of AP, but not too close to the AP. Distance between AP and repeater depends on the range of the AP and repeater should be kept in such a way that maximum possible area coverage can be achieved.   Figure 4. Repeater mode   Bridge Mode Bridge connects two or more networks to each other. It operates on the Data link layer of the OSI Model. Bridge mode allows the AP to communicate with another AP capable of point-to-point bridging. An example of this is connecting two buildings through a wireless connection.   Figure 5. Bridge mode
View full article
If the application running in the KW41Z does not operate in low power mode, the device could work without the 32 kHz oscillator. However, for it to work correctly, the clock configuration must be changed. Figure 1.  KW41Z clock distribution By default, the software stack running on the KW41Z selects a clock source that requires the 32 kHz oscillator. However, if the 32 kHz oscillator is not available, the clock configuration must be changed. Fortunately, the option to change it is already implemented, it is only required to change the clock configuration to the desired one. To do this, change the value for the CLOCK_INIT_CONFIG macro located in the app_preinclude.h file. /* Define Clock Configuration */ #define CLOCK_INIT_CONFIG           CLOCK_RUN_32‍‍‍‍‍‍‍‍‍‍ In the selected mode in this example, CLOCK_RUN_32, the selected clock mode is BLPE (Bypassed Low Power External). In this mode, the FLL is bypassed entirely, and clock is derived from the external RF oscillator, in this case, the 32 MHz external clock. These macros are the default available options to change the clock configuration, they are located in the board.h file. It is up to the application and the developer to chose the most appropriate configuration. #define CLOCK_VLPR       1U #define CLOCK_RUN_16     2U #define CLOCK_RUN_32     3U #define CLOCK_RUN_13     4U #define CLOCK_RUN_26     5U #define CLOCK_RUN_48_24  6U #define CLOCK_RUN_48_16  7U #define CLOCK_RUN_20_FLL 8U‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ More information regarding the different clock modes and their clock sources are available in the KW41Z reference manual, Chapter 5: Clock Distribution, section 5.4 Clock definitions, and Chapter 24: Multipurpose Clock Generator.
View full article