Intermediate
30 min

Achieve precise motion tracking and orientation data with BHI260, BMM150 and STM32G071RB

Spatial awareness and 3D modeling

Smart Sens Click with Nucleo 64 with STM32G071RB MCU

Published Oct 08, 2024

Click board™

Smart Sens Click

Dev. board

Nucleo 64 with STM32G071RB MCU

Compiler

NECTO Studio

MCU

STM32G071RB

With this smart system, developers can create immersive virtual and augmented reality experiences, enhancing interactivity and realism

A

A

Hardware Overview

How does it work?

Smart Sens Click is based on the BHI260 and BMM150, a programmable smart sensor combining an accelerometer, gyroscope, and fusion software alongside a standalone geometric sensor from Bosch Sensortec. The BHI260 is based on the 32-bit microcontroller (Fuser2) and is mainly intended as a coprocessor offloading the main CPU from any sensor data processing-related tasks, such as data from BMM150. It integrates the Inertial Measurement Unit (6DoF IMU) and Event-Driven Software Framework, making the BHI260 a complete sensor subsystem and computing platform for always-on sensor data processing algorithms at the lowest power consumption. The BMM150 is a geomagnetic sensor that allows magnetic field measurements in three perpendicular axes. An application-specific circuit (ASIC) converts the output of the geomagnetic sensor to digital results, which are then sent to the BHI260 for signal processing over the industry-standard digital I2C interface. The BMM150 can communicate with the BHI260 in two ways: by choosing the main or auxiliary I2C master interface. The selection can be made by positioning SMD jumpers labeled BUS SEL to an appropriate position, AUX or M2I. Note that all

the jumpers' positions must be on the same side, or the Click board™ may become unresponsive. Four magnetometer-based interrupt engines are integrated into the BMM150: Low-Threshold, High-Threshold, Overflow, mapped to the INT pin of the BMM150, and Data Ready, mapped to the DRY pin of BMM150. By positioning SMD jumpers labeled as INT SEL to an appropriate position (INT or DRY), the user chooses which interrupt will be forwarded to BHI260 and with which BHI260 will perform data processing by BMM150. Smart Sens Click allows the use of both I2C and SPI interfaces to communicate with MCU. The selection can be made by positioning SMD jumpers labeled as COMM SEL in an appropriate position. Note that all the jumpers' positions must be on the same side, or the Click board™ may become unresponsive. While the I2C interface is selected, the BHI260 allows choosing the least significant bit (LSB) of its I2C slave address using the SMD jumper labeled ADDR SEL. In addition to interface pins, this Click board™ also uses a Reset pin, RST pin on the mikroBUS™ socket, and INT pin on the mikroBUS™ socket, which indicates the data transfer request from the BHI260 to the MCU. Since the BHI260 and BMM150 for operation

require a 1.8V logic voltage level to work correctly, a small regulating LDO, the SPX3819, provides a 1.8V out of mikroBUS™ power rails. That's why voltage-level translators are also featured, the TXB0106 and PCA9306. The interface bus lines are routed to the dual bidirectional voltage-level translators, allowing this Click board™ to work properly with both 3.3V and 5V MCUs. In addition, the onboard BOOT switch is used to select whether the host interface shall be used (HOST position) or whether the BHI260 shall attempt to boot from an onboard QSPI Flash memory, the W25Q32JW, and run in a Standalone operation mode (QSPI position). Besides, at the top of the Smart Sens Click, an additional unpopulated header is marked as cJTAG, which users can use for debugging purposes, available through the JTAG interface pins (TCK and TMS). This Click board™ can operate with either 3.3V or 5V logic voltage levels selected via the VCC SEL jumper. This way, both 3.3V and 5V capable MCUs can use the communication lines properly. Also, this Click board™ comes equipped with a library containing easy-to-use functions and an example code that can be used as a reference for further development.

Smart Sens Click hardware overview image

Features overview

Development board

Nucleo-64 with STM32G071RB MCU offers a cost-effective and adaptable platform for developers to explore new ideas and prototype their designs. This board harnesses the versatility of the STM32 microcontroller, enabling users to select the optimal balance of performance and power consumption for their projects. It accommodates the STM32 microcontroller in the LQFP64 package and includes essential components such as a user LED, which doubles as an ARDUINO® signal, alongside user and reset push-buttons, and a 32.768kHz crystal oscillator for precise timing operations. Designed with expansion and flexibility in mind, the Nucleo-64 board features an ARDUINO® Uno V3 expansion connector and ST morpho extension pin

headers, granting complete access to the STM32's I/Os for comprehensive project integration. Power supply options are adaptable, supporting ST-LINK USB VBUS or external power sources, ensuring adaptability in various development environments. The board also has an on-board ST-LINK debugger/programmer with USB re-enumeration capability, simplifying the programming and debugging process. Moreover, the board is designed to simplify advanced development with its external SMPS for efficient Vcore logic supply, support for USB Device full speed or USB SNK/UFP full speed, and built-in cryptographic features, enhancing both the power efficiency and security of projects. Additional connectivity is

provided through dedicated connectors for external SMPS experimentation, a USB connector for the ST-LINK, and a MIPI® debug connector, expanding the possibilities for hardware interfacing and experimentation. Developers will find extensive support through comprehensive free software libraries and examples, courtesy of the STM32Cube MCU Package. This, combined with compatibility with a wide array of Integrated Development Environments (IDEs), including IAR Embedded Workbench®, MDK-ARM, and STM32CubeIDE, ensures a smooth and efficient development experience, allowing users to fully leverage the capabilities of the Nucleo-64 board in their projects.

Nucleo 64 with STM32G071RB MCU double side image

Microcontroller Overview

MCU Card / MCU

default

Architecture

ARM Cortex-M0

MCU Memory (KB)

128

Silicon Vendor

STMicroelectronics

Pin count

64

RAM (Bytes)

36864

You complete me!

Accessories

Click Shield for Nucleo-64 comes equipped with two proprietary mikroBUS™ sockets, allowing all the Click board™ devices to be interfaced with the STM32 Nucleo-64 board with no effort. This way, Mikroe allows its users to add any functionality from our ever-growing range of Click boards™, such as WiFi, GSM, GPS, Bluetooth, ZigBee, environmental sensors, LEDs, speech recognition, motor control, movement sensors, and many more. More than 1537 Click boards™, which can be stacked and integrated, are at your disposal. The STM32 Nucleo-64 boards are based on the microcontrollers in 64-pin packages, a 32-bit MCU with an ARM Cortex M4 processor operating at 84MHz, 512Kb Flash, and 96KB SRAM, divided into two regions where the top section represents the ST-Link/V2 debugger and programmer while the bottom section of the board is an actual development board. These boards are controlled and powered conveniently through a USB connection to program and efficiently debug the Nucleo-64 board out of the box, with an additional USB cable connected to the USB mini port on the board. Most of the STM32 microcontroller pins are brought to the IO pins on the left and right edge of the board, which are then connected to two existing mikroBUS™ sockets. This Click Shield also has several switches that perform functions such as selecting the logic levels of analog signals on mikroBUS™ sockets and selecting logic voltage levels of the mikroBUS™ sockets themselves. Besides, the user is offered the possibility of using any Click board™ with the help of existing bidirectional level-shifting voltage translators, regardless of whether the Click board™ operates at a 3.3V or 5V logic voltage level. Once you connect the STM32 Nucleo-64 board with our Click Shield for Nucleo-64, you can access hundreds of Click boards™, working with 3.3V or 5V logic voltage levels.

