Linux kernel I2C 调用接口汇总

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 *)&reg,
        },
        {
            .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调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值