C++ APIs

The C++ library is the heart of our development tools but this part of the tutorial is optional. Unless you are going to develop specifically using C++, you should go to the tutorial for the language of your choice.

If compiled as a shared library, the C++ API can be used with any language that supports calling C functions from a shared library, such as Node and Python.

Warning

The library only constructs the bytes for communicating with the MetaWear platform, it does not contain any Bluetooth LE code.

Users will need to fill in the appropriate Bluetooth LE functions for their target platform.

Source Code

You can find the C++ code on Github here: https://github.com/mbientlab/MetaWear-SDK-Cpp.

C++ Tutorials

You can find tutorials to use the C++ libs here: https://mbientlab.com/cppdocs/latest.

C++ API Documentation

The C++ API calls are documented here: https://mbientlab.com/documents/metawear/cpp/latest/.

MetaWear

The source code for our low level libraries are written in C++. This code is used by our Swift, Python, and Javascript APIs. You can also use it to make your own API in the language of your choice.

API Code Repository

Head over to our C++ Github page: https://github.com/mbientlab/MetaWear-SDK-Cpp

You can clone the repository or simply download as a ZIP file:

>>>  git clone https://github.com/mbientlab/MetaWear-SDK-Cpp

Build

Building the project has been tested on * nix systems with Clang 4.

> clang++ --version
clang version 4.0.1 (tags/RELEASE_401/final 305264)
Target: x86_64-unknown-linux-gnu

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>cl.exe
Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25019 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]

GCC and Clang

Linux users can build the project by invoking GNU make; the default action is to build the shared library for your current platform. You can also change the C++ compiler by overriding the CXX make variable.

> make

# build using g++ as the compiler
> make CXX=g++

Upon a successful compile, the library will be placed in the newly created “dist” directory.

> make
> tree dist
dist/
└── release
    └── lib
        └── x64
            ├── libmetawear.so -> libmetawear.so.0
            ├── libmetawear.so.0 -> libmetawear.so.0.12.1
            └── libmetawear.so.0.12.1

Testing

Unit tests for the library are written in Python (min v3.4.1) and can be invoked by calling the test target (Test for MSBuild).

> make test
python3 -m unittest discover -s test
................................................................................
................................................................................
................................................................................
................................................................................
...........s....................................................................
.........................
----------------------------------------------------------------------
Ran 425 tests in 22.388s

OK (skipped=1)

Here’s a look at our C++ library.

Connect

In the C++ library, you are responsible for telling the SDK that a bluetooth connection is lost (depending you which Bluetooth library you use).

First create a MblMwBtleConnection and then call mbl_mw_metawearboard_create to instantiate a MblMwMetaWearBoard struct.

After you have instantiated a MblMwMetaWearBoard, you then need to initialize its internal state by calling mbl_mw_metawearboard_initialize. Initializing can take a few seconds and will asynchronously alert the caller when it is finished.

If initialization succeeded, MBL_MW_STATUS_OK will be passed to the callback function, otherwise a non-zero value will be returned instead signalling the task failed. You can check if a MblMwMetaWearBoard has been initialized by calling mbl_mw_metawearboard_is_initialized.

Disconnect

The C++ APIs use the on_disconnect field to pass a function pointer to the Bluetooth LE wrapper for handling disconnect events.

static unordered_map<const void*, MblMwFnVoidVoidPtrInt> dc_handlers;
...
static void on_disconnect(void* context, const void* caller, MblMwFnVoidVoidPtrInt handler) {
    // call this handler everytime connection is lost, use 0 for 'value' parameter
    // handler(context, caller, 0)
    dc_handlers.insert({ caller, handler });
}

Reset

If your board is stuck in a bad state or needs to be reset, there are a few steps and functions you should call to throughly reset your board:

// Stops data logging
METAWEAR_API void mbl_mw_logging_stop(const MblMwMetaWearBoard* board);
// Clear the logger of saved entries
METAWEAR_API void mbl_mw_logging_clear_entries(const MblMwMetaWearBoard* board);
// Remove all macros on the flash memory
METAWEAR_API void mbl_mw_macro_erase_all (MblMwMetaWearBoard *board)
// Restarts the board after performing garbage collection
METAWEAR_API void mbl_mw_debug_reset_after_gc (const MblMwMetaWearBoard *board)

You can take time to look at what each call does in the C++ documentation yourself.

Data

Data signals are an abstract representation of data producers. The API treats them as an event that contains data and represents them with the MblMwDataSignal struct.

They can be safely typecasted to an MblMwEvent.

Signal data is encapsulated by the MblMwData struct. The struct contains a:

  • Timestamp of when the data was created

  • Pointer to the data

  • Data type id indicating how to cast the pointer

