I2C Module

Note

The I2C Module contains wrappers for the controller’s I²C interface.
Doxygen:

Features

Direct device access

Simple I²C devices may simply be accessed directly through their device address.

The following code demonstrates how to send a single byte of data directly to a device.

const uint8_t Address = 0x12;
const uint8_t Data = 0xFF;

if (R_SUCCESS(I2C_Write(Address, Data))) {
    // Successfully sent data and received ACK from device
}

The following code demonstrates how to read a single byte of data directly from a device.

const uint8_t Address = 0x12;

uint8_t data = 0;

if (R_SUCCESS(I2C_Read(Address, &data))) {
    // Successfully read data and received ACK from device
}
result_t I2C_Write(I2C_Handle_t handle, uint8_t address, uint8_t data)

Writes one byte to an I2C device.

Parameters
  • address – Device address

  • data – Data to write

Returns

Status result

result_t I2C_Read(I2C_Handle_t handle, uint8_t address, uint8_t *data)

Reads one byte from an I2C device.

Parameters
  • address – Device address

  • data – Pointer to where read byte should be written to

Returns

Status result

Register access

Most I²C sensors consist of more than one register that can be written to or read from. For these devices, the device address is not enough but a second address, the register address, is needed.

The following code starts a pressure measurement of the on-board pressure sensor

const uint8_t DeviceAddress     = 0x5C;
const uint8_t CTRL_REG2         = 0x11;

if (R_SUCCESS(I2C_WriteRegister(DeviceAddress, CTRL_REG2, 0x01))) {
    // Successfully wrote value to register and received ACK
}

The following code reads the WHO_AM_I register of the on-board pressure sensor.

const uint8_t DeviceAddress     = 0x5C;
const uint8_t RequestResponse   = 0x80;
const uint8_t WHO_AM_I          = 0x0F;

uint8_t data = 0;
if (R_SUCCESS(I2C_ReadRegister(DeviceAddress, WHO_AM_I | RequestResponse, &data))) {
    // Successfully read value from register and received ACK

    if (data == 0xB1) {
        LOG_Info("Received correct device ID!");
    }
}
result_t I2C_WriteRegister(I2C_Handle_t handle, uint8_t address, uint8_t reg, uint8_t data)

Writes one byte into a register of an I2C device.

Parameters
  • address – Device address

  • reg – Register address

  • data – Data to write

Returns

Status result

result_t I2C_ReadRegister(I2C_Handle_t handle, uint8_t address, uint8_t reg, uint8_t *data)

Reads one byte from a register of an I2C device.

Parameters
  • address – Device address

  • reg – Register address

  • data – Pointer to where read byte should be written to

Returns

Status result