1 // SPDX-License-Identifier: GPL-2.0+
3 * ADE7854/58/68/78 Polyphase Multifunction Energy Metering IC Driver (I2C Bus)
5 * Copyright 2010 Analog Devices Inc.
8 #include <linux/device.h>
9 #include <linux/kernel.h>
10 #include <linux/i2c.h>
11 #include <linux/slab.h>
12 #include <linux/module.h>
14 #include <linux/iio/iio.h>
17 static int ade7854_i2c_write_reg(struct device *dev,
24 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
25 struct ade7854_state *st = iio_priv(indio_dev);
27 mutex_lock(&st->buf_lock);
28 st->tx[0] = (reg_address >> 8) & 0xFF;
29 st->tx[1] = reg_address & 0xFF;
33 st->tx[2] = val & 0xFF;
37 st->tx[2] = (val >> 8) & 0xFF;
38 st->tx[3] = val & 0xFF;
42 st->tx[2] = (val >> 16) & 0xFF;
43 st->tx[3] = (val >> 8) & 0xFF;
44 st->tx[4] = val & 0xFF;
48 st->tx[2] = (val >> 24) & 0xFF;
49 st->tx[3] = (val >> 16) & 0xFF;
50 st->tx[4] = (val >> 8) & 0xFF;
51 st->tx[5] = val & 0xFF;
59 ret = i2c_master_send(st->i2c, st->tx, count);
62 mutex_unlock(&st->buf_lock);
64 return ret < 0 ? ret : 0;
67 static int ade7854_i2c_read_reg(struct device *dev,
72 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
73 struct ade7854_state *st = iio_priv(indio_dev);
76 mutex_lock(&st->buf_lock);
77 st->tx[0] = (reg_address >> 8) & 0xFF;
78 st->tx[1] = reg_address & 0xFF;
80 ret = i2c_master_send(st->i2c, st->tx, 2);
84 ret = i2c_master_recv(st->i2c, st->rx, bits);
93 *val = (st->rx[0] << 8) | st->rx[1];
96 *val = (st->rx[0] << 16) | (st->rx[1] << 8) | st->rx[2];
99 *val = (st->rx[0] << 24) | (st->rx[1] << 16) |
100 (st->rx[2] << 8) | st->rx[3];
108 mutex_unlock(&st->buf_lock);
112 static int ade7854_i2c_probe(struct i2c_client *client,
113 const struct i2c_device_id *id)
115 struct ade7854_state *st;
116 struct iio_dev *indio_dev;
118 indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*st));
121 st = iio_priv(indio_dev);
122 i2c_set_clientdata(client, indio_dev);
123 st->read_reg = ade7854_i2c_read_reg;
124 st->write_reg = ade7854_i2c_write_reg;
126 st->irq = client->irq;
128 return ade7854_probe(indio_dev, &client->dev);
131 static const struct i2c_device_id ade7854_id[] = {
138 MODULE_DEVICE_TABLE(i2c, ade7854_id);
140 static struct i2c_driver ade7854_i2c_driver = {
144 .probe = ade7854_i2c_probe,
145 .id_table = ade7854_id,
147 module_i2c_driver(ade7854_i2c_driver);
149 MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
150 MODULE_DESCRIPTION("Analog Devices ADE7854/58/68/78 Polyphase Multifunction Energy Metering IC I2C Driver");
151 MODULE_LICENSE("GPL v2");