i2c是使用非常广泛的通信协议,tp,sensor都用它,今天就来熟悉总结一下i2c的使用
//i2c 写操作
static int my_i2c_write(struct i2c_client *client, u8 addr, u8 *pdata, int datalen)
{
int ret = 0;
unsigned int write_buf_len = 0;
u8 write_buf[128] = {0};
if (datalen > 125)
{
return -1;
}
write_buf[0] = addr; // 存入寄存器地址
write_buf_len++;
memcpy(&write_buf[write_buf_len], pdata, datalen); //存入要传输的数据
write_buf_len += datalen;
ret = i2c_master_send(client, write_buf, write_buf_len); //发送
return ret;
}
//i2c 读操作
static int my_i2c_read(struct i2c_client *client, u8 addr, u8 *pdata, unsigned int datalen)
{
int ret = 0;
ret = my_i2c_write(client, addr, NULL, 0); //先通过写入通知主机要接收数据
if (ret < 0)
{
print_info("%s set data address fail!\n", __func__);
return ret;
}
return i2c_master_recv(client, pdata, datalen); //接收
}
//i2c 设备注册
struct my_i2c_data { //自定义数据结构
}
static int __devinit my_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc;
struct my_i2c_data *my_data;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { //判定适配器能力I2C_FUNC_I2C
dev_err(&client->dev, "I2C functionality not supported\n");
return -ENODEV;
}
my_data = kzalloc(sizeof(*my_data), GFP_KERNEL); //为自定义数据分配内存
i2c_set_clientdata(client, my_data); //数据和client绑定
}
static struct i2c_driver my_i2c_driver = {
.driver = {
.name = "my_i2c",
.owner = THIS_MODULE,
},
.probe = my_i2c_probe, //probe函数
};
static int __init my_i2c_init(void)
{
return i2c_add_driver(&my_i2c_driver); //注册设备
}
static void __exit my_i2c_exit(void)
{
i2c_del_driver(&my_i2c_driver);
return;
}
module_init(my_i2c_init);
module_exit(my_i2c_exit);
设备的注册跟硬件平台是有很大关系的,比如高通和MTK,会有些细节不一样。