驱动怎么拿到设备树中iic地址
时间: 2024-03-09 21:45:49 浏览: 53
在设备树中,I2C设备节点通常会定义一个属性 `reg`,该属性的值指定了I2C设备在总线上的地址信息。对于I2C设备而言,`reg` 属性通常包含两个值,第一个值是设备在I2C总线上的地址,第二个值是设备的寄存器地址。例如,下面是一个示例设备树节点:
```
i2c_device@50 {
compatible = "vendor,device";
reg = <0x50 0x00>;
};
```
在这个示例中,设备节点的名称是 `i2c_device`,它的I2C地址是 `0x50`,寄存器地址是 `0x00`。因此,在驱动程序中,可以通过调用 `devm_i2c_new_device()` 函数来注册I2C设备,并传递设备树节点中的 `reg` 属性值。
```c
static const struct of_device_id i2c_device_of_match[] = {
{ .compatible = "vendor,device" },
{ },
};
static int i2c_device_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
/* 读取设备树中的I2C地址信息 */
struct device_node *np = client->dev.of_node;
u32 reg[2];
int ret;
ret = of_property_read_u32_array(np, "reg", reg, ARRAY_SIZE(reg));
if (ret < 0) {
dev_err(&client->dev, "failed to read I2C address\n");
return ret;
}
/* 注册I2C设备 */
struct i2c_board_info board_info = {
.type = "i2c_device",
.addr = reg[0],
};
struct device *dev = &client->dev;
struct i2c_adapter *adapter = client->adapter;
struct i2c_client *new_client;
new_client = i2c_new_device(adapter, &board_info);
if (!new_client) {
dev_err(dev, "failed to register I2C device\n");
return -ENODEV;
}
/* 存储设备信息 */
struct i2c_device_data *data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);
if (!data) {
dev_err(dev, "failed to allocate memory\n");
return -ENOMEM;
}
data->i2c_client = new_client;
data->reg_addr = reg[1];
/* 存储设备数据 */
i2c_set_clientdata(new_client, data);
/* 配置设备 */
i2c_device_setup(new_client);
dev_info(dev, "I2C device registered: %s\n", new_client->name);
return 0;
}
static struct i2c_driver i2c_device_driver = {
.driver = {
.name = "i2c_device",
.of_match_table = i2c_device_of_match,
},
.probe = i2c_device_probe,
.remove = i2c_device_remove,
.id_table = i2c_device_id,
};
```
阅读全文