Click Shield for Nucleo-64 accessories 1 image

Used MCU Pins

mikroBUS™ mapper

NC
NC
AN
Reset
PC12
RST
SPI Chip Select
PB12
CS
SPI Clock
PB3
SCK
SPI Data OUT
PB4
MISO
SPI Data IN
PB5
MOSI
Power Supply
3.3V
3.3V
Ground
GND
GND
NC
NC
PWM
Interrupt
PC14
INT
NC
NC
TX
NC
NC
RX
I2C Clock
PB8
SCL
I2C Data
PB9
SDA
Power Supply
5V
5V
Ground
GND
GND
1

Take a closer look

Click board™ Schematic

Smart Sens Click Schematic schematic

Step by step

Project assembly

Click Shield for Nucleo-64 front image hardware assembly

Start by selecting your development board and Click board™. Begin with the Nucleo 64 with STM32G071RB MCU as your development board.

Click Shield for Nucleo-64 front image hardware assembly
Nucleo 64 with STM32F401RE MCU front image hardware assembly
EEPROM 13 Click front image hardware assembly
Prog-cut hardware assembly
Nucleo-64 with STM32XXX MCU MB 1 Mini B Conn - upright/background hardware assembly
Necto image step 2 hardware assembly
Necto image step 3 hardware assembly
Necto image step 4 hardware assembly
Necto image step 5 hardware assembly
Necto image step 6 hardware assembly
Clicker 4 for STM32F4 HA MCU Step hardware assembly
Necto No Display image step 8 hardware assembly
Necto image step 9 hardware assembly
Necto image step 10 hardware assembly
Debug Image Necto Step hardware assembly

Track your results in real time

Application Output

1. Application Output - In Debug mode, the 'Application Output' window enables real-time data monitoring, offering direct insight into execution results. Ensure proper data display by configuring the environment correctly using the provided tutorial.

2. UART Terminal - Use the UART Terminal to monitor data transmission via a USB to UART converter, allowing direct communication between the Click board™ and your development system. Configure the baud rate and other serial settings according to your project's requirements to ensure proper functionality. For step-by-step setup instructions, refer to the provided tutorial.

3. Plot Output - The Plot feature offers a powerful way to visualize real-time sensor data, enabling trend analysis, debugging, and comparison of multiple data points. To set it up correctly, follow the provided tutorial, which includes a step-by-step example of using the Plot feature to display Click board™ readings. To use the Plot feature in your code, use the function: plot(*insert_graph_name*, variable_name);. This is a general format, and it is up to the user to replace 'insert_graph_name' with the actual graph name and 'variable_name' with the parameter to be displayed.

Software Support

Library Description

This library contains API for Smart Sens Click driver.

Key functions:

  • smartsens_cmd_write - Send command

  • smartsens_get_parameter - Get command parameters resposne

  • smartsens_power_on_device - Power on device boot/upload firmware to device

Open Source

Code example

The complete application code and a ready-to-use project are available through the NECTO Studio Package Manager for direct installation in the NECTO Studio. The application code can also be found on the MIKROE GitHub account.

/*!
 * @file main.c
 * @brief Smart Sens Click example
 *
 * # Description
 * This example showcases the ability of the Smart Sens click board.
 * It has multiple examples that you can easily select with the 
 * defines at the top of the main. There are 5 examples: Euler, Quaternion, 
 * and Vector (Accelerometer, Gyroscope, Magnetometer).
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * Initialization of communication modules (SPI/I2C) and additional 
 * pins(int_pin, rst). After that going through reset sequence and checking
 * device and product IDs, interrupt mask, and host control is set to 0, so
 * every interrupt enabled. If boot status is OK boot sequence is initiated,
 * depending on the defines from the library header it will use RAM or Flash type
 * of the boot. If RAM is selected firmware image first needs to be uploaded to RAM
 * and then it will be booted. If Flash example is selected it will try to boot
 * firmware first if it fails it will then write firmware image to flash and then
 * try to boot it again. When firmware boot is finished Kernel version and Feature
 * registers will be read to check if the firmware is loaded. Then all the callback function
 * will be registered(meta event callback and whatever type of example parser you set),
 * and driver will update the list of virtual sensors present, and finally will configure
 * virtual sensor that will be used in the selected example.
 *
 * ## Application Task
 * Wait for an interrupt to occur, then read wake-up, non-weak-up, and status FIFO.
 * Parse received data and run the callback parsers to show data on the USB UART.
 *
 * @note
 * Select one of the examples with macros at the top of the main file. Euler example is selected by default. 
 * You can choose one of 3 type of parsers: Euler, Quaternion, Vector. If Vector example is selected 
 * you choose one of the 3 sensors to show X, Y, and Z values: Accelerometer, Gyroscope, or Magnetometer.
 *
 * @author MikroE Team
 *
 */

#include "board.h"
#include "log.h"
#include "smartsens.h"

/**
 * @brief Example parser selector.
 * @details Macros for selecting example and its parser.
 */
#define EULER                   1
#define QUATERNION              0
#define VECTOR                  0

/**
 * @brief Vector sensor selector.
 * @details Macros for selecting vector's sensor.
 */
#define ACCELEROMETER           1
#define GYROSCOPE               0
#define MAGNETOMETER            0

#define WORK_BUFFER_SIZE        2048
uint8_t work_buffer[ WORK_BUFFER_SIZE ] = { 0 };
static smartsens_t smartsens;
static log_t logger;
uint8_t accuracy; /* Accuracy is reported as a meta event. It is being printed alongside the data */

#if EULER
/**
 * @brief Euler data.
 * @details Struct for euler data of the Smart Sens Click example.
 */
struct smartsens_data_orientation
{
    int16_t heading;
    int16_t pitch;
    int16_t roll;
};

/**
 * @brief Euler callback parsing function.
 * @details Callback function to parse euler data.
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 * @return Nothing
 */
static void parse_euler ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );
#elif QUATERNION
/**
 * @brief Quaternion data.
 * @details Struct for quaternion data of the Smart Sens Click example.
 */
struct smartsens_data_quaternion
{
    int16_t x;
    int16_t y;
    int16_t z;
    int16_t w;
    uint16_t accuracy;
};

/**
 * @brief Parse FIFO frame data into quaternion
 * @details Function to parse FIFO frame data into quaternion
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 */
static void parse_quaternion ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );
#elif VECTOR
/**
 * @brief Vector data.
 * @details Struct for vector data of the Smart Sens Click example.
 */
struct smartsens_data_xyz
{
    int16_t x;
    int16_t y;
    int16_t z;
};

/**
 * @brief Parse reference.
 * @details Struct for parse reference data of the Smart Sens Click example.
 */
struct parse_ref
{
    struct
    {
        uint8_t accuracy;
        float scaling_factor;
    }
    sensor[ SMARTSENS_SENSOR_ID_MAX ];
    uint8_t *verbose;
};
struct parse_ref parse_table;