An enumeration of data types is defined by the MblMwDataTypeId enum and structs wrapping non basic data types are defined in the types.h header file.

#include "metawear/core/data.h"
#include <chrono>
#include <iomanip>

using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
using std::chrono::time_point;

void data_printer(void* context, const MblMwData* data) {
    // Print data as 2 digit hex values
    uint8_t* data_bytes = (uint8_t*) data->value;
    string bytes_str("[");
    char buffer[5];
    for (uint8_t i = 0; i < data->length; i++) {
        if (i) {
            bytes_str += ", ";
        }
        sprintf(buffer, "0x%02x", data_bytes[i]);
        bytes_str += buffer;
    }
    bytes_str += "]";

    // Format time as YYYYMMDD-HH:MM:SS.LLL
    time_point<system_clock> then(milliseconds(data->epoch));
    auto time_c = system_clock::to_time_t(then);
    auto rem_ms= data->epoch % 1000;

    cout << "{timestamp: " << put_time(localtime(&time_c), "%Y%m%d-%T") << "." << rem_ms << ", "
        << "type_id: " << data->type_id << ", "
        << "bytes: " << bytes_str.c_str() << "}"
        << endl;
}

Let’s take a look at the most common MblMwCartesianFloat data type. Angular velocity from the Gyropscope is represented by the MblMwCartesianFloat struct and is in units of degrees per second. The x, y, and z fields contain the angular velocity of the spin around that axis.

For the Python and Javascript APIs, you cast the type when you subscribe to the signal. The type FnVoid_VoidP_DataP represents the MblMwCartesianFloat type.

Don’t bother too much with the rest of the code, we will look into it in more details in the rest of this tutorial. Concentrate on the different data types that can come from our sensors and how we cast them:

#include "metawear/sensor/gyro_bmi160.h"

void gyro_rot_rate_stream(MblMwMetaWearBoard* board) {
    static auto rot_handler = [](void* context, const MblMwData* data) {
        // Cast value to MblMwCartesianFloat*
        auto rot_rate = (MblMwCartesianFloat*)data->value;
        printf("(%.3fdps, %.3fdps, %.3fdps)\n", rot_rate->x, rot_rate->y, rot_rate->z);
    };
    auto state_signal = mbl_mw_gyro_bmi160_get_rotation_data_signal(board);
    mbl_mw_datasignal_subscribe(state_signal, nullptr, rot_handler);

    mbl_mw_gyro_bmi160_enable_rotation_sampling(board);
    mbl_mw_gyro_bmi160_start(board);
}

Streaming

You can stream sensor data continuously from any of the digital sensors on board including the magnetomer, gyroscope, accelerometer, pressure, humidity and light sensor.

When you do so, you need to setup the sensor with the frequency interval of the desired data (sampling frequency).

You need to lookup the capabilities and setup requirements of that particular sensor and write your code accordingly. For example, the accelerometer might need the resolution to be set at +/-4g and the sample rate at 25Hz.

To stream data live from your MetaSensor board, call mbl_mw_datasignal_subscribe with the desired data signal and include a callback function for handling the received data.

Terminating the live stream is done by calling mbl_mw_datasignal_unsubscribe . Don’t forget to turn of the sensor as well!

Here is an example to stream accelerometer data:

#include "metawear/core/datasignal.h"
#include "metawear/core/types.h"
#include "metawear/sensor/accelerometer.h"

void enable_acc_sampling(MblMwMetaWearBoard* board) {
    // Set ODR to 25Hz or closest valid frequency
    mbl_mw_acc_set_odr(board, 25.f);

    // Set range to +/-4g or closest valid range
    mbl_mw_acc_set_range(board, 4.f);

    // Write the config to the sensor
    mbl_mw_acc_write_acceleration_config(board);

    auto data_handler = [](void* context, const MblMwData* data) -> void {
        // Cast value to MblMwCartesianFloat*
        auto acceleration = (MblMwCartesianFloat*) data->value;
        printf("(%.3fg, %.3fg, %.3fg)\n", acceleration->x, acceleration->y, acceleration->z);
    };

    auto acc_signal= mbl_mw_acc_get_acceleration_data_signal(board);
    mbl_mw_datasignal_subscribe(acc_signal, nullptr, data_handler);

    mbl_mw_acc_enable_acceleration_sampling(board);
    mbl_mw_acc_start(board);
}

void disable_acc_sampling(MblMwMetaWearBoard* board) {
    auto acc_signal= mbl_mw_acc_get_acceleration_data_signal(board);
    mbl_mw_datasignal_unsubscribe(acc_signal);

    mbl_mw_acc_disable_acceleration_sampling(board);
    mbl_mw_acc_stop(board);
}

