Wireless Connectivity Knowledge Base

cancel
Showing results for 
Search instead for 
Did you mean: 

Wireless Connectivity Knowledge Base

Discussions

Sort by:
Bluetooth® Low Energy (or BLE) is a wireless technology that allows the exchange of information between a device that contains data (Server) and a device that requests that data (Client). Servers are usually small battery powered devices connected to sensors or actuators to gather data or perform some actions while clients are usually devices that use that information in a system or for display to a user (most common client devices are the Smartphones). When creating a custom BLE profile, we need to consider that it will need to be implemented on both Server and Client. Server will include the database of all the information that can be accessed or modified while the Client will require drivers to access and handle the data provided by the server. This post explains how to implement a custom profile in the server side using the NXP BLE stack. As example, a custom Potentiometer reporter is implemented on a MKW40Z160. Generic Attribute Profile Before implementing a custom profile, we need to be familiarized with the way BLE exchanges information. The Generic Attribute Profile (GATT) establishes how to exchange all profile and user data over a BLE connection. All standard BLE profiles are based on GATT and must comply with it to operate correctly. GATT defines two communication roles: Server and Client. The GATT Server stores the data to be transported and accepts GATT requests, commands and confirmations from the client . The GATT Client accesses data on the remote GATT server via read, write, notify or indicate operations. Figure 1 GATT Client-Server GATT data is exposed using attributes that are organized to describe the information accessible in a GATT server. These are Profile, Service, Characteristic and Descriptor. Profiles are high level definitions that determine the behavior of the application as a whole (i.e. Heart Rate Monitor, or Temperature Sensor). Profiles are integrated by one or more Services that define individual functionalities (i.e. a Heart Rate Monitor requires a Heart Rate Sensor and a Battery Measurement Unit). Services are integrated by one or more characteristics that hold individual measurements, control points or other data for a service (i.e. Heart Rate Sensor might have a characteristic for Heart Rate and other for Sensor Location). Finally Descriptors define how characteristics must be accessed. Figure 2 GATT database structure Adding a New Service to the GATT Database The GATT database in a server only includes attributes that describe services, characteristics and descriptors. Profiles are implied since they are a set of predefined services. In the NXP Connectivity Software, macros are used to define each of the attributes present in the database in an easier way. Each service and characteristic in a GATT database has a Universally Unique Identifier (UUID). These UUID are assigned by Bluetooth Org on adopted services and characteristics. When working with custom profiles, a proprietary UUID must be assigned. In the NXP connectivity Software, custom UUIDs are defined in the file gatt_uuid128.h. Each new UUID must be defined using the macro UUID128 (name, bytes) where name is an identifier that will help us to reference the UUID later in the code. Byte is a sequence of 16-bytes (128-bits) which are the custom UUID. Following is an example of the definition of the Potentiometer service and the Potentiometer Relative Value characteristic associated to it. /* Potentiometer Service */ UUID128 ( uuid_service_potentiometer , 0xE0 , 0x1C , 0x4B , 0x5E , 0x1E , 0xEB , 0xA1 , 0x5C , 0xEE , 0xF4 , 0x5E , 0xBA , 0x04 , 0x56 , 0xFF , 0x02 ) /* Potentiometer Characteristic */ UUID128 ( uuid_characteristic_potentiometer_relative_value , 0xE0 , 0x1C , 0x4B , 0x5E , 0x1E , 0xEB , 0xA1 , 0x5C , 0xEE , 0xF4 , 0x5E , 0xBA , 0x04 , 0x57 , 0xFF , 0x02 ) ‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ Once proper UUIDs have been stablished, the new service must be added to the GATT database. It is defined in the file gatt_db.h. Simple macros are used to include each of the attributes in the proper order. Following code shows the implementation of the potentiometer service in gatt_db file. PRIMARY_SERVICE_UUID128(service_potentiometer, uuid_service_potentiometer)     CHARACTERISTIC_UUID128(char_potentiometer_relative_value, uuid_characteristic_potentiometer_relative_value, (gGattCharPropRead_c | gGattCharPropNotify_c))         VALUE_UUID128(value_potentiometer_relative_value, uuid_characteristic_potentiometer_relative_value, (gPermissionFlagReadable_c ), 1, 0x00)         CCCD(cccd_potentiometer)         DESCRIPTOR(cpfd_potentiometer, gBleSig_CharPresFormatDescriptor_d, (gPermissionFlagReadable_c), 7, gCpfdUnsigned8BitInteger, 0x00,                    0xAD/*Unit precentage UUID in Little Endian (Lower byte)*/,                    0x27/*Unit precentage UUID in Little Endian (Higher byte)*/,                    0x01, 0x00, 0x00) ‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ PRIMARY_SERVICE_UUID128 (service_name, service_uuid) defines a new service in the GATT database with a custom 128-bit UUID. It requires two parameters; service_name is the name of this service in the code and it is used later during the program implementation. Service_uuid is the identifier for the service UUID previously defined in gatt_uuid128.h. CHARACTERISTIC_UUID128 (characteristic_name, characteristic_uuid, flags) defines a new characteristic inside the previously defined service with a custom 128-bit UUID. It requires three parameters; characteristic_name is the name of the characteristic in the code, characteristic_uuid is the identifier for the characteristic UUID previously defined in gatt_uuid128.h. Finally, flags is a concatenation of all the characteristic properties (read, write, notify, etc.). VALUE_UUID128 (value_name, characteristic_uuid, permission_flags, number_of_bytes, initial_values…) defines the value in the database of the previously defined characteristic. Value_name is an identifier used later in the code to read or modify the characteristic value. Characteristic_uuid is the same UUID identifier for the previously defined characteristic. Permission_flags determine how the value can be accessed (read, write or both). Number of bytes define the size of the value followed by the initial value of each of those bytes. CCCD (cccd_name) defines a new Client Characteristic Configuration Descriptor for the previously defined characteristic. Cccd_name is the name of the CCCD for use later in the code. This value is optional depending on the characteristic flags. DESCRIPTOR (descriptor_name, descriptor_format, permissions, size, descriptor_bytes…) defines a descriptor for the previously defined characteristic. Descriptor_name defines the name for this descriptor. Descriptor_format determines the type of descriptor. Permissions stablishes how the descriptor is accessed. Finally the size and descriptor bytes are added. All the macros used to fill the GATT database are properly described in the BLEADG (included in the NXP Connectivity Software documentation) under chapter 7 “Creating a GATT Database”. Implementing Drivers for New Service Once the new service has been defined in gatt_db.h, drivers are required to handle the service and properly respond to client requests. To do this, two new files need to be created per every service added to the application; (service name)_service.c and (service name)_interface.h. The service.c file will include all the functions required to handle the service data, and the interface.h file will include all the definitions used by the application to refer to the recently created service. It is recommended to take an existing file for reference. Interface header file shall include the following. Service configuration structure that includes a 16-bit variable for Service Handle and a variable per each characteristic value in the service . /*! Potentiometer Service - Configuration */ typedef struct psConfig_tag {     uint16_t    serviceHandle ;                  /*!<Service handle */     uint8_t     potentiometerValue ;             /*!<Input report field */ } psConfig_t ; ‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ Function declarations for the start service and stop service functions. These are required to initialize/deinitialize a service . bleResult_t Ps_Start ( psConfig_t * pServiceConfig ) ; bleResult_t Ps_Stop ( psConfig_t * pServiceConfig ) ; ‍‍‍ ‍ ‍ ‍ Function declarations for subscribe and unsubscribe functions required to subscribe/unsubscribe a specific client to a service . bleResult_t Ps_Subscribe ( deviceId_t clientDeviceId ) ; bleResult_t Ps_Unsubscribe ( ) ; ‍‍‍ ‍ ‍ ‍ Depending on your application, functions to read, write, update a specific characteristic or a set of them . bleResult_t Ps_RecordPotentiometerMeasurement ( uint16_t serviceHandle , uint8_t newPotentiometerValue ) ; ‍ ‍ Service source file shall include the following. A deviceId_t variable to store the ID for the subscribed client . /*! Potentiometer Service - Subscribed Client*/ static deviceId_t mPs_SubscribedClientId ; ‍‍‍ ‍ ‍ ‍ Function definitions for the Start, Stop, Subscribe and Unsubscribe functions. The Start function may include code to set an initial value to the service characteristic values . bleResult_t Ps_Start ( psConfig_t * pServiceConfig ) {         /* Clear subscibed clien ID (if any) */     mPs_SubscribedClientId = gInvalidDeviceId_c ;         /* Set the initial value defined in pServiceConfig to the characteristic values */     return Ps_RecordPotentiometerMeasurement ( pServiceConfig -> serviceHandle ,                                              pServiceConfig -> potentiometerValue ) ; } bleResult_t Ps_Stop ( psConfig_t * pServiceConfig ) {   /* Unsubscribe current client */     return Ps_Unsubscribe ( ) ; } bleResult_t Ps_Subscribe ( deviceId_t deviceId ) {    /* Subscribe a new client to this service */     mPs_SubscribedClientId = deviceId ;     return gBleSuccess_c ; } bleResult_t Ps_Unsubscribe ( ) {    /* Clear current subscribed client ID */     mPs_SubscribedClientId = gInvalidDeviceId_c ;     return gBleSuccess_c ; } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ Definition of the service specific functions. It is, the functions used to write, read or notify characteristic values. Our example only implements two; a public function to update a characteristic value in the GATT database, and a local function to issue a notification with the recently updated value to the client . bleResult_t Ps_RecordPotentiometerMeasurement ( uint16_t serviceHandle , uint8_t newPotentiometerValue ) {     uint16_t  handle ;     bleResult_t result ;     /* Get handle of Potentiometer characteristic */     result = GattDb_FindCharValueHandleInService ( serviceHandle ,         gBleUuidType128_c , ( bleUuid_t * ) & potentiometerCharacteristicUuid128 , & handle ) ;     if ( result != gBleSuccess_c )         return result ;     /* Update characteristic value */     result = GattDb_WriteAttribute ( handle , sizeof ( uint8_t ) , ( uint8_t * ) & newPotentiometerValue ) ;     if ( result != gBleSuccess_c )         return result ;     Ps_SendPotentiometerMeasurementNotification ( handle ) ;     return gBleSuccess_c ; } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ Previous function first obtains the handle value of the characteristic value we want to modify. Handle values are like an index used by the application to access attributes in the database. The UUID for the Potentiometer Relative Value is used to obtain the proper handle by calling GattDb_FindCharValueHandleInService function. Once handle has been obtained, is used in the GattDb_WriteAttribute function to write the new value into the GATT database and it can be accessed by the client. Finally our second function is called to issue a notification . static void Ps_SendPotentiometerMeasurementNotification (   uint16_t handle ) {     uint16_t  hCccd ;     bool_t isNotificationActive ;     /* Get handle of CCCD */     if ( GattDb_FindCccdHandleForCharValueHandle ( handle , & hCccd ) != gBleSuccess_c )         return ;     if ( gBleSuccess_c == Gap_CheckNotificationStatus         ( mPs_SubscribedClientId , hCccd , & isNotificationActive ) &&         TRUE == isNotificationActive )     {         GattServer_SendNotification ( mPs_SubscribedClientId , handle ) ;     } } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ SendPotentiometerMeasurementNotification sends a notification to the client. It first obtain the handle value of the CCCD we defined in the GATT database for this characteristic. Then, it checks that the CCCD has been written by the client for notifications. If it has, then it sends the notification so the client can perform a read to the characteristic value. All the functions used to access the GATT database and use the GATT server are better explained in the BLEADG document under chapters 6 and 7. Also instructions on how to create a custom profile are included in chapter 8. BLEADG is part of the NXP Connectivity Software documentation. Integrating a New Service to an Existing BLE Project So far a new service has been created in the database and functions to handle it have been defined. Now this new project must be integrated so it can be managed by the NXP Connectivity Stack. Folder structure of an NXP Connectivity Software project is divided in five different modules. App includes all the application files. Bluetooth contains files related with BLE communications. Framework contains auxiliary software used by the stack for the handling of memory, low power etcetera. KSDK contains the Kinetis SDK drivers for low level modules (ADC, GPIO…) and RTOS include files associated with the operating system. Figure 3 Folder structure Service files must be added to the project under the Bluetooth folder, inside the profiles sub-folder. A new folder must be created for the service.c file and the interface.h file must be added under the interface sub-folder. Figure 4 Service files included Once the files are included in the project, the service must be initialized in the stack. File app.c is the main application file for the NXP BLE stack. It calls all the BLE initializations and application callbacks. The service_interface.h file must be included in this file. Figure 5 Interface header inclusion Then in the local variables definition, a new service configuration variable must be defined for the new service. The type of this variable is the one defined in the service interface file and must be initialized with the service name (defined in gattdb.h) and the initial values for all the characteristic values. Figure 6 Service configuration struct The service now must be initialized. It is performed inside the BleApp_Config function by calling the Start function for the recently added service. static void BleApp_Config ( ) {       /* Read public address from controller */     Gap_ReadPublicDeviceAddress ( ) ;     /* Register for callbacks*/     App_RegisterGattServerCallback ( BleApp_GattServerCallback ) ;       .    .    .    mAdvState . advOn = FALSE ;     /* Start services */     Lcs_Start ( & lcsServiceConfig ) ;     Dis_Start ( & disServiceConfig ) ;     Irs_Start ( & irsServiceConfig ) ;     Bcs_Start ( & bcsServiceConfig ) ;     Ps_Start ( & psServiceConfig ) ; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ Finally, subscribe and unsubscribe functions must be added to the proper host callback. In the BleApp_ConnectionCallback function the subscribe function must be called after the gConnEvtConnected_c (device connected) case, and the unsubscribe function must be called after the gConnEvtDisconnected_c (device disconnected) case. static void BleApp_ConnectionCallback ( deviceId_t peerDeviceId , gapConnectionEvent_t * pConnectionEvent ) {     switch ( pConnectionEvent -> eventType )     {         case gConnEvtConnected_c :         {         .         .         .             /* Subscribe client*/             mPeerDeviceId = peerDeviceId ;             Lcs_Subscribe ( peerDeviceId ) ;             Irs_Subscribe ( peerDeviceId ) ;             Bcs_Subscribe ( peerDeviceId ) ;             Cts_Subscribe ( peerDeviceId ) ;             Ps_Subscribe ( peerDeviceId ) ;             Acs_Subscribe ( peerDeviceId ) ;             Cps_Subscribe ( peerDeviceId ) ;             Rcs_Subscribe ( peerDeviceId ) ;         .         .         .         case gConnEvtDisconnected_c :         {         /* UI */           Led1Off ( ) ;                     /* Unsubscribe client */           mPeerDeviceId = gInvalidDeviceId_c ;           Lcs_Unsubscribe ( ) ;           Irs_Unsubscribe ( ) ;           Bcs_Unsubscribe ( ) ;           Cts_Unsubscribe ( ) ;           Ps_Unsubscribe ( ) ;           Acs_Unsubscribe ( ) ;           Cps_Unsubscribe ( ) ;           Rcs_Unsubscribe ( ) ; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ After this, services can be accessed by a client application. Handling Notifications and Write Requests Once the new service has been initialized, it is possible for the client to access GATT database attributes and issue commands (read, write, notify…). Nevertheless, when an attribute is written or a CCCD is set to start notifications, program must be aware of these requests to handle them if required. Handling Notifications When a characteristic has been configured as notifiable, the client expects to receive messages from it every time in a while depending on the pre-configured parameters. To indicate this, the client writes the specific CCCD for the characteristic indicating that notifications must start/stop being sent. When this occurs, BleApp_GattServerCallback is executed in the main program. All the application CCCDs must be monitored when the gEvtCharacteristicCccdWritten_c event is set. This event indicates that a CCCD has been written. A conditional structure must be programmed to determine which CCCD was modified and act accordingly. static void BleApp_GattServerCallback ( deviceId_t deviceId , gattServerEvent_t * pServerEvent ) {     switch ( pServerEvent -> eventType )     {       case gEvtCharacteristicCccdWritten_c :         {             /*             Attribute CCCD write handler: Create a case for your registered attribute and             execute callback action accordingly             */             switch ( pServerEvent -> eventData . charCccdWrittenEvent . handle )             {             case cccd_input_report : {               //Determine if the timer must be started or stopped               if ( pServerEvent -> eventData . charCccdWrittenEvent . newCccd ) {                 // CCCD set, start timer                 TMR_StartTimer ( tsiTimerId , gTmrIntervalTimer_c , gTsiUpdateTime_c , BleApp_TsiSensorTimer , NULL ) ; #if gAllowUartDebug                 Serial_Print ( debugUartId , "Input Report notifications enabled \n\r" , gNoBlock_d ) ; #endif               }               else {                 // CCCD cleared, stop timer                 TMR_StopTimer ( tsiTimerId ) ; #if gAllowUartDebug                 Serial_Print ( debugUartId , "Input Report notifications disabled \n\r" , gNoBlock_d ) ; #endif               }             }               break ;                           case cccd_potentiometer : {               //Determine if the timer must be started or stopped               if ( pServerEvent -> eventData . charCccdWrittenEvent . newCccd ) {                 // CCCD set, start timer                 TMR_StartTimer ( potTimerId , gTmrIntervalTimer_c , gPotentiometerUpdateTime_c , BleApp_PotentiometerTimer , NULL ) ; #if gAllowUartDebug                 Serial_Print ( debugUartId , "Potentiometer notifications enabled \n\r" , gNoBlock_d ) ; #endif               }               else {                 // CCCD cleared, stop timer                 TMR_StopTimer ( potTimerId ) ; #if gAllowUartDebug                 Serial_Print ( debugUartId , "Potentiometer notifications disabled \n\r" , gNoBlock_d ) ; #endif               }             }               break ; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ In this example, when the gEvtCharacteristicCccdWritten_c is set a switch-case selector is executed to determine the written CCCD. This is done by reading the pServerEvent structure in the eventData.charCccdWrittenEvent.handle field. The obtained handle must be compared with the name of the CCCD defined in gatt_db.h for each notifiable characteristic. Figure 7 CCCD name Once the correct CCCD has been detected, the program must determine if it was set or clear. This is done by reading the pServerEvent structure in the eventData.charCccdWrittenEvent.newCccd and executing an action accordingly. In the example code, a timer is started or stopped. Once this timer reaches its modulo value, a new notification is sent using the Ps_RecordPotentiometerMeasurement function previously defined in the service files (see Implementing Drivers for New Service). Handling Write Requests Write request callbacks are not automatically generated like the notification ones. They must be registered during the application initialization. Something to take into account is when this feature is enabled, the written value is not automatically stored in the GATT database. Developers must implement code to do this and perform other application actions if needed.To do this, the GattServer_RegisterHandlesForWriteNotifications function must be called including the handles of all the characteristics that are wanted to generate a callback when written. * Configure writtable attributes that require a callback action * /     uint16_t notifiableHandleArray [ ] = { value_led_control , value_buzzer , value_accelerometer_scale , value_controller_command , value_controller_configuration } ;     uint8_t notifiableHandleCount = sizeof ( notifiableHandleArray ) / 2 ;     bleResult_t initializationResult = GattServer_RegisterHandlesForWriteNotifications ( notifiableHandleCount , ( uint16_t * ) & notifiableHandleArray [ 0 ] ) ; ‍‍‍‍ ‍ ‍ ‍ ‍ ‍ In this example, an array with all the writable characteristics was created. The function that register callbacks requires the quantity of characteristic handles to be registered and the pointer to an array with all the handles. After a client has connected, the gEvtAttributeWritten_c will be executed inside the function BleApp_GattServerCallback every time one of the configured characteristics has been written. Variable pServerEvent->eventData.attributeWrittenEvent.handle must be read to determine the handle of the written characteristic and perform an action accordingly. Depending on the user application, the GATT database must be updated with the new value. To do this, function GattDb_WriteAttribute must be executed. It is recommended to create a function inside the service.c file that updates the attribute in database. case gEvtAttributeWritten_c:         {             /*             Attribute write handler: Create a case for your registered attribute and             execute callback action accordingly             */             switch(pServerEvent->eventData.attributeWrittenEvent.handle){               case value_led_control:{                 bleResult_t result;                                 //Get written value                 uint8_t* pAttWrittenValue = pServerEvent->eventData.attributeWrittenEvent.aValue;                                 //Create a new instance of the LED configurator structure                 lcsConfig_t lcs_LedConfigurator = {                   .serviceHandle = service_led_control,                   .ledControl.ledNumber = (uint8_t)*pAttWrittenValue,                   .ledControl.ledCommand = (uint8_t)*(pAttWrittenValue + sizeof(uint8_t)),                 };                                 //Call LED update function                 result = Lcs_SetNewLedValue(&lcs_LedConfigurator);                                 //Send response to client                 BleApp_SendAttWriteResponse(&deviceId, pServerEvent, &result);                               }               break; ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ After all the required actions have been executed, server must send a response to the client. To do this, function GattServer_SendAttributeWrittenStatus is called including the handle and the error code for the client (OK or any other error status). static void BleApp_SendAttWriteResponse ( deviceId_t * pDeviceId , gattServerEvent_t * pGattServerEvent , bleResult_t * pResult ) {   attErrorCode_t attErrorCode ;     // Determine response to send (OK or Error)   if ( * pResult == gBleSuccess_c )     attErrorCode = gAttErrCodeNoError_c ;   else {     attErrorCode = ( attErrorCode_t ) ( * pResult & 0x00FF ) ;   }   // Send response to client    GattServer_SendAttributeWrittenStatus ( * pDeviceId , pGattServerEvent -> eventData . attributeWrittenEvent . handle , attErrorCode ) ; } ‍‍‍‍‍‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ More information on how to handle writable characteristics can be found in the BLEADG Chapter 5 (Included in the NXP Connectivity Software documentation). References Bluetooth® Low Energy Application Developer’s Guide (BLEADG)– Included in the NXP Connectivity Software Documentation FRDM-KW40Z Demo Application - Link
View full article
The KW40Z connectivity software stack has several demo application available, and one of them is the OTAP client. This application allows the user to reprogram the device in a wireless fashion. This can be done by both using another device with an OTAP server application, or with the Kinetis BLE Toolbox mobile application, using the OTAP tool. To create a binary file for the KW40Z, follow these next steps: Using IAR Embedded Workbench, open the application you want to send through OTAP. Right click the main project, and open the Options... menu.                                                                                                                                              In the options menu, go to the Output Converter submenu. In the Output Converter submenu, check the "Generate additional output" box, and choose Motorola as the Output format.                                                                                                                                                                            In the options menu, go to the Linker submenu. Now, in the Config tab, replace the symbols in the Configuration file symbol definitions box with these: gUseNVMLink_d=1 gUseBootloaderLink_d=1 gUseInternalStorageLink_d=0 __ram_vector_table__=1                                                                                                                                                                                              In the Linker submenu, go to the Input tab. In the Keep symbols box, add the symbol 'bootloader' (without the quotes). In the Input tab, in the Raw binary image box, in the File option, add the following path: $PROJ_DIR$\..\..\..\..\..\..\..\framework\Bootloader\Bin\BootloaderOTAP_KW40Z4.bin In the Raw binary image box, add the following options to the Symbol, Section and Align boxes: Symbol: bootloader Section: .bootloader Align: 4                                                                                                                                                                                                                         Press OK. Compile the project. The output file (*.srec) should be in the main project folder, inside the debug folder.                                                      You can now use this binary file to reprogram your device with OTAP.
View full article
Bluetooth Low Energy, through the Generic Attribute Profile (GATT), supports various ways to send and receive data between clients and servers. Data can be transmitted through indications, notifications, write requests and read requests. Data can also be transmitted through the Generic Access Profile (GAP) by using broadcasts. Here however, I'll focus on write and read requests. Write and read requests are made by a client to a server, to ask for data (read request) or to send data (write request). In these cases, the client first makes the request, and the server then responds, by either acknowledging the write request (and thus, writing the data) or by sending back the value requested by the client. To be able to make write and read requests, we must first understand how BLE handles the data it transmits. To transmit data back and forth between devices, BLE uses the GATT protocol. The GATT protocol handles data using a GATT database. A GATT database implements profiles, and each profile is made from a collection of services. These services each contain one or more characteristics. A BLE characteristic is made of attributes. These attributes constitute the data itself, and the handle to reference, access or modify said data. To have a characteristic that is able to be both written and read, it must be first created. This is done precisely in the GATT database file ( gatt_db.h 😞 /* gatt_db.h */ /* Custom service*/ PRIMARY_SERVICE_UUID128(service_custom, uuid_custom_service)     /* Custom characteristic with read and write properties */     CHARACTERISTIC_UUID128(char_custom, uuid_custom_char, (gGattCharPropRead_c | gGattCharPropWrite_c))         /* Custom length attribute with read and write permissions*/         VALUE_UUID128_VARLEN(value_custom, uuid_custom_char, (gPermissionFlagReadable_c | gPermissionFlagWritable_c), 50, 1, 0x00) The custom UUIDs are defined in the gatt_uuid128.h file: /* gatt_uuid128.h */ /* Custom 128 bit UUIDs*/ UUID128(uuid_custom_service, 0xE0, 0x1C, 0x4B, 0x5E, 0x1E, 0xEB, 0xA1, 0x5C, 0xEE, 0xF4, 0x5E, 0xBA, 0x00, 0x01, 0xFF, 0x01) UUID128(uuid_custom_char, 0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6, 0x17, 0x28, 0x39, 0x4A, 0x5B, 0x6C, 0x7D, 0x8E, 0x9F, 0x00) With this custom characteristic, we can write and read a value of up to 50 bytes (as defined by the variable length value declared in the gatt_db.h file, see code above). Remember that you also need to implement the interface and functions for the service. For further information and guidance in how to make a custom profile, please refer to the BLE application developer's guide (BLEDAG.pdf, located in <KW40Z_connSw_install_dir>\ConnSw\doc\BLEADG.pdf. Once a connection has been made, and you've got two (or more) devices connected, read and write requests can be made. I'll first cover how to make a write and read request from the client side, then from the server side. Client To make a write request to a server, you'll need to have the handle for the characteristic you want to modify. This handle should be stored once the characteristic discovery is done. Obviously, you also need the data that is going to be written. The following function needs a pointer to the data and the size of the data. It also uses the handle to tell the server what characteristic is going to be written: static void SendWriteReq(uint8_t* data, uint8_t dataSize) {       gattCharacteristic_t characteristic;     characteristic.value.handle = charHandle;     // Previously stored characteristic handle     GattClient_WriteCharacteristicValue( mPeerInformation.deviceId, &characteristic,                                          dataSize, data, FALSE,                                          FALSE, FALSE, NULL); } uint8_t wdata[15] = {"Hello world!\r"}; uint8_t size = sizeof(wdata); SendWriteReq(wdata, size); The data is send with the GattClient_WriteCharacteristicValue() API. This function has various configurable parameters to establish how to send the data. The function's parameters are described with detail on the application developer's guide, but basically, you can determine whether you need or not a response for the server, whether the data is signed or not, etc. Whenever a client makes a read or write request to the server, there is a callback procedure triggered,  to which the program then goes. This callback function has to be registered though. You can register the client callback function using the App_RegisterGattClientProcedureCallback() API: App_RegisterGattClientProcedureCallback( gattClientProcedureCallback ); void gattClientProcedureCallback ( deviceId_t deviceId,                                    gattProcedureType_t procedureType,                                    gattProcedureResult_t procedureResult,                                    bleResult_t error ) {   switch (procedureType)   {        /* ... */        case gGattProcWriteCharacteristicValue_c:             if (gGattProcSuccess_c == procedureResult)             {                  /* Continue */             }             else             {                  /* Handle error */             }             break;        /* ... */   } } Reading an attribute is somewhat similar to writing an attribute, you still need the handle for the characteristic, and a buffer in which to store the read value: #define size 17 static void SendReadReq(uint8_t* data, uint8_t dataSize) {     /* Memory has to be allocated for the characteristic because the        GattClient_ReadCharacteristicValue() API runs in a different task, so        it has a different stack. If memory were not allocated, the pointer to        the characteristic would point to junk. */     characteristic = MEM_BufferAlloc(sizeof(gattCharacteristic_t));     data = MEM_BufferAlloc(dataSize);         characteristic->value.handle = charHandle;     characteristic->value.paValue = data;     bleResult_t result = GattClient_ReadCharacteristicValue(mPeerInformation.deviceId, characteristic, dataSize); } uint8_t rdata[size];         SendReadReq(rdata, size); As mentioned before, a callback procedure is triggered whenever there is a write or read request. This is the same client callback procedure used for the write request, but the event generates a different procedure type: void gattClientProcedureCallback ( deviceId_t deviceId,                                    gattProcedureType_t procedureType,                                    gattProcedureResult_t procedureResult,                                    bleResult_t error ) {   switch (procedureType)   {        /* ... */        case gGattProcReadCharacteristicValue_c:             if (gGattProcSuccess_c == procedureResult)             {                  /* Read value length */                  PRINT(characteristic.value.valueLength);                  /* Read data */                  for (uint16_t j = 0; j < characteristic.value.valueLength; j++)                  {                       PRINT(characteristic.value.paValue[j]);                  }             }             else             {               /* Handle error */             }             break;       /* ... */   } } There are some other methods to read an attribute. For further information, refer to the application developer's guide chapter 5, section 5.1.4 Reading and Writing Characteristics. Server Naturally, every time there is a request to either read or write by a client, there must be a response from the server. Similar to the callback procedure from the client, with the server there is also a callback procedure triggered when the client makes a request. This callback function will handle both the write and read requests, but the procedure type changes. This function should also be registered using the  App_RegisterGattServerCallback() API. When there is a read request from a client, the server responds with the read status: App_RegisterGattServerCallback( gattServerProcedureCallback ); void gattServerProcedureCallback ( deviceId_t deviceId,                                    gattServerEvent_t* pServerEvent ) {     switch (pServerEvent->eventType)     {         /* ... */         case gEvtAttributeRead_c:             GattServer_SendAttributeReadStatus(deviceId, value_custom, gAttErrCodeNoError_c);                             break;         /* ... */     } } When there is a write request however, the server should write the received data in the corresponding attribute in the GATT database. To do this, the function GattDb_WriteAttribute() can be used: void gattServerProcedureCallback ( deviceId_t deviceId,                                    gattServerEvent_t* pServerEvent ) {     switch (pServerEvent->eventType)     {         /* ... */         case gEvtAttributeWritten_c:             if (pServerEvent->eventData.attributeWrittenEvent.handle == value_custom)             {                 GattDb_WriteAttribute( pServerEvent->eventData.attributeWrittenEvent.handle,                                        pServerEvent->eventData.attributeWrittenEvent.cValueLength,                                        pServerEvent->eventData.attributeWrittenEvent.aValue );                              GattServer_SendAttributeWrittenStatus(deviceId, value_custom, gAttErrCodeNoError_c);             }             break;         /* ... */     } } If you do not register the server callback function, the attribute can still be written in the GATT database (it is actually done automatically), however, if you want something else to happen when you receive a request (turning on a LED, for example), you will need the server callback procedure.
View full article
Wireless communication systems require several different components or parts to achieve reliable systems. Components like the antenna, radio and XTAL are all key elements in wireless communication. Here however, the XTAL will be discussed. In the Kinetis W series, for example, the XTAL used for wireless operation is usually the oscillator also used as a core clock. Now, while this external oscillator is connected to the MCU, it is also connected to an internal programmable capacitor bank. What is the purpose of these capacitor banks? To allow frequency trimming. And why would you want to trim the frequency provided by this oscillator? Well, to properly adjust the central frequency to where it should be operating. This option exists because not every design is going to be the same: not the same PCB, not the same components, not the same manufacturing process. Thus, having the option to adjust the frequency provided by the external oscillator allows to any possible device to operate under the same conditions is essential. Let’s say your design is using a 32 MHz external oscillator, but because of the conditions of your whole design, the operating frequency ends up being slightly different. Now, if this design transmits over the air through 802.15.4, there could be some consequences to this slight shift in frequency. This capture shows a transmission made without being centered in the desired channel. This signal should be centered exactly on 2405 MHz, as specified by IEEE 802.15.4 channel 11. As you may see, in this case the frequency is actually centered on 2405.0259 MHz. Trimming these capacitors to change the frequency obtained from the oscillator can help to adjust error. In this case, the frequency was adjusted so that it was centered in the central frequency of the desired channel, to prevent any possible mistakes while transmitting to other devices. Once the XTAL is trimmed, the signal is effectively centered on 802.15.4 channel 11's frequency, 2405 MHz. Both transmit and receive are affected by incorrect frequency trim. Receiver performance is degraded when either (or both) of the transmitting or receiving stations have a frequency offset. And if both transmitting and receiving stations have frequency offsets in opposite directions the result is the receiver experiences the sum of the frequency offsets. Now, when trimming the frequency of a design, there are two possibilities: That the board layout design, board manufacturing and component selection have repeatable values of resistance, capacitance and inductance, resulting in a stable XTAL trim – The components and manufacturing process of the board are reliable enough, allowing you to characterize the XTAL trim during the system development and then use it every board during production. That the design and component selection do not result in a stable XTAL trim – If there is considerable variation between different boards of the same design or components used in the board manufacturing, you would need to implement a XTAL trim procedure during the production process, and somehow program that trim value into the device's NVM. For evaluation purposes, a manual adjustment could be done to a single device, modifying the corresponding XTAL trim register, and then including said adjustment in the evaluation application. The two posts linked explain how to modify and use the SMAC Connectivity Test demo to find the proper XTAL trim for KW40Z and KW41Z.
View full article
This document and the attached files are maintained up to date in collaboration with Dragos Musoiu. This document is a supplement for USB MSC device bootloader revision for FRDM-KL25Z (IAR) written by Kai Liu and describes the bootloader support for USB-KW24D512. How to use 1) Connect the USB-KW24D512 to the PC USB port; 2) Download the attached file ‘USB_KW24D512_MSD_Bootloader.bin’ to the flash memory of the MKW24D512 SiP following the next steps: Connect a J-Link programmer to the PC USB port (other than the one used for the USB-KW24D512 dongle); Navigate to your J-Link driver folder using a command console and type ‘jlink.exe’ followed by enter; After the apparition of the J-Link prompter, type ‘unlock kinetis’ followed by enter; Wait for the unlock command confirmation and after, type ‘device mkw24d512xxx5’ followed by enter; After the J-Link prompter appears type ‘loadbin USB_KW24D512_MSD_Bootloader.bin 0’ followed by enter; (Be sure you copied the ‘USB_KW24D512_MSD_Bootloader.bin’ file in the same directory with jlink.exe otherwise, type the command specifying the full path of the binary file); After the flashing process successfully finished type ‘exit’ followed by enter. 3) Reset or reconnect the USB-KW24D512; 4) The OS will prompt MSD device connecting and then BOOTLOADER drive will appear. The bootloader software was tested on Microsoft Windows 10, Microsoft Windows 8.1, Microsoft Windows 7, Ubuntu 14.04 and MAC operating systems. 5) Copy and paste any user application .SREC or .bin file into BOOTLOADER drive; 6) If a valid .SREC or .bin file was given, the board restarts and starts to run the user application. Please refer to the Notes section in order to create valid .SREC or .bin files. Note:            The bootloader has conditional jump to user application. The condition is the state of the SW1 button (PTC4). If the button is pressed (PTC4 grounded) during reset, the bootloader sequence will start, installing BOOTLOADER drive, as described before. Else if the button is released during reset, the SP and PC will be updated from address 0xC000. This means, the user application has to use a linker file which forces the application start address to 0xC000. If a valid SP and PC value is found at address 0xC000, the user application is launched. The bootloader application is located in the flash memory of the MKW24D512 SiP, from address 0x0000 to 0xBFFF, so the user application should not put any code in this memory region. Avoid using .SREC or .bin files having program bytes or fill patterns in the bootloader section. Attached files: USB_KW24D512_MSD_Bootloader.bin – bootloader binary file for USB-KW24D512; Pflash_512KB_0xC000.icf – IAR linker file for user application development; 802.15.4SnifferOnUSB.bin – user application demo binary file for KW24D512-USB. Be aware that the file ‘802.15.4SnifferOnUSB.srec’ is linked according to the above memory restrictions and is working only with the bootloader presented in this document.
View full article
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
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
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, u sing 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
Thread is a secure, wireless, simplified IPv6-based mesh networking protocol developed by industry leading technology companies, including Freescale, for connecting devices to each other, to the internet and to the cloud. Before starting a Thread Network implementation, users should be familiar with some concepts and how they are related to Thread protocol. IPv6 Addressing Devices in the Thread stack support IPv6 addressing IPv6 addresses are 128-bit identifiers (IPv4 is only 32-bit) for interfaces and sets of interfaces.  Thread supports the following types of addresses: Unicast:  An identifier for a single interface.  A packet sent to a unicast address is delivered to the interface identified by that address. Multicast : An identifier for a set of interfaces (typically belonging to different nodes).  A packet sent to a multicast address is delivered to all interfaces identified by that address. NOTES There are no broadcast addresses in IPv6, their function being superseded by multicast addresses. Each device joining the Thread Network is also assigned a 16-bit short address as specified in IEEE 802.15.4. 6LoWPAN All Thread devices use 6LoWPAN 6LoWPAN stands for “IPv6 over Low Power Wireless Personal Networks”. 6LoWPAN is a set of standards defined by the Internet Engineering Task Force (IETF), which enables the efficient use of IPv6 over low-power, low-rate wireless networks on simple embedded devices through an adaptation layer and the optimization of related protocols. Its main goal is to send/receive IPv6 packets over 802.15.4 links. Next figure compares IP and 6LoWPAN protocol stacks: The following concepts would explain the transport layer. ICMP Thread devices support the ICMPv6 (Internet Control Message Protocol version 6) protocol and ICMPv6 error messages, as well as the echo request and echo reply messages. The Internet Control Message Protocol (ICMP) is an error reporting and diagnostic utility and is considered a required part of any IP implementation. ICMPs are used by routers, intermediary devices, or hosts to communicate updates or error information to other routers, intermediary devices, or hosts. For instance, ICMPv6 is used by IPv6 nodes to report errors encountered in processing packets, and to perform other internet-layer functions, such as diagnostics. ICMP differs from transport protocols such a s TCP and UDP in that it is not typically used to exchange data between systems, nor is it regularly employed by end-user network applications.  The ICMPv6 messages have the following general format: The type field indicates the type of the message.  Its value determines the format of the remaining data. The code field depends on the message type.  It is used to create an additional level of message granularity. The checksum field is used to detect data corruption in the ICMPv6 message and parts of the IPv6 header. ICMPv6 messages are grouped into two classes: error messages and informational messages.  Error messages are identified as such by a zero in the high-order bit of their message Type field values.  Thus,   error messages have message types from 0 to 127; informational messages have message types from 128 to 255. UDP The Thread stack supports UDP for messaging between devices. This User Datagram Protocol  (UDP)  is defined  to  make available  a datagram   mode of  packet-switched   computer communication  in  the environment  of an  interconnected  set  of  computer  networks, assuming that the Internet  Protocol (IP) is used as the underlying protocol. With UDP, applications can send data messages to other hosts on an IP network without prior communications to set up special transmission channels or data paths. UDP is suitable for purposes where error checking and correction is either not necessary or is performed in the application, avoiding the overhead of such processing at the network interface level. The UDP format is as follows: Source Port is an optional field, when meaningful, it indicates the port of the sending  process,  and may be assumed  to be the port  to which a reply should be addressed  in the absence of any other information.  If not used, a value of zero is inserted. Destination Port has a meaning within the context of a particular internet destination address. Length is the length in octets of this user datagram including this header and the data.   (This means the minimum value of the length is eight.) Checksum is the 16-bit one's complement of the one's complement sum of a pseudo header of information from the IP header, the UDP header, and the data, padded  with zero octets at the end (if  necessary)  to  make  a multiple of two octets. References White papers available at http://threadgroup.org/ “6LoWPAN: The Wireless Embedded Internet” by Zach Shelby and Carsten Bromann RFC 4291, RFC 4944, RFC 4443 and RFC 768 from https://www.ietf.org
View full article
This patch fixes some minor issues with the Connectivity Software v1.0.2 when working with the Kinetis BLE Toolbox application for smartphones. Following issues are fixed. BLE OTAP Application: Fixes application failing to download the new image when the previous image upload has been interrupted due a disconnection. BLE Wireless UART: Fixes MTU exchange issue causing some characters not bein shown in the smartphone application in iOS and Android. Hybrid BLE + Thread console: Fixes MTU exchange issue causing some characters not bein shown in the smartphone application console in iOS and Android. Make sure the Connectivity Software version 1.0.2 is installed in your computer before proceeding to install this application.
View full article