/**
 * @brief Vector callback parsing function.
 * @details Callback function to parse vector data.
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 * @return Nothing
 */
static void parse_vector_s16 ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );
#else
    #error NO_EXAMPLE_DEFINED
#endif

/**
 * @brief Meta event callback parsing function.
 * @details Callback function to parse meta event data.
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 * @return Nothing
 */
static void parse_meta_event ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );

/**
 * @brief Get name of the virtual sensor by ID.
 * @details Function return name of the virutal sensor by its ID.
 * @param[in] sensor_id       : Virtual sensor ID.
 * @return Virtual sensor name.
 */
static char* get_sensor_name ( uint8_t sensor_id );

void application_init ( void )
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    smartsens_cfg_t smartsens_cfg;  /**< Click config object. */

    /** 
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX 
     * are defined as HAL_PIN_NC, you will 
     * need to define them manually for log to work. 
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );

    // Click initialization.
    smartsens_cfg_setup( &smartsens_cfg );
    SMARTSENS_MAP_MIKROBUS( smartsens_cfg, MIKROBUS_1 );
    err_t init_flag = smartsens_init( &smartsens, &smartsens_cfg );
    if ( ( I2C_MASTER_ERROR == init_flag ) || ( SPI_MASTER_ERROR == init_flag ) )
    {
        log_error( &logger, " Communication init." );
        for ( ; ; );
    }
    /* It can take a few seconds to configure and boot device */
    log_info( &logger, " Configuring device..." );
    if ( SMARTSENS_ERROR == smartsens_default_cfg ( &smartsens ) )
    {
        log_error( &logger, " Default configuration." );
        for ( ; ; );
    }

    log_info( &logger, " Setting callbacks..." );
    /* Set callbacks */
    if ( smartsens_register_fifo_parse_callback( &smartsens, SMARTSENS_SYS_ID_META_EVENT,
                                                  parse_meta_event, &accuracy ) )
    {
        log_error( &logger, " FIFO sys meta event." );
        for ( ; ; );
    }
    if ( smartsens_register_fifo_parse_callback( &smartsens, SMARTSENS_SYS_ID_META_EVENT_WU,
                                                  parse_meta_event, &accuracy ) )
    {
        log_error( &logger, " FIFO sys meta event wu." );
        for ( ; ; );
    }
    uint8_t sensor_id;
    smartsens_fifo_parse_callback_t callback;
    void *callback_ref;
#if EULER
    sensor_id = SMARTSENS_SENSOR_ID_ORI;
    callback = parse_euler;
    callback_ref = &accuracy;
#elif QUATERNION
    sensor_id = SMARTSENS_SENSOR_ID_RV;
    callback = parse_quaternion;
    callback_ref = NULL;
#elif VECTOR
    #if ACCELEROMETER
        parse_table.sensor[ SMARTSENS_SENSOR_ID_ACC ].scaling_factor = 1.0f / 4096.0f;
        sensor_id = SMARTSENS_SENSOR_ID_ACC;
    #elif GYROSCOPE
        parse_table.sensor[ SMARTSENS_SENSOR_ID_GYRO ].scaling_factor = 1.0f;
        sensor_id = SMARTSENS_SENSOR_ID_GYRO;
    #elif MAGNETOMETER
        parse_table.sensor[ SMARTSENS_SENSOR_ID_MAG ].scaling_factor = 1.0f;
        sensor_id = SMARTSENS_SENSOR_ID_MAG;
    #else
        #error NO_VECTOR_EXAMPLE_DEFINED
    #endif
    callback = parse_vector_s16;
    callback_ref = &parse_table;
#else
    #error NO_EXAMPLE_DEFINED
#endif
    if ( smartsens_register_fifo_parse_callback( &smartsens, sensor_id, callback, callback_ref ) )
    {
        log_error( &logger, " FIFO sensor id." );
        for ( ; ; );
    }
    /* Go through fifo process */
    if ( smartsens_get_and_process_fifo( &smartsens, work_buffer, WORK_BUFFER_SIZE ) )
    {
        log_error( &logger, " FIFO get and process." );
        for ( ; ; );
    }
    /* Update virtual sensor list in context object */
    if ( smartsens_update_virtual_sensor_list( &smartsens ) )
    {
        log_error( &logger, " Update virtual sensor list." );
        for ( ; ; );
    }
    /* Set virtual sensor configuration */
    float sample_rate = 10.0; /* Read out data at 10Hz */
    uint32_t report_latency_ms = 0; /* Report immediately */
    if ( smartsens_set_virt_sensor_cfg( &smartsens, sensor_id, sample_rate, report_latency_ms ) )
    {
        log_error( &logger, " Set virtual sensor configuration." );
        for ( ; ; );
    }
    
    log_info( &logger, " Application Task " );
}