Logging

Alternatively, data can be logged and retrieved at a later time. This applies to the same sensors including the magnetomer, gyroscope, accelerometer, pressure, humidity and light sensor.

This takes a bit more effort because your code will need to know what data is being logged so you are responsible for saving logger IDs and retrieving them when you download the sensor data from the MetaSensor internal memory.

You also need to handle the callbacks as the data is downloaded from the MetaSensor memory.

Warning

MetaSensors have a finite memory and when you run out of memory, new entries will over-write old entries. You can actually change this setting in the mbl_mw_logging_start call.

Note

Please see our calculator function to see how many sensor data entries and at what frequency will the memory of the MetaSensor become full.

Loggers record data from a data signal and are represented by the MblMwDataLogger struct. You create an MblMwDataLogger object by calling mbl_mw_datasignal_log with the data signal you want to log. If successful, the callback function will be executed with a MblMwDataLogger* pointer and a null pointer if it failed.

MblMwDataLogger objects only interact with the specific data signal, they do not control the logging features.

MblMwDataLogger objects are identified by a numerical id; you can retrieve the id by calling mbl_mw_logger_get_id. The id is used to retrieve existing loggers from the API with the mbl_mw_logger_lookup_id function and is important when you have multiple loggers running.

Like a data signal, you can subscribe to an MblMwDataLogger to process the downloaded data. Call mbl_mw_logger_subscribe to attach a callback function to the MblMwDataLogger which handles all received data.

After you have setup the signal loggers, start the logger by calling mbl_mw_logging_start.

When you are ready to retrieve the data, execute mbl_mw_logging_download . You will need to pass in a MblMwLogDownloadHandler struct to handle notifications from the logger.

We have updated our streaming accelerometer data example to log data this time:

#include "metawear/core/datasignal.h"
#include "metawear/core/logging_fwd.h"
#include "metawear/sensor/accelerometer.h"

void enable_acc_logging(MblMwMetaWearBoard* board) {
    mbl_mw_acc_set_odr(board, 25.f);
    mbl_mw_acc_set_range(board, 4.f);
    mbl_mw_acc_write_acceleration_config(board);

    auto acc_signal= mbl_mw_acc_get_acceleration_data_signal(board);
    mbl_mw_datasignal_log(acc_signal, nullptr, [](void* context, MblMwDataLogger* logger) -> void {
        if (logger != nullptr) {
            // save logger as acc_logger for logger_subscribe function
            printf("logger ready\n");
        } else {
            printf("Failed to create the logger\n");
        }
    });

    mbl_mw_logging_start(board, 0)
    mbl_mw_acc_enable_acceleration_sampling(board);
    mbl_mw_acc_start(board);
}

void logger_subscribe(MblMwDataLogger* acc_logger) {
    mbl_mw_logger_subscribe(acc_logger, context, [](void* context, const MblMwData* data) -> void {
        // Cast value to MblMwCartesianFloat*
        auto acceleration = (MblMwCartesianFloat*) data->value;
        printf("(%.3fg, %.3fg, %.3fg)\n", acceleration->x, acceleration->y, acceleration->z);
    });
}

Reading

Analog sensors such as the temperature sensor or the on-board push button cannot be read continuously; they will only send data when they receive a command to do so. You can either read them once OR use a timer loop to read them multiple times.

You can also read the pressure, light, and humidity sensors once if you wish.

Data signals that represent this type of data source are called readable signals. You can check if a data signal is readable by calling mbl_mw_datasignal_is_readable.

The read command is issued by calling mbl_mw_datasignal_read or mbl_mw_datasignal_read_with_parameters.

When using readable signals, you must decide up front if the data will be streamed or logged before interacting with it. That is, you should either have subscribed to or setup a logger for a readable signal before reading it.

Note

This is a great way to get very low sampling rates for certain sensors.

We will look at an example for the temperature sensor. Temperature reads are manually triggered by calling mbl_mw_datasignal_read. The data is represented as a float and is in units of Celsius.

Let’s do a one time read:

#include "metawear/core/datasignal.h"
#include "metawear/sensor/multichanneltemperature.h"

void read_temperature(MblMwMetaWearBoard* board) {
    static auto temp_handler = ;

    // Retrieve data signal for on board thermistor source
    auto temp_signal = mbl_mw_multi_chnl_temp_get_temperature_data_signal(board,
            MBL_MW_METAWEAR_RPRO_CHANNEL_ON_BOARD_THERMISTOR);
    mbl_mw_datasignal_subscribe(temp_signal, nullptr, [](void* context, const MblMwData* data) {
        // cast to float*
        printf("%.3fC\n", *((float*) data->value));
    });
    mbl_mw_datasignal_read(temp_signal);
}

