Implemented first Hangar-Service

Dependencies:   CalibrateMagneto QuaternionMath

Fork of SML2 by TobyRich GmbH

I2CPeripheral.cpp

Committer:
pvaibhav
Date:
2015-05-27
Revision:
46:fd5a62296b12
Parent:
7:604a8369b801

File content as of revision 46:fd5a62296b12:

#include "I2CPeripheral.h"
#include "mbed.h"
#define DEBUG "I2CPeripheral"
#include "Logger.h"

I2CPeripheral::I2CPeripheral(I2C &i2c, const uint8_t address) : mBus(&i2c), mAddress(address)
{
    LOG("Initialised with ADDR=0x%02X", mAddress);
}

void I2CPeripheral::write_reg(const uint8_t reg, const uint8_t val)
{
    char data[2];
    data[0] = reg;
    data[1] = val;
    if (mBus->write(mAddress, data, 2)) {
        ERR("Write failed, addr=0x%02x, reg=%02Xh, data=%02Xh", mAddress, reg, val);
    }
}

uint8_t I2CPeripheral::read_reg(const uint8_t reg)
{
    uint8_t byte;
    read_reg(reg, &byte, 1);
    return byte;
}

void I2CPeripheral::read_reg(const uint8_t reg, uint8_t* destination, const size_t nBytes)
{
    // Note about error checking - this function runs in a tight inner loop at 200 Hz or higher.
    // Therefore, checking for success and showing error message was removed.
    mBus->write(mAddress, (const char*)&reg, 1, true);
    // For reasons not known to me, the read() function also seems to require repeated start 'true'
    mBus->read(mAddress, (char*)destination, nBytes, true);
    mBus->stop();
}