Android 下Linux的I2C 读写函数实例


*******************************************************
功能:
读取从机数据
每个读操作用两条i2c_msg组成,第1条消息用于发送从机地址,
第2条用于发送读取地址和取回数据;每条消息前发送起始信号
参数:
client: i2c设备,包含设备地址
buf[0]: 首字节为读取地址
buf[1]~buf[len]:数据缓冲区
len: 读取数据长度
return:
执行消息数
*********************************************************/
/*Function as i2c_master_send */
static int i2c_read_bytes(struct i2c_client *client, uint8_t *buf, int len)
{
struct i2c_msg msgs[2];
int ret=-1;
//发送写地址
msgs[0].flags=!I2C_M_RD;//写消息
msgs[0].addr=client->addr;
msgs[0].len=2;
msgs[0].buf=&buf[0];
//接收数据
msgs[1].flags=I2C_M_RD;//读消息
msgs[1].addr=client->addr;
msgs[1].len=len-2;
msgs[1].buf=&buf[2];

ret=i2c_transfer(client->adapter,msgs, 2);
return ret;
}


/*******************************************************
功能:
向从机写数据
参数:
client: i2c设备,包含设备地址
buf[0]: 首字节为写地址
buf[1]~buf[len]:数据缓冲区
len: 数据长度
return:
执行消息数
*******************************************************/
/*Function as i2c_master_send */
static int i2c_write_bytes(struct i2c_client *client,uint8_t *data,int len)
{
struct i2c_msg msg;
int ret=-1;
//发送设备地址
msg.flags=!I2C_M_RD;//写消息
msg.addr=client->addr;
msg.len=len;
msg.buf=data;

ret=i2c_transfer(client->adapter,&msg, 1);
return ret;
}

相关内容