See the Timer section below to understand how we can do continuous reads of some of the analog sensors and peripherals.

Writing

Sometimes you want to send commands to the board. You can turn on the LED, make the board vibrate if it has a coin vibration motor on it, or send GPIO, I2C or SPI commands.

Let’s take a look at the LED since all boards come with an on-board RGD LED.

An led pattern is represented by the MblMwLedPattern struct. Users can configure every part of the pulse or load one of the preset patterns using the mbl_mw_led_load_preset_pattern function. Patterns are written to the board with the mbl_mw_led_write_pattern function.

After writing patterns to the board, you can playback the pattern, similar to playing a music track, using mbl_mw_led_play, mbl_mw_led_pause, and mbl_mw_led_stop.

To remove patterns, call mbl_mw_led_stop_and_clear; this will also stop pattern playback.

#include "metawear/peripheral/led.h"

void set_led_pattern(MblMwMetaWearBoard* board) {
    MblMwLedPattern pattern;

    // Load the blink pattern
    mbl_mw_led_load_preset_pattern(&pattern, MBL_MW_LED_PRESET_BLINK);
    // Write the blink pattern to the blue channel
    mbl_mw_led_write_pattern(board, &pattern, MBL_MW_LED_COLOR_BLUE);
    // Start playing the programmed patterns
    mbl_mw_led_play(board);
    ...
    // Stop
    mbl_mw_led_stop_and_clear(board)
}

Events

An event is an asynchronous notification from the MetaWear board represented in the C++ API by the MblMwEvent struct.

The board can be programmed to execute MetaWear commands in response to an event firing. To start recording commands, call mbl_mw_event_record_commands. While in a recording state, all MetaWear functions called will instead be recorded on the board and executed when the event is fired.

To stop recording, call mbl_mw_event_end_record. This function is asynchronous and will alert the caller when it is completed via a callback function. If recording events was successful, MBL_MW_STATUS_OK will be passed into the callback function, otherwise MBL_MW_STATUS_ERROR_TIMEOUT is used.

#include "metawear/core/event.h"
#include "metawear/core/settings.h"

void setup_dc_event(MblMwMetaWearBoard* board) {
    MblMwLedPattern pattern;
    mbl_mw_led_load_preset_pattern(&pattern, MBL_MW_LED_PRESET_BLINK);
    pattern.repeat_count = 10;

    // Setup disconnect event to blink the blue led 10x when fired
    MblMwEvent* dc_event = mbl_mw_settings_get_disconnect_event(board);
    mbl_mw_event_record_commands(dc_event);
    mbl_mw_led_write_pattern(board, &pattern, MBL_MW_LED_COLOR_BLUE);
    mbl_mw_led_play(board);
    mbl_mw_event_end_record(dc_event, nullptr, [](void* context, MblMwEvent* event, int32_t status) {
        if (!status) {
            cout << "Error recording commands, status= " << status << endl;
        } else {
            cout << "Commands recorded" << endl;
        }
    });
}

Timer

A MetaWear timer can be thought of as an event that is fired at fixed intervals. These timers are represented by the MblMwTimer struct and can be safely typcased to a MblMwEvent struct. Timers can be used to schedule periodic tasks or setup a delayed task execution.

MblMwTimer objects are identified by a numerical id; you can retrieve the id by calling mbl_mw_timer_get_id. The id is used to retrieve existing timers from the API with the mbl_mw_timer_lookup_id function.

Before you can schedule tasks, you first need to create a timer, by calling either mbl_mw_timer_create or mbl_mw_timer_create_indefinite. These functions are asynchronous and will pass a pointer to the caller when the timer is created. When you have a valid MblMwTimer, you can use the command recording system outlined in Events section to program the board to respond to the periodic events. Upon recording timer task commands, call mbl_mw_timer_start to start the timer.

When you are done using a timer, you can remove it with mbl_mw_timer_remove.

#include "metawear/core/event.h"
#include "metawear/core/timer.h"

#include "metawear/sensor/gpio.h"

void timer_setup(MblMwMetaWearBoard* board) {
    static auto cmds_recorded = [](void* context, MblMwEvent* event, int32_t status) {
        printf("timer task setup\n");
    };
    static auto timer_created = [](void* context, MblMwTimer* timer) {
        auto owner = mbl_mw_event_get_owner((MblMwEvent*) timer);

        auto adc_signal= mbl_mw_gpio_get_analog_input_data_signal(board, 0,
                MBL_MW_GPIO_ANALOG_READ_MODE_ADC);
        // read gpio adc data every time the timer fires an event
        mbl_mw_event_record_commands((MblMwEvent*) timer);
        mbl_mw_datasignal_read(adc_signal);
        mbl_mw_event_end_record((MblMwEvent*) timer, context, cmds_recorded);

        mbl_mw_timer_start(timer);
    };

    // create a timer that indefinitely fires events every 500ms
    mbl_mw_timer_create_indefinite(board, 500, 0, nullptr, timer_created);
}

