1.i2c_smbus:
i2c_smbus_read_byte_data,i2c_smbus_write_byte_data
i2c_smbus_write_byte_data(client, reg, val);
*val = i2c_smbus_read_byte_data(client, reg); val 为返回寄存器值
同时也有支持块读写的接口:
i2c_smbus_read_block_data,i2c_smbus_write_block_data
2.i2c_transfer:
static int max96745_reg_read(struct i2c_client *client, int reg, u8 *val)
{
int ret;
struct i2c_msg msg[] = {
{
.addr = client->addr,
.flags = 0,
.len = 1,
.buf = (u8 *)®,
},
{
.addr = client->addr,
.flags = I2C_M_RD,
.len = 1,
.buf = val,
},
};
reg = swab16(reg);
ret = i2c_transfer(client->adapter, msg, 2);
if (ret < 0) {
dev_err(&client->dev, "Failed reading register 0x%04x!\n", reg);
return ret;
}
return 0;
}
static int max96745_reg_write(struct i2c_client *client, int reg, u8 val)
{
struct i2c_msg msg;
struct {
u16 reg;
u8 val;
} __packed buf;
int ret;
reg = swab16(reg);
buf.reg = reg;
buf.val = val;
msg.addr = client->addr;
msg.flags = 0;
msg.len = 2;
msg.buf = (u8 *)&buf;
ret = i2c_transfer(client->adapter, &msg, 1);
if (ret < 0) {
dev_err(&client->dev, "Failed writing register 0x%04x!\n", reg);
return ret;
}
return 0;
}
需要注意读写函数的 len值, write 值写入2,read 写入两次1,还需要注意flag 标识;
3.i2c_master_send & i2c_master_recv
static int max96745_reg_write(struct i2c_client *client, int addr, u8 val)
{
uint8_t buf[] = {addr, val};
int ret;
ret = i2c_master_send(client, buf, ARRAY_SIZE(buf));
if (ret < 0)
printk("Error %d writing to subaddress 0x%x\n",
ret, addr);
return ret;
}
static int max96745_reg_read(struct i2c_client *client, char addr, u8 *val)
{
int ret;
ret = i2c_master_send(client, &addr, sizeof(addr));
if (ret < 0)
goto fail;
ret = i2c_master_recv(client, val, sizeof(val));
if (ret < 0)
goto fail;
return ret;
fail:
printk("Error %d reading from subaddress 0x%x\n",
ret, addr);
return 0;
}
read 需要先执行send,然后执行recv调用。