A I2C-Dev like library which can be used with different kinds of sensors.
Used in:
- BNO055 - Link
Diff: i2c_master.cpp
- Revision:
- 0:0af6c7cf0ed3
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/i2c_master.cpp Thu Jul 11 09:35:55 2019 +0000 @@ -0,0 +1,60 @@ +#include "mbed.h" +#include "i2c_master.h" + +I2C_Master::I2C_Master(PinName sda, PinName scl, uint32_t frequency) : + m_i2c_sensor(sda, scl) +{ + + m_i2c_sensor.frequency(frequency); +} + +void I2C_Master::i2c_write(uint8_t i2c_address, uint8_t slave_address, const uint8_t data) +{ + char writeArray[2] = {slave_address, data}; + m_i2c_sensor.write(i2c_address, writeArray, 2, false); +} + +void I2C_Master::i2c_writeBits(uint8_t i2c_address, uint8_t slave_address, const uint8_t data, uint8_t mask) +{ + char current_value; + char writeArray[2] = {slave_address, data}; + + //Get current value of desired register and mask it with mask-value + current_value = i2c_read(i2c_address, slave_address); + current_value &= ~mask; + + //Combine Data with the new data (additionaly masking the data) and send it to the Sensor + writeArray[1] = current_value | (data & mask); + + m_i2c_sensor.write(i2c_address, writeArray, 2, false); +} + +void I2C_Master::i2c_readSeries(uint8_t i2c_address, uint8_t slave_address, uint8_t *data, uint8_t length) +{ + char *data_array; + data_array = reinterpret_cast<char*>(data); + + const char temp_address = slave_address; + + m_i2c_sensor.write(i2c_address, &temp_address, 1, true); + m_i2c_sensor.read(i2c_address, data_array,length, false); +} + +uint8_t I2C_Master::i2c_read(uint8_t i2c_address, uint8_t slave_address) +{ + char data; + const char temp_address = slave_address; + m_i2c_sensor.write(i2c_address, &temp_address, 1, true); + m_i2c_sensor.read(i2c_address, &data, 1, false); + return data; +} + +uint8_t I2C_Master::i2c_readBits(uint8_t i2c_address, uint8_t slave_address, uint8_t mask) +{ + char data; + const char temp_address = slave_address; + m_i2c_sensor.write(i2c_address, &temp_address, 1, true); + m_i2c_sensor.read(i2c_address, &data, 1, false); + return data & mask; +} +