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.

Read

I2C reads are executed by calling mbl_mw_i2c_read. When calling the function, you need to specify:

  • Device address
  • Register address
  • Number of bytes
  • User defined id value identifying the operation
#include "metawear/core/datasignal.h"
#include "metawear/sensor/i2c.h"

void i2c_read(MblMwMetaWearBoard* board) {
    // Assign id=10 to this specific i2c read
    static uint8_t read_id = 10;
    static auto i2c_data = [](const MblMwData* data) -> void {
        printf("WHO_AM_I= %x", ((uint8_t*) data->value)[0]);
    };

    auto read_signal = mbl_mw_i2c_get_data_signal(board, 1, read_id);
    mbl_mw_datasignal_subscribe(read_signal, i2c_data);
    // Read WHO_AM_I register from the MetaWear R accelerometer
    mbl_mw_i2c_read(board, 0x1c, 0xd, 1, read_id);
}

Write

Writing data through the I2C bus is handled with the mbl_mw_i2c_write function. You will need to specify:

  • Device address
  • Register address
  • Data to send
#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);
}