Component Signals

Some signals, such as the acceleration datasignal, are composed of multiple values. While you can interact with them as a whole, sometimes it is more convenient to only use individual values.

To access the component values, call mbl_mw_datasignal_get_component with the signal and an index represnting which component to retrieve. If a signal is single valued, the function will return null.

#include "metawear/sensor/accelerometer.h"

void component_demo(MblMwMetaWearBoard* board) {
    auto acc_root = mbl_mw_acc_get_acceleration_data_signal(board);
    // get z axis signal
    auto acc_z = mbl_mw_datasignal_get_component(acc_root, MBL_MW_ACC_ACCEL_Z_AXIS_INDEX);

    mbl_mw_datasignal_subscribe(acc_z, [](MblMwData* data) -> void {
        //combined xyz data is MblMwCartesianFloat, individual axis is float
        printf("z-axis: %.3f\n", *((float*) data->value));
    });
}

Sensor Fusion

The sensor_fusion.h header file interfaces with the sensor fusion algorithm running on MetaMotion boards. When using the sensor fusion algorithm, it is important that you do not simultaneously use the Accelerometer, Gyro, and Magnetometer modules; the algorithm configures those sensors internally based on the selected fusion mode.

To activate the sensor fusion algorithm, first set the fusion mode and data ranges, then subscribe to and enable the desired output data, and finally, call mbl_mw_sensor_fusion_start.

The sensor fusion algorithm has 4 fusion modes, listed in the below table:

Mode

Description

NDoF

Calculates absolute orientation from accelerometer, gyro, and magnetometer

IMUPlus

Calculates relative orientation in space from accelerometer and gyro data

Compass

Determines geographic direction from th Earth’s magnetic field

M4G

Similar to IMUPlus except rotation is detected with the magnetometer

The mode is set with mbl_mw_sensor_fusion_set_mode and written to the board by calling mbl_mw_sensor_fusion_write_config. Before writing the configuration, you can also set the acceleration and rotation ranges of the accelerometer and gyroscope respectively.

#include "metawear/sensor/sensor_fusion.h"

void configure_sensor_fusion(MblMwMetaWearBoard* board) {
    // set fusion mode to ndof (n degress of freedom)
    mbl_mw_sensor_fusion_set_mode(board, MBL_MW_SENSOR_FUSION_MODE_NDOF);
    // set acceleration rangen to +/-8G, note accelerometer is configured here
    mbl_mw_sensor_fusion_set_acc_range(board, MBL_MW_SENSOR_FUSION_ACC_RANGE_8G);
    // write changes to the board
    mbl_mw_sensor_fusion_write_config(board);
}

What’s important is that you look at all the capabilities and settings of each sensor.

For example, for the sensor fusion to work, you need to pick the MODE, the OUTPUT TYPE, the GYROSCOPE RANGE, and the ACCELEROMETER RANGE. These are things you need to think about before you start coding.

Learn more here: https://mbientlab.com/cppdocs/latest/sensor_fusion.html

Data Processing

Data signals can be fed through the on-board data processors to filter and/or transform the data in the firmware.

By performing computations on the MetaWear side, you can reduce the amount of data that is sent over the radio and the amount of postprocessing that is done on your mobile device.

Data processors can also be chained together to perform more complex tasks, such as using the rss, average, and threshold processors to determine if the board is in freefall based on the XYZ acceleration data.

Here is an example of the rss processor. RSS which stands for root sum square is a statistical method of dealing with a series of values where each value is squared, the sum of these squares is calculated and the square root of that sum is then taken:

#include "metawear/core/dataprocessor_fwd.h"
#include "metawear/processor/rss.h"
#include "metawear/sensor/accelerometer.h"

void rss_accelerometer(MblMwMetaWearBoard* board) {
    static auto data_handler = [](void* context, const MblMwData* data) -> void {
        printf("acc rss= %.3fg\n", (float*) data->value);
    };
    static auto rss_ready = [](void* context, MblMwDataProcessor* processor) -> void {
        // subscribe to the rss processor
        mbl_mw_datasignal_subscribe((MblMwDataSignal*) processor, context, data_handler);
    };

    // Create an rss processor to transform the XYZ values into vector magnitude
    // Do not need to compute rss on your device and less data is transmitted
    auto acc_signal = mbl_mw_acc_get_acceleration_data_signal(board);
    mbl_mw_dataprocessor_rss_create(acc_signal, nullptr, rss_ready);
}

