已aw9523b 为例
模块初始化,卸载入口
module_init(aw9523b_init);
module_exit(aw9523b_exit);
static int __init aw9523b_init(void)
{
char ret=0;
ret=i2c_add_driver(&aw9523b_driver);
if(ret==0){
printk("success\n");
}else{
printk("failed\n");
}
}
static void __exit aw9523b_exit(void)
{
i2c_del_driver(&aw9523b_driver);
}
调用i2c_driver 的结构体,填写name,match_table,相关prob函数
static struct i2c_driver aw9523b_driver={
.driver={
.name = "aw9523b", //name 匹配
#ifdef CONFIG_OF
.of_match_table = aw9523b_of_match,
#endif
},
.probe=aw9523b_driver_probe, //匹配成功后会调用probe函数
.id_table=aw9523b_i2c_id, //id匹配
};
声明 i2c相关结构体 的名字
static struct i2c_client *new_client; //i2c_master_send 中作为参数使用
static const struct i2c_device_id aw9523b_i2c_id[]={{"aw9523b",0},{}}; //i2c_driver 用
#ifdef CONFIG_OF //和dtb匹配时
static const struct of_device_id aw9523b_of_match[]={
{.compatible="mediatek,AW9523B"},
{},
};
#endif
prob中写地址等
static int aw9523b_driver_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
new_client = client;
new_client->addr = 0x5b; //7bit地址
}
读写函数
int aw9523b_read_byte(unsigned char cmd, unsigned char *returnData)
{
char cmd_buf[1] = { 0x00 };
char readData = 0;
int ret = 0;
//mutex_lock(&aw9523b_i2c_access);
new_client->ext_flag =
((new_client->ext_flag) & I2C_MASK_FLAG) | I2C_WR_FLAG | I2C_DIRECTION_FLAG;
cmd_buf[0] = cmd;
ret = i2c_master_send(new_client, &cmd_buf[0], (1 << 8 | 1));
if (ret < 0) {
new_client->ext_flag = 0;
//mutex_unlock(&aw9523b_i2c_access);
return 0;
}
readData = cmd_buf[0];
*returnData = readData;
new_client->ext_flag = 0;
//mutex_unlock(&aw9523b_i2c_access);
return 1;
}
int aw9523b_write_byte(unsigned char cmd, unsigned char writeData)
{
char write_data[2] = { 0 };
int ret = 0;
//mutex_lock(&aw9523b_i2c_access);
write_data[0] = cmd;
write_data[1] = writeData;
new_client->ext_flag = ((new_client->ext_flag) & I2C_MASK_FLAG) | I2C_DIRECTION_FLAG;
ret = i2c_master_send(new_client, write_data, 2);
if (ret < 0) {
new_client->ext_flag = 0;
//mutex_unlock(&aw9523b_i2c_access);
return 0;
}
new_client->ext_flag = 0;
//mutex_unlock(&aw9523b_i2c_access);
return 1;
}