Problems about using I2C.h

When I use class I2C to create an object, I see there are only few functions and I wonder if these functions satisfy all the operation of I2C. For example, how can I read specific register of a slave(In the function,2,3,4), non of the four parameters related to register address )


you have to understand how your slave works, so you need open and read datasheet of your slave device where you will probably see a description about serial i2c communication.

Usually it works like in this example (not real code)

int slaveaddress = 0x44<<1
char readBuffer[6]
char wrireBuffer[2];
data[0] = 0x01 // this represent a comand for read
data[1] = 0x05 // this represent an address of a register from where you want read
if(i2c.wrire(slaveAddress, wrireBuffer,sizeof(wrireBuffer))){
   thread_sleep_for(200); //small delay according to datasheet of your slave,readBuffer,sizeof(readBuffer));
   // here process and clean the readBuffer

I2C - API references and tutorials | Mbed OS 6 Documentation

BR, Jan

Thanks for your reply. I 've had some understanding. However, I 'm still confused. For I2C protocol, the first byte is divided into two parts. First 7 bits are the address of slave and last bit indicate if the master want to read or write. However, in your code, the bit that indicate if the master wants to read or write seems to be sent in second byte because you use sizeof() and it refers to how many bytes are sent. But you did use 0x44 << 1 which means the address for the slave is the first seven bits. So …How is it work? Is your command 0x01 in first byte or second byte?

You are right address is 7 bits and 1 bit is for direction, that is the reason why have to be the address bitshifted to left for making space for that direction bit. The state of the direction bit is changed by I2C API automatically according to what method (read/write) you call.

The sizeof() gives information about how many data bytes you will sent but first address byte is not included in this. Address byte is separeted from data.

BR, Jan

Got it. The last bit of the first byte is based on the function I call. When I just saw your note for code, “for read” made me think that it means master wants to read. So, what does 0x01 means? Just a data for slave and have nothing to do with read/write of master.

Gaining a lot from you. Best wishes.

Great ! Thanks for sharing .