Data processors are functions in the firmware that filter or transform sensor data and are represented by the MblMwDataProcessor struct.

In the C++ API, data processors can be thought of as a data signal whose data is produced by the on-board data processor. As such, a MblMwDataProcessor can be safely typecasted to a MblMwDataSignal.

This section will focus on the MblMwDataProcessor struct. Data processors are identified by a unique numerical ID; you can retrieve this id by calling mbl_mw_dataprocessor_get_id. The data processor ID is used to lookup a previously created MblMwDataProcessor object with the mbl_mw_dataprocessor_lookup_id function.

Some processors have an internal state that can be read and modified; the internal state is treated as a readable MblMwDataSignal.

#include "metawear/core/datasignal.h"
#include "metawear/processor/dataprocessor.h"

// Assume input processor is a Buffer processor
void subscribe_state_signal(MblMwDataProcessor* buffer_processor) {
    auto state_signal = mbl_mw_dataprocessor_get_state_data_signal(buffer_processor);
    mbl_mw_datasignal_subscribe(state_signal, nullptr, data_printer);
    mbl_mw_datasignal_read(state_signal);
}

Removing a processor is handled by calling mbl_mw_dataprocessor_remove. When a processor is removed, all processors that consume its output will also be removed.

#include "metawear/core/datasignal_fwd.h"
#include "metawear/processor/dataprocessor.h"
#include "metawear/processor/math.h"

void remove_processors(MblMwDataSignal* temp_signal) {
    static MblMwDataProcessor* first_processor= nullptr;

    static auto add_32_created = [](void* context, MblMwDataProcessor* processor) -> void {
        // Removes all 3 processors in the chain
        mbl_mw_dataprocessor_remove(first_processor);
    };
    static auto div_10_created = [](void* context, MblMwDataProcessor* processor) -> void {
        mbl_mw_dataprocessor_math_create((MblMwDataSignal*) processor, MBL_MW_MATH_OP_ADD, 32.f,
                context, add_32_created);
    };
    static auto mul_18_created = [](void* context, MblMwDataProcessor* processor) -> void {
        first_processor = processor;
        mbl_mw_dataprocessor_math_create((MblMwDataSignal*) processor, MBL_MW_MATH_OP_DIVIDE,
                10.f, context, div_10_created);
    };
    mbl_mw_dataprocessor_math_create(temp_signal, MBL_MW_MATH_OP_MULTIPLY, 18.f, nullptr, mul_18_created);
}

There are many more processors which are detailed here.

Multiple sensors

#include "metawear/core/types.h"
#include "metawear/sensor/accelerometer.h"
#include "metawear/sensor/gyro_bmi160.h"

void gyro_rot_rate_stream(MblMwMetaWearBoard* board) {
    static auto rot_handler = [](void* context, const MblMwData* data) {
        // Cast value to MblMwCartesianFloat*
        auto rot_rate = (MblMwCartesianFloat*)data->value;
        printf("(%.3fdps, %.3fdps, %.3fdps)\n", rot_rate->x, rot_rate->y, rot_rate->z);
    };

    auto state_signal = mbl_mw_gyro_bmi160_get_rotation_data_signal(board);
    mbl_mw_datasignal_subscribe(state_signal, nullptr, rot_handler);

    mbl_mw_gyro_bmi160_enable_rotation_sampling(board);
    mbl_mw_gyro_bmi160_start(board);
}

void enable_acc_sampling(MblMwMetaWearBoard* board) {
    auto data_handler = [](void* context, const MblMwData* data) -> void {
        // Cast value to MblMwCartesianFloat*
        auto acceleration = (MblMwCartesianFloat*) data->value;
        printf("(%.3fg, %.3fg, %.3fg)\n", acceleration->x, acceleration->y, acceleration->z);
    };

    auto acc_signal= mbl_mw_acc_get_acceleration_data_signal(board);
    mbl_mw_datasignal_subscribe(acc_signal, nullptr, data_handler);

    mbl_mw_acc_enable_acceleration_sampling(board);
    mbl_mw_acc_start(board);
}

Multiple sensors with Fuser

The fuser is one of our data processors.

The fuser processor combines data from multiple sensors into 1 message. When fusing multiple data sources, ensure that they are sampling at the same frequency, or at the very least, integer multiples of the fastest frequency. Data sources sampling at the lower frequencies will repeat the last received value.

Unlike the other data sources, fuser data is represented as an MblMwData array, which is indexed based on the order of the data signals passed into mbl_mw_dataprocessor_fuser_create.

#include "metawear/processor/fuser.h"
#include "metawear/sensor/accelerometer.h"
#include "metawear/sensor/gyro_bmi160.h"