void application_task ( void )
{
    /* Check interrupt and get and process fifo buffer */
    if ( smartsens_get_interrupt( &smartsens ) )
    {
        /* Data from the FIFO is read and the relevant callbacks if registered are called */
        if ( smartsens_get_and_process_fifo( &smartsens, work_buffer, WORK_BUFFER_SIZE ) )
        {
            log_error( &logger, " Get and process fifo." );
            for ( ; ; );
        }
    }
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif
    
    application_init( );
    
    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

#if EULER
static void parse_euler ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    struct smartsens_data_orientation data_val;
    uint8_t *accuracy = ( uint8_t* ) callback_ref;
    if ( callback_info->data_size != 7 ) /* Check for a valid payload size. Includes sensor ID */
    {
        return;
    }
    data_val.heading = SMARTSENS_LE2S16( callback_info->data_ptr );
    data_val.pitch = SMARTSENS_LE2S16( callback_info->data_ptr + 2 );
    data_val.roll = SMARTSENS_LE2S16( callback_info->data_ptr + 4 );
    if ( accuracy )
    {
        log_printf( &logger, "SID: %s; H: %.3f, P: %.3f, R: %.3f; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( float ) ( data_val.heading * 360.0f / 32768.0f ),
                    ( float ) ( data_val.pitch * 360.0f / 32768.0f ),
                    ( float ) ( data_val.roll * 360.0f / 32768.0f ),
                    ( uint16_t ) ( *accuracy ),
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    }
    else
    {
        log_printf( &logger, "SID: %s; H: %.3f, P: %.3f, R: %.3f; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( float ) ( data_val.heading * 360.0f / 32768.0f ),
                    ( float ) ( data_val.pitch * 360.0f / 32768.0f ),
                    ( float ) ( data_val.roll * 360.0f / 32768.0f ),
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    }
}
#elif QUATERNION
static void parse_quaternion ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    struct smartsens_data_quaternion data_val;
    if ( callback_info->data_size != 11 ) /* Check for a valid payload size. Includes sensor ID */
    {
        return;
    }
    data_val.x = SMARTSENS_LE2S16( callback_info->data_ptr );
    data_val.y = SMARTSENS_LE2S16( callback_info->data_ptr + 2 );
    data_val.z = SMARTSENS_LE2S16( callback_info->data_ptr + 4 );
    data_val.w = SMARTSENS_LE2S16( callback_info->data_ptr + 6 );
    data_val.accuracy = SMARTSENS_LE2U16( callback_info->data_ptr + 8 );
    log_printf( &logger, "SID: %s; X: %.3f, Y: %.3f, Z: %.3f, W: %.3f; acc: %.2f; Time: %lus\r\n",
                get_sensor_name( callback_info->sensor_id ),
                ( float ) ( data_val.x / 16384.0f ),
                ( float ) ( data_val.y / 16384.0f ),
                ( float ) ( data_val.z / 16384.0f ),
                ( float ) ( data_val.w / 16384.0f ),
                ( float ) ( ( ( data_val.accuracy * 180.0f ) / 16384.0f ) / 3.141592653589793f ),
                SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
}
#elif VECTOR
static void parse_vector_s16 ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    struct smartsens_data_xyz data_value;
    if ( callback_ref )
    {
        struct parse_ref *parse_table = ( struct parse_ref* ) callback_ref;
        float scaling_factor = parse_table->sensor[ callback_info->sensor_id ].scaling_factor;
        data_value.x = SMARTSENS_LE2S16( callback_info->data_ptr );
        data_value.y = SMARTSENS_LE2S16( callback_info->data_ptr + 2 );
        data_value.z = SMARTSENS_LE2S16( callback_info->data_ptr + 4 );
    #if ACCELEROMETER
        log_printf( &logger, "SID: %s; X: %.3f, Y: %.3f, Z: %.3f; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( float ) ( data_value.x * scaling_factor ),
                    ( float ) ( data_value.y * scaling_factor ),
                    ( float ) ( data_value.z * scaling_factor ),
                    ( uint16_t ) parse_table->sensor[ callback_info->sensor_id ].accuracy, 
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    #elif GYROSCOPE
        log_printf( &logger, "SID: %s; X: %d, Y: %d, Z: %d; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( int16_t ) ( data_value.x * scaling_factor ),
                    ( int16_t ) ( data_value.y * scaling_factor ),
                    ( int16_t ) ( data_value.z * scaling_factor ),
                    ( uint16_t ) parse_table->sensor[ callback_info->sensor_id ].accuracy, 
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    #elif MAGNETOMETER
        log_printf( &logger, "SID: %s; X: %d, Y: %d, Z: %d; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( int16_t ) ( data_value.x * scaling_factor ),
                    ( int16_t ) ( data_value.y * scaling_factor ),
                    ( int16_t ) ( data_value.z * scaling_factor ),
                    ( uint16_t ) parse_table->sensor[ callback_info->sensor_id ].accuracy, 
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    #else
        #error NO_VECTOR_EXAMPLE_DEFINED
    #endif
    }
    else
    {
        log_error( &logger, "Null reference" );
    }
}
#else
    #error NO_EXAMPLE_DEFINED
#endif

static void parse_meta_event ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    uint8_t meta_event_type = callback_info->data_ptr[ 0 ];
    uint8_t byte1 = callback_info->data_ptr[ 1 ];
    uint8_t byte2 = callback_info->data_ptr[ 2 ];
    uint8_t *accuracy = ( uint8_t* ) callback_ref;
    char *event_text;

    if ( SMARTSENS_SYS_ID_META_EVENT == callback_info->sensor_id )
    {
        event_text = "[META EVENT]";
    }
    else if ( SMARTSENS_SYS_ID_META_EVENT_WU == callback_info->sensor_id )
    {
        event_text = "[META EVENT WAKE UP]";
    }
    else
    {
        return;
    }

    switch ( meta_event_type )
    {
        case SMARTSENS_META_EVENT_FLUSH_COMPLETE:
        {
            log_printf( &logger, "%s Flush complete for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_SAMPLE_RATE_CHANGED:
        {
            log_printf( &logger, "%s Sample rate changed for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_POWER_MODE_CHANGED:
        {
            log_printf( &logger, "%s Power mode changed for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_ALGORITHM_EVENTS:
        {
            log_printf( &logger, "%s Algorithm event\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_SENSOR_STATUS:
        {
            log_printf( &logger, "%s Accuracy for sensor id %s changed to %s\r\n", 
                        event_text, get_sensor_name( byte1 ), get_sensor_name( byte2 ) );
            if ( accuracy )
            {
                *accuracy = byte2;
            }
            break;
        }
        case SMARTSENS_META_EVENT_BSX_DO_STEPS_MAIN:
        {
            log_printf( &logger, "%s BSX event (do steps main)\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_BSX_DO_STEPS_CALIB:
        {
            log_printf( &logger, "%s BSX event (do steps calib)\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_BSX_GET_OUTPUT_SIGNAL:
        {
            log_printf( &logger, "%s BSX event (get output signal)\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_SENSOR_ERROR:
        {
            log_printf( &logger, "%s Sensor id %u reported error 0x%02X\r\n", 
                        event_text, byte1, byte2 );
            break;
        }
        case SMARTSENS_META_EVENT_FIFO_OVERFLOW:
        {
            log_printf( &logger, "%s FIFO overflow\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_DYNAMIC_RANGE_CHANGED:
        {
            log_printf( &logger, "%s Dynamic range changed for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_FIFO_WATERMARK:
        {
            log_printf( &logger, "%s FIFO watermark reached\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_INITIALIZED:
        {
            log_printf( &logger, "%s Firmware initialized. Firmware version %u\r\n", 
                        event_text, ( ( uint16_t )byte2 << 8 ) | byte1 );
            break;
        }
        case SMARTSENS_META_TRANSFER_CAUSE:
        {
            log_printf( &logger, "%s Transfer cause for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_SENSOR_FRAMEWORK:
        {
            log_printf( &logger, "%s Sensor framework event for sensor id %s\r\n", 
                        event_text, byte1 );
            break;
        }
        case SMARTSENS_META_EVENT_RESET:
        {
            log_printf( &logger, "%s Reset event\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_SPACER:
        {
            break;
        }
        default:
        {
            log_printf( &logger, "%s Unknown meta event with id: %u\r\n", 
                        event_text, meta_event_type );
            break;
        }
    }
}

static char* get_sensor_name ( uint8_t sensor_id )
{
    char *ret;

    switch ( sensor_id )
    {
        case SMARTSENS_SENSOR_ID_ACC_PASS:
        {
            ret = "Accelerometer passthrough";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_RAW:
        {
            ret = "Accelerometer uncalibrated";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC:
            ret = "Accelerometer corrected";
            break;
        case SMARTSENS_SENSOR_ID_ACC_BIAS:
        {
            ret = "Accelerometer offset";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_WU:
        {
            ret = "Accelerometer corrected wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_RAW_WU:
        {
            ret = "Accelerometer uncalibrated wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_PASS:
        {
            ret = "Gyroscope passthrough";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_RAW:
        {
            ret = "Gyroscope uncalibrated";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO:
        {
            ret = "Gyroscope corrected";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_BIAS:
        {
            ret = "Gyroscope offset";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_WU:
        {
            ret = "Gyroscope wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_RAW_WU:
        {
            ret = "Gyroscope uncalibrated wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_PASS:
        {
            ret = "Magnetometer passthrough";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_RAW:
        {
            ret = "Magnetometer uncalibrated";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG:
        {
            ret = "Magnetometer corrected";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_BIAS:
        {
            ret = "Magnetometer offset";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_WU:
        {
            ret = "Magnetometer wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_RAW_WU:
        {
            ret = "Magnetometer uncalibrated wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GRA:
        {
            ret = "Gravity vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_GRA_WU:
        {
            ret = "Gravity vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_LACC:
        {
            ret = "Linear acceleration";
            break;
        }
        case SMARTSENS_SENSOR_ID_LACC_WU:
        {
            ret = "Linear acceleration wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_RV:
        {
            ret = "Rotation vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_RV_WU:
        {
            ret = "Rotation vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAMERV:
        {
            ret = "Game rotation vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAMERV_WU:
        {
            ret = "Game rotation vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GEORV:
        {
            ret = "Geo-magnetic rotation vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_GEORV_WU:
        {
            ret = "Geo-magnetic rotation vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_ORI:
        {
            ret = "Orientation";
            break;
        }
        case SMARTSENS_SENSOR_ID_ORI_WU:
        {
            ret = "Orientation wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_TILT_DETECTOR:
        {
            ret = "Tilt detector";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD:
        {
            ret = "Step detector";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC:
        {
            ret = "Step counter";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC_WU:
        {
            ret = "Step counter wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_SIG:
        {
            ret = "Significant motion";
            break;
        }
        case SMARTSENS_SENSOR_ID_WAKE_GESTURE:
        {
            ret = "Wake gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_GLANCE_GESTURE:
        {
            ret = "Glance gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_PICKUP_GESTURE:
        {
            ret = "Pickup gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_AR:
        {
            ret = "Activity recognition";
            break;
        }
        case SMARTSENS_SENSOR_ID_WRIST_TILT_GESTURE:
        {
            ret = "Wrist tilt gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_DEVICE_ORI:
        {
            ret = "Device orientation";
            break;
        }
        case SMARTSENS_SENSOR_ID_DEVICE_ORI_WU:
        {
            ret = "Device orientation wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STATIONARY_DET:
        {
            ret = "Stationary detect";
            break;
        }
        case SMARTSENS_SENSOR_ID_MOTION_DET:
        {
            ret = "Motion detect";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_BIAS_WU:
        {
            ret = "Accelerometer offset wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_BIAS_WU:
        {
            ret = "Gyroscope offset wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_BIAS_WU:
        {
            ret = "Magnetometer offset wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD_WU:
        {
            ret = "Step detector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_TEMP:
        {
            ret = "Temperature";
            break;
        }
        case SMARTSENS_SENSOR_ID_BARO:
        {
            ret = "Barometer";
            break;
        }
        case SMARTSENS_SENSOR_ID_HUM:
        {
            ret = "Humidity";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAS:
        {
            ret = "Gas";
            break;
        }
        case SMARTSENS_SENSOR_ID_TEMP_WU:
        {
            ret = "Temperature wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_BARO_WU:
        {
            ret = "Barometer wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_HUM_WU:
        {
            ret = "Humidity wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAS_WU:
        {
            ret = "Gas wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC_HW:
        {
            ret = "Hardware Step counter";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD_HW:
        {
            ret = "Hardware Step detector";
            break;
        }
        case SMARTSENS_SENSOR_ID_SIG_HW:
        {
            ret = "Hardware Significant motion";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC_HW_WU:
        {
            ret = "Hardware Step counter wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD_HW_WU:
        {
            ret = "Hardware Step detector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_SIG_HW_WU:
        {
            ret = "Hardware Significant motion wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_ANY_MOTION:
        {
            ret = "Any motion";
            break;
        }
        case SMARTSENS_SENSOR_ID_ANY_MOTION_WU:
        {
            ret = "Any motion wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_EXCAMERA:
        {
            ret = "External camera trigger";
            break;
        }
        case SMARTSENS_SENSOR_ID_GPS:
        {
            ret = "GPS";
            break;
        }
        case SMARTSENS_SENSOR_ID_LIGHT:
        {
            ret = "Light";
            break;
        }
        case SMARTSENS_SENSOR_ID_PROX:
        {
            ret = "Proximity";
            break;
        }
        case SMARTSENS_SENSOR_ID_LIGHT_WU:
        {
            ret = "Light wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_PROX_WU:
        {
            ret = "Proximity wake up";
            break;
        }
        default:
        {
            if ( ( sensor_id >= SMARTSENS_SENSOR_ID_CUSTOM_START ) && ( sensor_id <= SMARTSENS_SENSOR_ID_CUSTOM_END ) )
            {
                ret = "Custom sensor ID ";
            }
            else
            {
                ret = "Undefined sensor ID ";
            }
        }
    }

    return ret;
}

// ------------------------------------------------------------------------ END
/*!
 * @file main.c
 * @brief Smart Sens Click example
 *
 * # Description
 * This example showcases the ability of the Smart Sens click board.
 * It has multiple examples that you can easily select with the 
 * defines at the top of the main. There are 5 examples: Euler, Quaternion, 
 * and Vector (Accelerometer, Gyroscope, Magnetometer).
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * Initialization of communication modules (SPI/I2C) and additional 
 * pins(int_pin, rst). After that going through reset sequence and checking
 * device and product IDs, interrupt mask, and host control is set to 0, so
 * every interrupt enabled. If boot status is OK boot sequence is initiated,
 * depending on the defines from the library header it will use RAM or Flash type
 * of the boot. If RAM is selected firmware image first needs to be uploaded to RAM
 * and then it will be booted. If Flash example is selected it will try to boot
 * firmware first if it fails it will then write firmware image to flash and then
 * try to boot it again. When firmware boot is finished Kernel version and Feature
 * registers will be read to check if the firmware is loaded. Then all the callback function
 * will be registered(meta event callback and whatever type of example parser you set),
 * and driver will update the list of virtual sensors present, and finally will configure
 * virtual sensor that will be used in the selected example.
 *
 * ## Application Task
 * Wait for an interrupt to occur, then read wake-up, non-weak-up, and status FIFO.
 * Parse received data and run the callback parsers to show data on the USB UART.
 *
 * @note
 * Select one of the examples with macros at the top of the main file. Euler example is selected by default. 
 * You can choose one of 3 type of parsers: Euler, Quaternion, Vector. If Vector example is selected 
 * you choose one of the 3 sensors to show X, Y, and Z values: Accelerometer, Gyroscope, or Magnetometer.
 *
 * @author MikroE Team
 *
 */

#include "board.h"
#include "log.h"
#include "smartsens.h"

/**
 * @brief Example parser selector.
 * @details Macros for selecting example and its parser.
 */
#define EULER                   1
#define QUATERNION              0
#define VECTOR                  0

/**
 * @brief Vector sensor selector.
 * @details Macros for selecting vector's sensor.
 */
#define ACCELEROMETER           1
#define GYROSCOPE               0
#define MAGNETOMETER            0

#define WORK_BUFFER_SIZE        2048
uint8_t work_buffer[ WORK_BUFFER_SIZE ] = { 0 };
static smartsens_t smartsens;
static log_t logger;
uint8_t accuracy; /* Accuracy is reported as a meta event. It is being printed alongside the data */

#if EULER
/**
 * @brief Euler data.
 * @details Struct for euler data of the Smart Sens Click example.
 */
struct smartsens_data_orientation
{
    int16_t heading;
    int16_t pitch;
    int16_t roll;
};

/**
 * @brief Euler callback parsing function.
 * @details Callback function to parse euler data.
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 * @return Nothing
 */
static void parse_euler ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );
#elif QUATERNION
/**
 * @brief Quaternion data.
 * @details Struct for quaternion data of the Smart Sens Click example.
 */
struct smartsens_data_quaternion
{
    int16_t x;
    int16_t y;
    int16_t z;
    int16_t w;
    uint16_t accuracy;
};

/**
 * @brief Parse FIFO frame data into quaternion
 * @details Function to parse FIFO frame data into quaternion
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 */
static void parse_quaternion ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );
#elif VECTOR
/**
 * @brief Vector data.
 * @details Struct for vector data of the Smart Sens Click example.
 */
struct smartsens_data_xyz
{
    int16_t x;
    int16_t y;
    int16_t z;
};

/**
 * @brief Parse reference.
 * @details Struct for parse reference data of the Smart Sens Click example.
 */
struct parse_ref
{
    struct
    {
        uint8_t accuracy;
        float scaling_factor;
    }
    sensor[ SMARTSENS_SENSOR_ID_MAX ];
    uint8_t *verbose;
};
struct parse_ref parse_table;

/**
 * @brief Vector callback parsing function.
 * @details Callback function to parse vector data.
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 * @return Nothing
 */
static void parse_vector_s16 ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );
#else
    #error NO_EXAMPLE_DEFINED
#endif

/**
 * @brief Meta event callback parsing function.
 * @details Callback function to parse meta event data.
 * @param[in] callback_info      : Callback data.
 * @param[in] callback_ref       : Callback reference.
 * @return Nothing
 */
static void parse_meta_event ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref );

/**
 * @brief Get name of the virtual sensor by ID.
 * @details Function return name of the virutal sensor by its ID.
 * @param[in] sensor_id       : Virtual sensor ID.
 * @return Virtual sensor name.
 */
static char* get_sensor_name ( uint8_t sensor_id );

void application_init ( void )
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    smartsens_cfg_t smartsens_cfg;  /**< Click config object. */

    /** 
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX 
     * are defined as HAL_PIN_NC, you will 
     * need to define them manually for log to work. 
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );

    // Click initialization.
    smartsens_cfg_setup( &smartsens_cfg );
    SMARTSENS_MAP_MIKROBUS( smartsens_cfg, MIKROBUS_1 );
    err_t init_flag = smartsens_init( &smartsens, &smartsens_cfg );
    if ( ( I2C_MASTER_ERROR == init_flag ) || ( SPI_MASTER_ERROR == init_flag ) )
    {
        log_error( &logger, " Communication init." );
        for ( ; ; );
    }
    /* It can take a few seconds to configure and boot device */
    log_info( &logger, " Configuring device..." );
    if ( SMARTSENS_ERROR == smartsens_default_cfg ( &smartsens ) )
    {
        log_error( &logger, " Default configuration." );
        for ( ; ; );
    }

    log_info( &logger, " Setting callbacks..." );
    /* Set callbacks */
    if ( smartsens_register_fifo_parse_callback( &smartsens, SMARTSENS_SYS_ID_META_EVENT,
                                                  parse_meta_event, &accuracy ) )
    {
        log_error( &logger, " FIFO sys meta event." );
        for ( ; ; );
    }
    if ( smartsens_register_fifo_parse_callback( &smartsens, SMARTSENS_SYS_ID_META_EVENT_WU,
                                                  parse_meta_event, &accuracy ) )
    {
        log_error( &logger, " FIFO sys meta event wu." );
        for ( ; ; );
    }
    uint8_t sensor_id;
    smartsens_fifo_parse_callback_t callback;
    void *callback_ref;
#if EULER
    sensor_id = SMARTSENS_SENSOR_ID_ORI;
    callback = parse_euler;
    callback_ref = &accuracy;
#elif QUATERNION
    sensor_id = SMARTSENS_SENSOR_ID_RV;
    callback = parse_quaternion;
    callback_ref = NULL;
#elif VECTOR
    #if ACCELEROMETER
        parse_table.sensor[ SMARTSENS_SENSOR_ID_ACC ].scaling_factor = 1.0f / 4096.0f;
        sensor_id = SMARTSENS_SENSOR_ID_ACC;
    #elif GYROSCOPE
        parse_table.sensor[ SMARTSENS_SENSOR_ID_GYRO ].scaling_factor = 1.0f;
        sensor_id = SMARTSENS_SENSOR_ID_GYRO;
    #elif MAGNETOMETER
        parse_table.sensor[ SMARTSENS_SENSOR_ID_MAG ].scaling_factor = 1.0f;
        sensor_id = SMARTSENS_SENSOR_ID_MAG;
    #else
        #error NO_VECTOR_EXAMPLE_DEFINED
    #endif
    callback = parse_vector_s16;
    callback_ref = &parse_table;
#else
    #error NO_EXAMPLE_DEFINED
#endif
    if ( smartsens_register_fifo_parse_callback( &smartsens, sensor_id, callback, callback_ref ) )
    {
        log_error( &logger, " FIFO sensor id." );
        for ( ; ; );
    }
    /* Go through fifo process */
    if ( smartsens_get_and_process_fifo( &smartsens, work_buffer, WORK_BUFFER_SIZE ) )
    {
        log_error( &logger, " FIFO get and process." );
        for ( ; ; );
    }
    /* Update virtual sensor list in context object */
    if ( smartsens_update_virtual_sensor_list( &smartsens ) )
    {
        log_error( &logger, " Update virtual sensor list." );
        for ( ; ; );
    }
    /* Set virtual sensor configuration */
    float sample_rate = 10.0; /* Read out data at 10Hz */
    uint32_t report_latency_ms = 0; /* Report immediately */
    if ( smartsens_set_virt_sensor_cfg( &smartsens, sensor_id, sample_rate, report_latency_ms ) )
    {
        log_error( &logger, " Set virtual sensor configuration." );
        for ( ; ; );
    }
    
    log_info( &logger, " Application Task " );
}

void application_task ( void )
{
    /* Check interrupt and get and process fifo buffer */
    if ( smartsens_get_interrupt( &smartsens ) )
    {
        /* Data from the FIFO is read and the relevant callbacks if registered are called */
        if ( smartsens_get_and_process_fifo( &smartsens, work_buffer, WORK_BUFFER_SIZE ) )
        {
            log_error( &logger, " Get and process fifo." );
            for ( ; ; );
        }
    }
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif
    
    application_init( );
    
    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

#if EULER
static void parse_euler ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    struct smartsens_data_orientation data_val;
    uint8_t *accuracy = ( uint8_t* ) callback_ref;
    if ( callback_info->data_size != 7 ) /* Check for a valid payload size. Includes sensor ID */
    {
        return;
    }
    data_val.heading = SMARTSENS_LE2S16( callback_info->data_ptr );
    data_val.pitch = SMARTSENS_LE2S16( callback_info->data_ptr + 2 );
    data_val.roll = SMARTSENS_LE2S16( callback_info->data_ptr + 4 );
    if ( accuracy )
    {
        log_printf( &logger, "SID: %s; H: %.3f, P: %.3f, R: %.3f; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( float ) ( data_val.heading * 360.0f / 32768.0f ),
                    ( float ) ( data_val.pitch * 360.0f / 32768.0f ),
                    ( float ) ( data_val.roll * 360.0f / 32768.0f ),
                    ( uint16_t ) ( *accuracy ),
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    }
    else
    {
        log_printf( &logger, "SID: %s; H: %.3f, P: %.3f, R: %.3f; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( float ) ( data_val.heading * 360.0f / 32768.0f ),
                    ( float ) ( data_val.pitch * 360.0f / 32768.0f ),
                    ( float ) ( data_val.roll * 360.0f / 32768.0f ),
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    }
}
#elif QUATERNION
static void parse_quaternion ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    struct smartsens_data_quaternion data_val;
    if ( callback_info->data_size != 11 ) /* Check for a valid payload size. Includes sensor ID */
    {
        return;
    }
    data_val.x = SMARTSENS_LE2S16( callback_info->data_ptr );
    data_val.y = SMARTSENS_LE2S16( callback_info->data_ptr + 2 );
    data_val.z = SMARTSENS_LE2S16( callback_info->data_ptr + 4 );
    data_val.w = SMARTSENS_LE2S16( callback_info->data_ptr + 6 );
    data_val.accuracy = SMARTSENS_LE2U16( callback_info->data_ptr + 8 );
    log_printf( &logger, "SID: %s; X: %.3f, Y: %.3f, Z: %.3f, W: %.3f; acc: %.2f; Time: %lus\r\n",
                get_sensor_name( callback_info->sensor_id ),
                ( float ) ( data_val.x / 16384.0f ),
                ( float ) ( data_val.y / 16384.0f ),
                ( float ) ( data_val.z / 16384.0f ),
                ( float ) ( data_val.w / 16384.0f ),
                ( float ) ( ( ( data_val.accuracy * 180.0f ) / 16384.0f ) / 3.141592653589793f ),
                SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
}
#elif VECTOR
static void parse_vector_s16 ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    struct smartsens_data_xyz data_value;
    if ( callback_ref )
    {
        struct parse_ref *parse_table = ( struct parse_ref* ) callback_ref;
        float scaling_factor = parse_table->sensor[ callback_info->sensor_id ].scaling_factor;
        data_value.x = SMARTSENS_LE2S16( callback_info->data_ptr );
        data_value.y = SMARTSENS_LE2S16( callback_info->data_ptr + 2 );
        data_value.z = SMARTSENS_LE2S16( callback_info->data_ptr + 4 );
    #if ACCELEROMETER
        log_printf( &logger, "SID: %s; X: %.3f, Y: %.3f, Z: %.3f; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( float ) ( data_value.x * scaling_factor ),
                    ( float ) ( data_value.y * scaling_factor ),
                    ( float ) ( data_value.z * scaling_factor ),
                    ( uint16_t ) parse_table->sensor[ callback_info->sensor_id ].accuracy, 
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    #elif GYROSCOPE
        log_printf( &logger, "SID: %s; X: %d, Y: %d, Z: %d; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( int16_t ) ( data_value.x * scaling_factor ),
                    ( int16_t ) ( data_value.y * scaling_factor ),
                    ( int16_t ) ( data_value.z * scaling_factor ),
                    ( uint16_t ) parse_table->sensor[ callback_info->sensor_id ].accuracy, 
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    #elif MAGNETOMETER
        log_printf( &logger, "SID: %s; X: %d, Y: %d, Z: %d; acc: %u; Time: %lus\r\n",
                    get_sensor_name( callback_info->sensor_id ),
                    ( int16_t ) ( data_value.x * scaling_factor ),
                    ( int16_t ) ( data_value.y * scaling_factor ),
                    ( int16_t ) ( data_value.z * scaling_factor ),
                    ( uint16_t ) parse_table->sensor[ callback_info->sensor_id ].accuracy, 
                    SMARTSENS_TIMESTAMP_TO_SEC( *callback_info->time_stamp ) );
    #else
        #error NO_VECTOR_EXAMPLE_DEFINED
    #endif
    }
    else
    {
        log_error( &logger, "Null reference" );
    }
}
#else
    #error NO_EXAMPLE_DEFINED
#endif

static void parse_meta_event ( struct smartsens_fifo_parse_data_info *callback_info, void *callback_ref )
{
    uint8_t meta_event_type = callback_info->data_ptr[ 0 ];
    uint8_t byte1 = callback_info->data_ptr[ 1 ];
    uint8_t byte2 = callback_info->data_ptr[ 2 ];
    uint8_t *accuracy = ( uint8_t* ) callback_ref;
    char *event_text;

    if ( SMARTSENS_SYS_ID_META_EVENT == callback_info->sensor_id )
    {
        event_text = "[META EVENT]";
    }
    else if ( SMARTSENS_SYS_ID_META_EVENT_WU == callback_info->sensor_id )
    {
        event_text = "[META EVENT WAKE UP]";
    }
    else
    {
        return;
    }

    switch ( meta_event_type )
    {
        case SMARTSENS_META_EVENT_FLUSH_COMPLETE:
        {
            log_printf( &logger, "%s Flush complete for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_SAMPLE_RATE_CHANGED:
        {
            log_printf( &logger, "%s Sample rate changed for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_POWER_MODE_CHANGED:
        {
            log_printf( &logger, "%s Power mode changed for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_ALGORITHM_EVENTS:
        {
            log_printf( &logger, "%s Algorithm event\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_SENSOR_STATUS:
        {
            log_printf( &logger, "%s Accuracy for sensor id %s changed to %s\r\n", 
                        event_text, get_sensor_name( byte1 ), get_sensor_name( byte2 ) );
            if ( accuracy )
            {
                *accuracy = byte2;
            }
            break;
        }
        case SMARTSENS_META_EVENT_BSX_DO_STEPS_MAIN:
        {
            log_printf( &logger, "%s BSX event (do steps main)\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_BSX_DO_STEPS_CALIB:
        {
            log_printf( &logger, "%s BSX event (do steps calib)\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_BSX_GET_OUTPUT_SIGNAL:
        {
            log_printf( &logger, "%s BSX event (get output signal)\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_SENSOR_ERROR:
        {
            log_printf( &logger, "%s Sensor id %u reported error 0x%02X\r\n", 
                        event_text, byte1, byte2 );
            break;
        }
        case SMARTSENS_META_EVENT_FIFO_OVERFLOW:
        {
            log_printf( &logger, "%s FIFO overflow\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_DYNAMIC_RANGE_CHANGED:
        {
            log_printf( &logger, "%s Dynamic range changed for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_FIFO_WATERMARK:
        {
            log_printf( &logger, "%s FIFO watermark reached\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_INITIALIZED:
        {
            log_printf( &logger, "%s Firmware initialized. Firmware version %u\r\n", 
                        event_text, ( ( uint16_t )byte2 << 8 ) | byte1 );
            break;
        }
        case SMARTSENS_META_TRANSFER_CAUSE:
        {
            log_printf( &logger, "%s Transfer cause for sensor id %s\r\n", 
                        event_text, get_sensor_name( byte1 ) );
            break;
        }
        case SMARTSENS_META_EVENT_SENSOR_FRAMEWORK:
        {
            log_printf( &logger, "%s Sensor framework event for sensor id %s\r\n", 
                        event_text, byte1 );
            break;
        }
        case SMARTSENS_META_EVENT_RESET:
        {
            log_printf( &logger, "%s Reset event\r\n", event_text );
            break;
        }
        case SMARTSENS_META_EVENT_SPACER:
        {
            break;
        }
        default:
        {
            log_printf( &logger, "%s Unknown meta event with id: %u\r\n", 
                        event_text, meta_event_type );
            break;
        }
    }
}

static char* get_sensor_name ( uint8_t sensor_id )
{
    char *ret;

    switch ( sensor_id )
    {
        case SMARTSENS_SENSOR_ID_ACC_PASS:
        {
            ret = "Accelerometer passthrough";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_RAW:
        {
            ret = "Accelerometer uncalibrated";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC:
            ret = "Accelerometer corrected";
            break;
        case SMARTSENS_SENSOR_ID_ACC_BIAS:
        {
            ret = "Accelerometer offset";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_WU:
        {
            ret = "Accelerometer corrected wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_RAW_WU:
        {
            ret = "Accelerometer uncalibrated wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_PASS:
        {
            ret = "Gyroscope passthrough";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_RAW:
        {
            ret = "Gyroscope uncalibrated";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO:
        {
            ret = "Gyroscope corrected";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_BIAS:
        {
            ret = "Gyroscope offset";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_WU:
        {
            ret = "Gyroscope wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_RAW_WU:
        {
            ret = "Gyroscope uncalibrated wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_PASS:
        {
            ret = "Magnetometer passthrough";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_RAW:
        {
            ret = "Magnetometer uncalibrated";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG:
        {
            ret = "Magnetometer corrected";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_BIAS:
        {
            ret = "Magnetometer offset";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_WU:
        {
            ret = "Magnetometer wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_RAW_WU:
        {
            ret = "Magnetometer uncalibrated wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GRA:
        {
            ret = "Gravity vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_GRA_WU:
        {
            ret = "Gravity vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_LACC:
        {
            ret = "Linear acceleration";
            break;
        }
        case SMARTSENS_SENSOR_ID_LACC_WU:
        {
            ret = "Linear acceleration wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_RV:
        {
            ret = "Rotation vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_RV_WU:
        {
            ret = "Rotation vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAMERV:
        {
            ret = "Game rotation vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAMERV_WU:
        {
            ret = "Game rotation vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GEORV:
        {
            ret = "Geo-magnetic rotation vector";
            break;
        }
        case SMARTSENS_SENSOR_ID_GEORV_WU:
        {
            ret = "Geo-magnetic rotation vector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_ORI:
        {
            ret = "Orientation";
            break;
        }
        case SMARTSENS_SENSOR_ID_ORI_WU:
        {
            ret = "Orientation wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_TILT_DETECTOR:
        {
            ret = "Tilt detector";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD:
        {
            ret = "Step detector";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC:
        {
            ret = "Step counter";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC_WU:
        {
            ret = "Step counter wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_SIG:
        {
            ret = "Significant motion";
            break;
        }
        case SMARTSENS_SENSOR_ID_WAKE_GESTURE:
        {
            ret = "Wake gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_GLANCE_GESTURE:
        {
            ret = "Glance gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_PICKUP_GESTURE:
        {
            ret = "Pickup gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_AR:
        {
            ret = "Activity recognition";
            break;
        }
        case SMARTSENS_SENSOR_ID_WRIST_TILT_GESTURE:
        {
            ret = "Wrist tilt gesture";
            break;
        }
        case SMARTSENS_SENSOR_ID_DEVICE_ORI:
        {
            ret = "Device orientation";
            break;
        }
        case SMARTSENS_SENSOR_ID_DEVICE_ORI_WU:
        {
            ret = "Device orientation wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STATIONARY_DET:
        {
            ret = "Stationary detect";
            break;
        }
        case SMARTSENS_SENSOR_ID_MOTION_DET:
        {
            ret = "Motion detect";
            break;
        }
        case SMARTSENS_SENSOR_ID_ACC_BIAS_WU:
        {
            ret = "Accelerometer offset wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GYRO_BIAS_WU:
        {
            ret = "Gyroscope offset wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_MAG_BIAS_WU:
        {
            ret = "Magnetometer offset wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD_WU:
        {
            ret = "Step detector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_TEMP:
        {
            ret = "Temperature";
            break;
        }
        case SMARTSENS_SENSOR_ID_BARO:
        {
            ret = "Barometer";
            break;
        }
        case SMARTSENS_SENSOR_ID_HUM:
        {
            ret = "Humidity";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAS:
        {
            ret = "Gas";
            break;
        }
        case SMARTSENS_SENSOR_ID_TEMP_WU:
        {
            ret = "Temperature wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_BARO_WU:
        {
            ret = "Barometer wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_HUM_WU:
        {
            ret = "Humidity wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_GAS_WU:
        {
            ret = "Gas wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC_HW:
        {
            ret = "Hardware Step counter";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD_HW:
        {
            ret = "Hardware Step detector";
            break;
        }
        case SMARTSENS_SENSOR_ID_SIG_HW:
        {
            ret = "Hardware Significant motion";
            break;
        }
        case SMARTSENS_SENSOR_ID_STC_HW_WU:
        {
            ret = "Hardware Step counter wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_STD_HW_WU:
        {
            ret = "Hardware Step detector wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_SIG_HW_WU:
        {
            ret = "Hardware Significant motion wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_ANY_MOTION:
        {
            ret = "Any motion";
            break;
        }
        case SMARTSENS_SENSOR_ID_ANY_MOTION_WU:
        {
            ret = "Any motion wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_EXCAMERA:
        {
            ret = "External camera trigger";
            break;
        }
        case SMARTSENS_SENSOR_ID_GPS:
        {
            ret = "GPS";
            break;
        }
        case SMARTSENS_SENSOR_ID_LIGHT:
        {
            ret = "Light";
            break;
        }
        case SMARTSENS_SENSOR_ID_PROX:
        {
            ret = "Proximity";
            break;
        }
        case SMARTSENS_SENSOR_ID_LIGHT_WU:
        {
            ret = "Light wake up";
            break;
        }
        case SMARTSENS_SENSOR_ID_PROX_WU:
        {
            ret = "Proximity wake up";
            break;
        }
        default:
        {
            if ( ( sensor_id >= SMARTSENS_SENSOR_ID_CUSTOM_START ) && ( sensor_id <= SMARTSENS_SENSOR_ID_CUSTOM_END ) )
            {
                ret = "Custom sensor ID ";
            }
            else
            {
                ret = "Undefined sensor ID ";
            }
        }
    }

    return ret;
}

// ------------------------------------------------------------------------ END

Additional Support

Resources

Love this project?

'Buy This Kit' button takes you directly to the shopping cart where you can easily add or remove products.