void setup_adc_delta(MblMwMetaWearBoard* board) {
    static auto proc_created = [](void* context, MblMwDataProcessor* fuser) {
        mbl_mw_datasignal_subscribe((MblMwDataSignal*)fuser, context, [](void* context, const MblMwData* data) {
            auto fused = (MblMwData**)data->value;

            // 0 - acc data
            // 1 - gyro data
            auto acc = (MblMwCartesianFloat*) fused[0]->value;
            auto gyro = (MblMwCartesianFloat*) fused[1]->value;
            printf("acc = (%.3f, %.3f, %.3f), gyro = (%.3f, %.3f, %.3f)\n",
                    acc->x, acc->y, acc->z,gyro->x, gyro->y, gyro->z);
        });
    };

    auto acc_signal = mbl_mw_acc_get_acceleration_data_signal(board);
    auto gyro_signal = mbl_mw_gyro_bmi160_get_rotation_data_signal(board);

    mbl_mw_dataprocessor_fuser_create(acc_signal, &gyro_signal, 1, nullptr, proc_created);
}

Anonymous downloading

Anonymous data signals are a variant of the Logger type used to retrieve logged data from a board that was not programmed by the current host device. Use mbl_mw_metawearboard_create_anonymous_datasignals to sync the host device with the board’s current logger state. If the function fails, a null pointer will be returned and the uint32_t parameter instead corresponds to a status code from the SDK.

Because of the anonymous nature of the object, users will need to rely on an identifier string to determine what kind of data is being passed to each route. Generate the identifier string by calling mbl_mw_logger_generate_identifier for each MblMwDataLogger type and match these values with mbl_mw_anonymous_datasignal_get_identifier.

Warning

Please note that not all loggers are supported.

#include "metawear/core/datasignal.h"
#include "metawear/core/logging.h"
#include "metawear/platform/memory.h"
#include "metawear/sensor/gyro_bmi160.h"

void identifier_demo(MblMwMetaWearBoard* board) {
    auto gyro = mbl_mw_gyro_bmi160_get_rotation_data_signal(board);
    auto gyro_y = mbl_mw_datasignal_get_component(gyro, MBL_MW_GYRO_ROTATION_Y_AXIS_INDEX);
    mbl_mw_datasignal_log(gyro_y, nullptr, [](void* context, MblMwDataLogger* logger) -> void {
        auto identifier = mbl_mw_logger_generate_identifier(logger);
        cout << "gyro_y identifier = " << identifier << endl;
    });
}
#include "metawear/core/anonymous_datasignal.h"

// Use mbl_mw_metawearboard_create_anonymous_datasignals to retrieve log data from
// another device
void anonymous_signal_demo(MblMwMetaWearboard* board) {
    mbl_mw_metawearboard_create_anonymous_datasignals(board, nullptr, [](void* context, MblMwMetaWearBoard* board,
            MblMwAnonymousDataSignal** anonymous_signals, uint32_t size) {
        if (anonymous_signals == nullptr) {
            cerr << "Failed to create anonymous signals, status = " << (int32_t) size << endl;
            return;
        }
        for (uint32_t i = 0; i < size; i++) {
            auto identifier = mbl_mw_anonymous_datasignal_get_identifier(anonymous_signals[i]);

            // identifier earlier extracted from calling
            // mbl_mw_logger_generate_identifier, use in if-else statements to identify
            // which anonymous signal represents gyro y-axis data
            if (!strcmp(identifier, "angular-velocity[1]")) {
                mbl_mw_anonymous_datasignal_subscribe(anonymous_signals[i], context, [](void* context, const MblMwData* data) {
                    printf("gyro y-axis: %.3f", *((float*) data->value));
                });
            }
        }
    });
}

Macro

The on-board flash memory can also be used to store MetaWear commands instead of sensor data. Recorded commands can be executed any time after being programmed with the functions in macro.h header file.

To record commands:

  1. Call mbl_mw_macro_record to put the API in macro mode

  2. Use the MetaWear commands that you want programmed

  3. Exit macro mode with mbl_mw_macro_end_record

Macros can be set to run on boot by setting the exec_on_boot parameter with a non-zero value.

Erasing macros is done with the mbl_mw_macro_erase_all method. The erase operation will not occur until you disconnect from the board.

#include "metawear/core/macro.h"
#include "metawear/peripheral/led.h"

void setup_macro(MblMwMetaWearBoard* board) {
    static auto callback = [](void* context, MblMwMetaWearBoard* board, int32_t id) {
        cout << "Macro ID = " << id << endl;
    };
    MblMwLedPattern pattern = { 16, 16, 0, 500, 0, 1000, 0, 5 };

    mbl_mw_macro_record(board, 1);
    mbl_mw_led_write_pattern(board, &pattern, MBL_MW_LED_COLOR_BLUE);
    mbl_mw_led_play(board);
    mbl_mw_macro_end_record(board, nullptr, callback);
}

...
mbl_mw_macro_erase_all(board)

Settings

The battery data provided by the Settings module reports both charge percetange and voltage, encapsulated by the MblMwBatteryState struct. Unlike the battery gatt servive, this battery data can be utilized with MetaWear features such as the logger.

#include "metawear/core/datasignal.h"
#include "metawear/core/settings.h"
#include "metawear/core/types.h"

void battery_stream(MblMwMetaWearBoard* board) {
    auto battery_signal = mbl_mw_settings_get_battery_state_data_signal(board);

    mbl_mw_datasignal_subscribe(battery_signal, nullptr, [](void* context, const MblMwData* data) -> void {
        auto state = (MblMwBatteryState*) data->value;
        printf("{voltage: %dmV, charge: %d}\n", state->voltage, state->charge);
    });
    mbl_mw_datasignal_read(battery_signal);
}

There are other settings available such as changing connection parameters, advertising parameters, and getting the power and charge status of the MetaSensor.

Peripherals

All boards come with general purpose I/O pins allowing users to attach their own sensors.

The I/O pins can be used as general analog or digital pins. Some of the I/Os also support I2C and SPI connectivity.

Let’s take a quick look at two examples. First, let’s read an analog input from one of the I/O pins.

Functions for communicating with the gpio pins are in the gpio.h header file.

Analog input data comes in 2 forms, an ADC value or a absolute reference value. These two modes are distinguished with the MblMwGpioAnalogReadMode enum.

To read analog data, call mbl_mw_datasignal_read with your analog input signal. ADC values are represented as an unsigned integer and are simply ratiometric values with no units. The absolute reference value is also represented as an unsigned integer but has units of milli volts.

#include "metawear/sensor/gpio.h"

void gpio_analog_stream(MblMwMetaWearBoard* board) {
    auto adc_signal = mbl_mw_gpio_get_analog_input_data_signal(board, 0,
            MBL_MW_GPIO_ANALOG_READ_MODE_ADC);
    mbl_mw_datasignal_subscribe(adc_signal, nullptr, [](void* context, const MblMwData* data) {
        // Cast value to uint32_t*
        printf("gpio 0 adc= %d", *((uint32_t*) data->value));
    });
    mbl_mw_datasignal_read(adc_signal);

    auto abs_ref_signal = mbl_mw_gpio_get_analog_input_data_signal(board, 1,
            MBL_MW_GPIO_ANALOG_READ_MODE_ABS_REF);
    mbl_mw_datasignal_subscribe(abs_ref_signal, nullptr, [](void* context, const MblMwData* data) {
        // Cast value to uint32_t*
        printf("gpio 1 voltage= %dmV", *((uint32_t*) data->value));
    });
    mbl_mw_datasignal_read(abs_ref_signal);
}

The next example is I2C.

The I2C module allows you to directly communicate with a sensor via the I2C bus. I2C functions are defined in the i2c.h header file.

I2C data signals are retrieved by calling mbl_mw_i2c_get_data_signal. You will need to pass two parameters:

  • Length variable that sets how many bytes the signal is expected to receive

  • An unique ID identifying the signal

If the id value has already been used, the length parameter will be ignored and the previously created signal will be returned.

#include "metawear/sensor/i2c.h"

// create and get a datasignal for 1 byte of i2c data
auto i2c_signal= mbl_mw_i2c_get_data_signal(board, 1, 0xa);

To read I2C data, use the mbl_mw_datasignal_read_with_parameters function with the parameters set by the MblMwI2cReadParameters struct.

#include "metawear/core/datasignal.h"
#include "metawear/sensor/i2c.h"

mbl_mw_datasignal_subscribe(i2c_signal, nullptr, [](void* context, const MblMwData* data) {
    printf("WHO_AM_I= %x", ((uint8_t*) data->value)[0]);
});

MblMwI2cReadParameters read_params= {0x1c, 0xd};
mbl_mw_datasignal_read_with_parameters(i2c_signal, &read_params);

Writing data through the I2C bus is handled with the mbl_mw_i2c_write function.

#include "metawear/sensor/i2c.h"

void i2c_write(MblMwMetaWearBoard* board) {
    // Write to the ctrl_meas register on the RPro/CPro barometer
    uint8_t ctrl_meas= 0x37;
    mbl_mw_i2c_write(board, 0x77, 0xf4, &ctrl_meas, 1);
}

Next Steps

Advanced developers building more complex apps can refer to the C++ Documentation.