Difference between revisions of "I2C driver"

[quality revision] [pending revision]
m (Replaced content with "<noinclude> {{ArticleMainWriter|Pierre-YvesM}} {{ArticleApprovedVersion | Jean-ChristopheT | Nobody | No previous approved version | Automatic approval (article under cons...")
(Tag: Replaced)
m
 


Under construction.png Coming soon

1 Register/Unregister i2c driver[edit]

To register an i2c driver with i2c-core, the i2c_add_driver(struct i2c_driver *driver) function is used :


static int __init sample_init_driver(void)
{
	return(i2c_add_driver(&sample_driver));
}

Unregister i2c driver using i2c_del_driver(struct i2c_driver *driver) :


static void __exit sample_exit_driver(void)
{
	i2c_del_driver(&sample_driver);
}


<div class="NavFrame collapsed">
  <div class="NavHead">'''Struct i2c_driver''' in detail found on {{Red| /linux/i2c.h}}</div>
  <div class="NavContent">
<div style="overflow:auto; height:25em;">

/**
 * struct i2c_driver - represent an I2C device driver
 * @class: What kind of i2c device we instantiate (for detect)
 * @attach_adapter: Callback for bus addition (deprecated)
 * @probe: Callback for device binding
 * @remove: Callback for device unbinding
 * @shutdown: Callback for device shutdown
 * @alert: Alert callback, for example for the SMBus alert protocol
 * @command: Callback for bus-wide signaling (optional)
 * @driver: Device driver model driver
 * @id_table: List of I2C devices supported by this driver
 * @detect: Callback for device detection
 * @address_list: The I2C addresses to probe (for detect)
 * @clients: List of detected clients we created (for i2c-core use only)
 *
 * The driver.owner field should be set to the module owner of this driver.
 * The driver.name field should be set to the name of this driver.
 *
 * For automatic device detection, both @detect and @address_list must
 * be defined. @class should also be set, otherwise only devices forced
 * with module parameters will be created. The detect function must
 * fill at least the name field of the i2c_board_info structure it is
 * handed upon successful detection, and possibly also the flags field.
 *
 * If @detect is missing, the driver will still work fine for enumerated
 * devices. Detected devices simply won't be supported. This is expected
 * for the many I2C/SMBus devices which can't be detected reliably, and
 * the ones which can always be enumerated in practice.
 *
 * The i2c_client structure which is handed to the @detect callback is
 * not a real i2c_client. It is initialized just enough so that you can
 * call i2c_smbus_read_byte_data and friends on it. Don't do anything
 * else with it. In particular, calling dev_dbg and friends on it is
 * not allowed.
 */
struct i2c_driver {
	unsigned int class;

	/* Notifies the driver that a new bus has appeared. You should avoid
	 * using this, it will be removed in a near future.
	 */
	int (*attach_adapter)(struct i2c_adapter *) __deprecated;

	/* Standard driver model interfaces */
	int (*probe)(struct i2c_client *, const struct i2c_device_id *);
	int (*remove)(struct i2c_client *);

	/* driver model interfaces that don't relate to enumeration  */
	void (*shutdown)(struct i2c_client *);

	/* Alert callback, for example for the SMBus alert protocol.
	 * The format and meaning of the data value depends on the protocol.
	 * For the SMBus alert protocol, there is a single bit of data passed
	 * as the alert response's low bit ("event flag").
	 */
	void (*alert)(struct i2c_client *, unsigned int data);

	/* a ioctl like command that can be used to perform specific functions
	 * with the device.
	 */
	int (*command)(struct i2c_client *client, unsigned int cmd, void *arg);

	struct device_driver driver;
	const struct i2c_device_id *id_table;

	/* Device detection callback for automatic device creation */
	int (*detect)(struct i2c_client *, struct i2c_board_info *);
	const unsigned short *address_list;
	struct list_head clients;
};

</div>
</div>
</div>

Minimal configuration can be :


static const struct i2c_device_id sample_device_id[] = {
	{ "dummy_device", 0 },
	{ }
};

static struct i2c_driver sample_driver = {
	.probe    = sample_driver_probe,
	.remove   = sample_driver_remove,
	.id_table = sample_device_id,
	.driver   = {
		.name = "sample driver example",
	},
};

probe is called when a peripheral is bind with the driver.
remove is the opposite of probe function.
id_table lists all peripherals matching with this driver.
driver are driver characteristics (its name for example).
Further structure details here.

2 Bind/Unbind a peripheral[edit]

When an I2C peripheral is found and matching with the driver id_table, probe function is called from i2c-core :


static int sample_driver_probe(struct i2c_client *client,
			const struct i2c_device_id *id)
{
	struct private_data *dev;

	if (!i2c_check_functionality(client->adapter,
		I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
		I2C_FUNC_SMBUS_I2C_BLOCK))
		return -ENODEV;

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (dev == NULL)
		return -ENOMEM;

	/* Set private data */
	i2c_set_clientdata(client, dev);

	return 0;
}

Passed along as a parameter to the probe function is a struct i2c_client structure that represents our I2C slave chip.
Typically a probe function will detect the compatibility between the I2C bus adapter and the I2C peripheral and allocate memory for the peripheral.
In order to check a functionality of the adapter, the i2c_check_functionality function is used with all functionality located at /Documentation/i2c/functionality.
i2c_set_clientdata function is used to set peripheral private data under an i2c_client structure to be able to retrieve it with i2c_get_clientdata.

When an I2C peripheral is unbind with the driver, remove function is called :


static int sample_driver_remove(struct i2c_client *client)
{
	struct private_data *dev;

	/* Get private data */
	dev = i2c_get_clientdata(client);
	kfree(dev);

	return 0;
}

At remove time, release the peripheral memory allocated in probe function.

3 Access I2C peripheral data[edit]

After probing success, read and write peripheral registers using different methods

3.1 SMBus commands[edit]


<div class="NavFrame collapsed">
  <div class="NavHead">SMBus command prototypes from {{Red| /linux/i2c.h}}</div>
  <div class="NavContent">
<div style="overflow:auto; height:25em;">

/* This is the very generalized SMBus access routine. You probably do not
   want to use this, though; one of the functions below may be much easier,
   and probably just as fast.
   Note that we use i2c_adapter here, because you do not need a specific
   smbus adapter to call this function. */
extern s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
			  unsigned short flags, char read_write, u8 command,
			  int size, union i2c_smbus_data *data);

/* Now follow the 'nice' access routines. These also document the calling
   conventions of i2c_smbus_xfer. */

extern s32 i2c_smbus_read_byte(const struct i2c_client *client);
extern s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value);
extern s32 i2c_smbus_read_byte_data(const struct i2c_client *client,
				    u8 command);
extern s32 i2c_smbus_write_byte_data(const struct i2c_client *client,
				     u8 command, u8 value);
extern s32 i2c_smbus_read_word_data(const struct i2c_client *client,
				    u8 command);
extern s32 i2c_smbus_write_word_data(const struct i2c_client *client,
				     u8 command, u16 value);

static inline s32
i2c_smbus_read_word_swapped(const struct i2c_client *client, u8 command)
{
	s32 value = i2c_smbus_read_word_data(client, command);

	return (value < 0) ? value : swab16(value);
}

static inline s32
i2c_smbus_write_word_swapped(const struct i2c_client *client,
			     u8 command, u16 value)
{
	return i2c_smbus_write_word_data(client, command, swab16(value));
}

/* Returns the number of read bytes */
extern s32 i2c_smbus_read_block_data(const struct i2c_client *client,
				     u8 command, u8 *values);
extern s32 i2c_smbus_write_block_data(const struct i2c_client *client,
				      u8 command, u8 length, const u8 *values);
/* Returns the number of read bytes */
extern s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client,
					 u8 command, u8 length, u8 *values);
extern s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client,
					  u8 command, u8 length,
					  const u8 *values);

</div>
</div>
</div>

If SMBus functionality is enable, access peripheral registers with a set of SMBus commands.
All functions are described at /Documentation/i2c/writing-clients.


/* Read a byte */
char value;
u8 registerAddr = 0xXX;             /* XX is the register peripheral address */
value = i2c_smbus_read_byte_data(client, registerAddr);

/* Write a byte */
char registerAddr = 0XX;             /* XX is the register peripheral address */
char value = 0xXX;                   /* XX is the value to write */
int err;
err = i2c_smbus_write_byte_data(client, registerAddr, value);

3.2 i2c_master_send / i2c_master_recv[edit]

Use i2c_master_send to set the index reader position at the register address to read and use i2c_master_recv to read data from the index reader.
Both functions return negative errno, or else the number of bytes write/read.


int set_pointer(struct i2c_client *client, u8 addr)
{
	int ret;
	ret = i2c_master_send(client, &addr, 1);
	if (ret != 1)
		dev_err(&client->dev, "Failed to perform i2c_master_send\n");

	return ret;
}

int read_register(struct i2c_client *client, u8 addr, u8 *buf)
{
	int ret = 0;

	ret = set_pointer(client, addr);
	if (ret < 0)
		return ret;

	ret = i2c_master_recv(client, buf, 1);
	if (ret != 1)
		dev_err(&client->dev, "Failed to perform i2c_master_recv\n");

	return ret;
}

int write_register(struct i2c_client *client, u8 addr, u8 value)
{
	int ret;
	u8 buf[2];
	buf[0] = addr;
	buf[1] = value;

	ret = i2c_master_send(client, buf, 2);
	if (ret < 0)
		dev_err(&client->dev, "Failed to perform i2c_master_send\n");

	return ret;
}

3.3 i2c_transfer[edit]


<div class="NavFrame collapsed">
  <div class="NavHead">'''Struct i2c_msg''' in detail found on {{Red| /uapi/linux/i2c.h}}</div>
  <div class="NavContent">
<div style="overflow:auto; height:25em;">

/**
 * struct i2c_msg - an I2C transaction segment beginning with START
 * @addr: Slave address, either seven or ten bits.  When this is a ten
 *	bit address, I2C_M_TEN must be set in @flags and the adapter
 *	must support I2C_FUNC_10BIT_ADDR.
 * @flags: I2C_M_RD is handled by all adapters.  No other flags may be
 *	provided unless the adapter exported the relevant I2C_FUNC_*
 *	flags through i2c_check_functionality().
 * @len: Number of data bytes in @buf being read from or written to the
 *	I2C slave address.  For read transactions where I2C_M_RECV_LEN
 *	is set, the caller guarantees that this buffer can hold up to
 *	32 bytes in addition to the initial length byte sent by the
 *	slave (plus, if used, the SMBus PEC); and this value will be
 *	incremented by the number of block data bytes received.
 * @buf: The buffer into which data is read, or from which it's written.
 *
 * An i2c_msg is the low level representation of one segment of an I2C
 * transaction.  It is visible to drivers in the @i2c_transfer() procedure,
 * to userspace from i2c-dev, and to I2C adapter drivers through the
 * @i2c_adapter.@master_xfer() method.
 *
 * Except when I2C "protocol mangling" is used, all I2C adapters implement
 * the standard rules for I2C transactions.  Each transaction begins with a
 * START.  That is followed by the slave address, and a bit encoding read
 * versus write.  Then follow all the data bytes, possibly including a byte
 * with SMBus PEC.  The transfer terminates with a NAK, or when all those
 * bytes have been transferred and ACKed.  If this is the last message in a
 * group, it is followed by a STOP.  Otherwise it is followed by the next
 * @i2c_msg transaction segment, beginning with a (repeated) START.
 *
 * Alternatively, when the adapter supports I2C_FUNC_PROTOCOL_MANGLING then
 * passing certain @flags may have changed those standard protocol behaviors.
 * Those flags are only for use with broken/nonconforming slaves, and with
 * adapters which are known to support the specific mangling options they
 * need (one or more of IGNORE_NAK, NO_RD_ACK, NOSTART, and REV_DIR_ADDR).
 */
struct i2c_msg {
	__u16 addr;	/* slave address			*/
	__u16 flags;
#define I2C_M_TEN		0x0010	/* this is a ten bit chip address */
#define I2C_M_RD		0x0001	/* read data, from slave to master */
#define I2C_M_STOP		0x8000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NOSTART		0x4000	/* if I2C_FUNC_NOSTART */
#define I2C_M_REV_DIR_ADDR	0x2000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_IGNORE_NAK	0x1000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NO_RD_ACK		0x0800	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_RECV_LEN		0x0400	/* length will be first received byte */
	__u16 len;		/* msg length				*/
	__u8 *buf;		/* pointer to msg data			*/
};

</div>
</div>
</div>

i2c_transfer executes a single or combined I2C message.
Note that there is no requirement that each message be sent to the same slave address, although that is the most common model.
Returns negative errno, else the number of messages executed.
See https://www.kernel.org/doc/htmldocs/device-drivers/API-i2c-transfer.html.

As i2c_master_send and i2c_master_recv functions, first message will set the index reader position and second message will store data from the index reader.


u8 registerAddr = 0xXX;             /* XX is the register peripheral address */
u8 value;

struct i2c_msg msg[2] = {
	{
		.addr = client->addr,
		.flags = 0,
		.len = 1,
		.buf = &registerAddr,
	},
	{
		.addr = client->addr,
		.flags = I2C_M_RD,
		.len = 1,
		.buf = &value,
	},
};

ret = i2c_transfer(client->adapter, msg, 2);
if (ret != 2)
        dev_err(&client->dev, "Failed to perform i2c_transfer\n");

4 Documentations and programming examples[edit]

Brief tutorial :
http://renjucnair.blogspot.fr/2012/01/writing-i2c-client-driver.html

Further functions descriptions :
http://www.embedded-bits.co.uk/2009/i2c-in-the-2632-linux-kernel

Code example :
https://code.google.com/archive/p/ldd-templates/source/default/source

4.1 API[edit]

https://www.kernel.org/doc/htmldocs/device-drivers/i2c.html

4.2 Full example[edit]

Implementation architecture

The driver example below communicates with a sensor expansion board for STM32 Nucleo.
This board contains four sensor communicating via I2C :

  • A capacitive digital sensor for relative humidity and temperature (HTS221),
  • A 3D accelerometer and 3D gyroscope (LSM6DS0),
  • A 3D magnetometer (LIS3MDL),
  • And a pressure sensor (LPS25HB).

This example informs the user if all peripherals included on the expansion board are correctly detected by reading their name registers.
When a peripheral is bound with the driver, the probe function reads its register name and detects if is the good one or not.
Instantiation of all peripherals into the device tree looks like :


i2c@9842000 {
	status = "okay";

	lsm6ds0@6b {
		compatible = "nucleo";
		reg = <0x6b>;
	};
	hts221@5f {
		compatible = "nucleo";
		reg = <0x5f>;
	};
	lps25hb@5d {
		compatible = "nucleo";
		reg = <0x5d>;
	};
	lis3mdl@1e {
		compatible = "nucleo";
		reg = <0x1e>;
	};
};

Result of the driver can be :


dmesg
nucleo driver 0-006b: [SUCCESS]The device LSM6DS0 is correctly detected
nucleo driver 0-005f: [SUCCESS]The device HTS221  is correctly detected
nucleo driver 0-005d: [SUCCESS]The device LPS25HB is correctly detected
nucleo driver 0-001e: [SUCCESS]The device LIS3MDL is correctly detected

or,


dmesg
nucleo driver 0-006b: [FAILED]The device is not detected, ID = 0x0
nucleo driver 0-005f: [FAILED]The device is not detected, ID = 0x0
nucleo driver 0-005d: [FAILED]The device is not detected, ID = 0x0
nucleo driver 0-001e: [FAILED]The device is not detected, ID = 0x0

GitHub of all sensor drivers : https://github.com/STMemsLinuxDrivers

download source code


<div class="NavFrame collapsed">
  <div class="NavHead">nucleo_driver.c source code</div>
  <div class="NavContent">
<div style="overflow:auto; height:25em;">

#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>

#define WHO_IS_IT_REG		0x0F

#define HTS221_ID			0xBC
#define LPS25HB_ID			0xBD
#define LSM6DS0_ID			0x68
#define LIS3MDL_ID			0x3D

struct nucleo_sensor {
	struct i2c_client *client;

	/* Add driver properties here */
};

static int nucleo_read_smbus(struct i2c_client *client, u8 addr, u8 *buf)
{
	return *buf = i2c_smbus_read_byte_data(client, addr);
}

static int nucleo_read_method1(struct i2c_client *client, u8 addr, u8 *buf)
{
	u8 out_buf = addr;
	int ret = 0;

	ret = i2c_master_send(client, &out_buf, 1);
	if (ret != 1) {
		dev_err(&client->dev, "Failed to perform i2c_master_send\n");
	} else {
		ret = i2c_master_recv(client, buf, 1);
		if (ret != 1)
			dev_err(&client->dev, "Failed to perform i2c_master_recv\n");
	}

	return ret;
}

static int nucleo_read_method2(struct i2c_client *client, u8 addr, u8 *buf)
{
	u8 out_buf = addr;
	struct i2c_msg msg[2] = {
		{
			.addr = client->addr,
			.flags = 0,
			.len = 1,
			.buf = &out_buf,
		},
		{
			.addr = client->addr,
			.flags = I2C_M_RD,
			.len = 1,
			.buf = buf,
		},
	};

	return i2c_transfer(client->adapter, msg, 2);
}

static int nucleo_sensor_probe(struct i2c_client *client,
			const struct i2c_device_id *id)
{
	struct nucleo_sensor *dev;
	u8 who_is_it = 0x00;
	int ret = 0;

	if (!i2c_check_functionality(client->adapter,
		I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
		I2C_FUNC_SMBUS_I2C_BLOCK))
		return -ENODEV;

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (dev == NULL)
		return -ENOMEM;

	dev->client = client;

	/* Set private data */
	i2c_set_clientdata(client, dev);

	/* First method read the device name register using
	 * i2c_smbus_read_byte_data function */
	ret = nucleo_read_smbus(client, WHO_IS_IT_REG, &who_is_it);
	if (ret < 0)
		dev_err(&client->dev, "Failed to read device using smbus command\n");

	/* Second method read the device name register using
	 * i2c_master_send and i2c_master_recv functions */
	ret = nucleo_read_method1(client, WHO_IS_IT_REG, &who_is_it);
	if (ret < 0)
		dev_err(&client->dev, "Failed to read device using method1\n");

	/* Third method read the device name register using
	 * i2c_transfer function */
	ret = nucleo_read_method2(client, WHO_IS_IT_REG, &who_is_it);
	if (ret < 0)
		dev_err(&client->dev, "Failed to read device using method2\n");

	switch (who_is_it) {
	case HTS221_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device HTS221  is correctly detected\n");
		break;
	case LPS25HB_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device LPS25HB is correctly detected\n");
		break;
	case LSM6DS0_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device LSM6DS0 is correctly detected\n");
		break;
	case LIS3MDL_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device LIS3MDL is correctly detected\n");
		break;
	default:
		dev_err(&client->dev,
			"[FAILED]The device is not detected, ID=0x%x\n",
			who_is_it);
	}

	return 0;
}

static int nucleo_sensor_remove(struct i2c_client *client)
{
	struct nucleo_sensor_temp *dev;

	/* Get private data */
	dev = i2c_get_clientdata(client);
	kfree(dev);

	return 0;
}

static const struct i2c_device_id nucleo_sensor_id[] = {
	{ "nucleo", 0 },
	{ }
};

static struct i2c_driver nucleo_sensor_driver = {
	.probe    = nucleo_sensor_probe,
	.remove   = nucleo_sensor_remove,
	.id_table = nucleo_sensor_id,
	.driver   = {
		.name = "nucleo driver",
	},
};

static int __init nucleo_sensor_init_driver(void)
{
	return i2c_add_driver(&nucleo_sensor_driver);
}

static void __exit nucleo_sensor_exit_driver(void)
{
	i2c_del_driver(&nucleo_sensor_driver);
}

module_init(nucleo_sensor_init_driver);
module_exit(nucleo_sensor_exit_driver);

MODULE_DESCRIPTION("nucleo_sensor client driver");
MODULE_LICENSE("GPL");

</div>
</div>
</div>

Help for compilation : BitBake_cheat_sheet

<noinclude>

{{ArticleMainWriter|Pierre-YvesM}}
{{ArticleApprovedVersion | Jean-ChristopheT | Nobody | No previous approved version | Automatic approval (article under construction) | 19Feb’19}}
[[Category:I2C]]</noinclude>

{{UnderConstruction}}{{ReviewsComments|FGA W839: Discussed in domain weekly: Article should be renamed either I2C device driver, or How to write an I2C device driver... or similar<br/>

Current "I2C driver" is confusing: other XXX Linux driver article exist, but deal with internal controller linux driver}}

== Register/Unregister i2c driver ==

To register an i2c driver with i2c-core, the '''i2c_add_driver(struct i2c_driver *driver)''' function is used :<pre class="brush:c; gutter:true; tab-size: 8">

static int __init sample_init_driver(void)
{
	return(i2c_add_driver(&sample_driver));
}</pre>


Unregister i2c driver using '''i2c_del_driver(struct i2c_driver *driver)''' :<pre class="brush:c; gutter:true; tab-size: 8">

static void __exit sample_exit_driver(void)
{
	i2c_del_driver(&sample_driver);
}</pre>

<pre class="brush:c; gutter:true; tab-size: 8">
<div class="NavFrame collapsed">
<div class="NavHead">'''Struct i2c_driver''' in detail found on {{Red| /linux/i2c.h}}</div>
<div class="NavContent">
<div style="overflow:auto; height:25em;">


/**
 * struct i2c_driver - represent an I2C device driver
 * @class: What kind of i2c device we instantiate (for detect)
 * @attach_adapter: Callback for bus addition (deprecated)
 * @probe: Callback for device binding
 * @remove: Callback for device unbinding
 * @shutdown: Callback for device shutdown
 * @alert: Alert callback, for example for the SMBus alert protocol
 * @command: Callback for bus-wide signaling (optional)
 * @driver: Device driver model driver
 * @id_table: List of I2C devices supported by this driver
 * @detect: Callback for device detection
 * @address_list: The I2C addresses to probe (for detect)
 * @clients: List of detected clients we created (for i2c-core use only)
 *
 * The driver.owner field should be set to the module owner of this driver.
 * The driver.name field should be set to the name of this driver.
 *
 * For automatic device detection, both @detect and @address_list must
 * be defined. @class should also be set, otherwise only devices forced
 * with module parameters will be created. The detect function must
 * fill at least the name field of the i2c_board_info structure it is
 * handed upon successful detection, and possibly also the flags field.
 *
 * If @detect is missing, the driver will still work fine for enumerated
 * devices. Detected devices simply won't be supported. This is expected
 * for the many I2C/SMBus devices which can't be detected reliably, and
 * the ones which can always be enumerated in practice.
 *
 * The i2c_client structure which is handed to the @detect callback is
 * not a real i2c_client. It is initialized just enough so that you can
 * call i2c_smbus_read_byte_data and friends on it. Don't do anything
 * else with it. In particular, calling dev_dbg and friends on it is
 * not allowed.
 */
struct i2c_driver {
	unsigned int class;

	/* Notifies the driver that a new bus has appeared. You should avoid
	 * using this, it will be removed in a near future.
	 */
	int (*attach_adapter)(struct i2c_adapter *) __deprecated;

	/* Standard driver model interfaces */
	int (*probe)(struct i2c_client *, const struct i2c_device_id *);
	int (*remove)(struct i2c_client *);

	/* driver model interfaces that don't relate to enumeration  */
	void (*shutdown)(struct i2c_client *);

	/* Alert callback, for example for the SMBus alert protocol.
	 * The format and meaning of the data value depends on the protocol.
	 * For the SMBus alert protocol, there is a single bit of data passed
	 * as the alert response's low bit ("event flag").
	 */
	void (*alert)(struct i2c_client *, unsigned int data);

	/* a ioctl like command that can be used to perform specific functions
	 * with the device.
	 */
	int (*command)(struct i2c_client *client, unsigned int cmd, void *arg);

	struct device_driver driver;
	const struct i2c_device_id *id_table;

	/* Device detection callback for automatic device creation */
	int (*detect)(struct i2c_client *, struct i2c_board_info *);
	const unsigned short *address_list;
	struct list_head clients;
};
</div>
</div>
</div>
</pre>


Minimal configuration can be :<pre class="brush:c; gutter:true; tab-size: 8">

static const struct i2c_device_id sample_device_id[] = {
	{ "dummy_device", 0 },
	{ }
};

static struct i2c_driver sample_driver = {
	.probe    = sample_driver_probe,
	.remove   = sample_driver_remove,
	.id_table = sample_device_id,
	.driver   = {
		.name = "sample driver example",
	},
};</pre>

'''probe''' is called when a peripheral is bind with the driver.<br />

'''remove''' is the opposite of '''probe''' function.<br />

'''id_table''' lists all peripherals matching with this driver.<br />

'''driver''' are driver characteristics (its name for example).<br />

Further structure details [https://www.kernel.org/doc/htmldocs/device-drivers/API-struct-i2c-driver.html here].

== Bind/Unbind a peripheral ==
When an I2C peripheral is found and matching with the driver '''id_table''', '''probe''' function is called from i2c-core :<pre class="brush:c; gutter:true; tab-size: 8">

static int sample_driver_probe(struct i2c_client *client,
			const struct i2c_device_id *id)
{
	struct private_data *dev;

	if (!i2c_check_functionality(client->adapter,
		I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
		I2C_FUNC_SMBUS_I2C_BLOCK))
		return -ENODEV;

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (dev == NULL)
		return -ENOMEM;

	/* Set private data */
	i2c_set_clientdata(client, dev);

	return 0;
}</pre>

Passed along as a parameter to the probe function is a '''struct i2c_client''' structure that represents our I2C slave chip.<br />

Typically a probe function will detect the compatibility between the I2C bus adapter and the I2C peripheral and allocate memory for the peripheral.<br />

In order to check a functionality of the adapter, the '''i2c_check_functionality''' function is used with all functionality located at [https://www.kernel.org/doc/Documentation/i2c/functionality /Documentation/i2c/functionality].<br />

'''i2c_set_clientdata''' function is used to set peripheral private data under an i2c_client structure to be able to retrieve it with '''i2c_get_clientdata'''.

When an I2C peripheral is unbind with the driver, '''remove''' function is called :<pre class="brush:c; gutter:true; tab-size: 8">

static int sample_driver_remove(struct i2c_client *client)
{
	struct private_data *dev;

	/* Get private data */
	dev = i2c_get_clientdata(client);
	kfree(dev);

	return 0;
}</pre>

At remove time, release the peripheral memory allocated in probe function.

== Access I2C peripheral data ==
After probing success, read and write peripheral registers using different methods

=== SMBus commands ===<pre class="brush:c; gutter:true; tab-size: 8">
<div class="NavFrame collapsed">
<div class="NavHead">SMBus command prototypes from {{Red| /linux/i2c.h}}</div>
<div class="NavContent">
<div style="overflow:auto; height:25em;">


/* This is the very generalized SMBus access routine. You probably do not
   want to use this, though; one of the functions below may be much easier,
   and probably just as fast.
   Note that we use i2c_adapter here, because you do not need a specific
   smbus adapter to call this function. */
extern s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
			  unsigned short flags, char read_write, u8 command,
			  int size, union i2c_smbus_data *data);

/* Now follow the 'nice' access routines. These also document the calling
   conventions of i2c_smbus_xfer. */

extern s32 i2c_smbus_read_byte(const struct i2c_client *client);
extern s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value);
extern s32 i2c_smbus_read_byte_data(const struct i2c_client *client,
				    u8 command);
extern s32 i2c_smbus_write_byte_data(const struct i2c_client *client,
				     u8 command, u8 value);
extern s32 i2c_smbus_read_word_data(const struct i2c_client *client,
				    u8 command);
extern s32 i2c_smbus_write_word_data(const struct i2c_client *client,
				     u8 command, u16 value);

static inline s32
i2c_smbus_read_word_swapped(const struct i2c_client *client, u8 command)
{
	s32 value = i2c_smbus_read_word_data(client, command);

	return (value < 0) ? value : swab16(value);
}

static inline s32
i2c_smbus_write_word_swapped(const struct i2c_client *client,
			     u8 command, u16 value)
{
	return i2c_smbus_write_word_data(client, command, swab16(value));
}

/* Returns the number of read bytes */
extern s32 i2c_smbus_read_block_data(const struct i2c_client *client,
				     u8 command, u8 *values);
extern s32 i2c_smbus_write_block_data(const struct i2c_client *client,
				      u8 command, u8 length, const u8 *values);
/* Returns the number of read bytes */
extern s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client,
					 u8 command, u8 length, u8 *values);
extern s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client,
					  u8 command, u8 length,
					  const u8 *values);
</div></div>
</div>
</pre>


If SMBus functionality is enable, access peripheral registers with a set of SMBus commands.<br />

All functions are described at [https://www.kernel.org/doc/Documentation/i2c/writing-clients /Documentation/i2c/writing-clients].<pre class="brush:c; gutter:true; tab-size: 8">

/* Read a byte */
char value;
u8 registerAddr = 0xXX;             /* XX is the register peripheral address */
value = i2c_smbus_read_byte_data(client, registerAddr);

/* Write a byte */
char registerAddr = 0XX;             /* XX is the register peripheral address */
char value = 0xXX;                   /* XX is the value to write */
int err;
err = i2c_smbus_write_byte_data(client, registerAddr, value);</pre>


=== i2c_master_send / i2c_master_recv ===<div class="NavFrame collapsed">
<div class="NavHead">function prototypes from {{Red| /linux/i2c.h}}</div>
<div class="NavContent">
<pre class="brush:c; gutter:true; tab-size: 8;">

/*
 * The master routines are the ones normally used to transmit data to devices
 * on a bus (or read from them). Apart from two basic transfer functions to
 * transmit one message at a time, a more complex version can be used to
 * transmit an arbitrary number of messages without interruption.
 * @count must be less than 64k since msg.len is u16.
 */
extern int i2c_master_send(const struct i2c_client *client, const char *buf,
			   int count);
extern int i2c_master_recv(const struct i2c_client *client, char *buf,
			   int count);</pre>
</div>
</div>


Use '''i2c_master_send''' to set the index reader position at the register address to read and use '''i2c_master_recv''' to read data from the index reader.<br />

Both functions return negative errno, or else the number of bytes write/read.<pre class="brush:c; gutter:true; tab-size: 8; highlight: [4,19,33];">

int set_pointer(struct i2c_client *client, u8 addr)
{
	int ret;
	ret = i2c_master_send(client, &addr, 1);
	if (ret != 1)
		dev_err(&client->dev, "Failed to perform i2c_master_send\n");

	return ret;
}

int read_register(struct i2c_client *client, u8 addr, u8 *buf)
{
	int ret = 0;

	ret = set_pointer(client, addr);
	if (ret < 0)
		return ret;

	ret = i2c_master_recv(client, buf, 1);
	if (ret != 1)
		dev_err(&client->dev, "Failed to perform i2c_master_recv\n");

	return ret;
}

int write_register(struct i2c_client *client, u8 addr, u8 value)
{
	int ret;
	u8 buf[2];
	buf[0] = addr;
	buf[1] = value;

	ret = i2c_master_send(client, buf, 2);
	if (ret < 0)
		dev_err(&client->dev, "Failed to perform i2c_master_send\n");

	return ret;
}</pre>


=== i2c_transfer ===<div class="NavFrame collapsed">
<div class="NavHead">function prototypes from {{Red| /linux/i2c.h}}</div>
<div class="NavContent">
<pre class="brush:c; gutter:true; tab-size: 8">

/* Transfer num messages.
 */
extern int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
			int num);</pre>
</div>
</div>

<pre class="brush:c; gutter:true; tab-size: 8">
<div class="NavFrame collapsed">
<div class="NavHead">'''Struct i2c_msg''' in detail found on {{Red| /uapi/linux/i2c.h}}</div>
<div class="NavContent">
<div style="overflow:auto; height:25em;">


/**
 * struct i2c_msg - an I2C transaction segment beginning with START
 * @addr: Slave address, either seven or ten bits.  When this is a ten
 *	bit address, I2C_M_TEN must be set in @flags and the adapter
 *	must support I2C_FUNC_10BIT_ADDR.
 * @flags: I2C_M_RD is handled by all adapters.  No other flags may be
 *	provided unless the adapter exported the relevant I2C_FUNC_*
 *	flags through i2c_check_functionality().
 * @len: Number of data bytes in @buf being read from or written to the
 *	I2C slave address.  For read transactions where I2C_M_RECV_LEN
 *	is set, the caller guarantees that this buffer can hold up to
 *	32 bytes in addition to the initial length byte sent by the
 *	slave (plus, if used, the SMBus PEC); and this value will be
 *	incremented by the number of block data bytes received.
 * @buf: The buffer into which data is read, or from which it's written.
 *
 * An i2c_msg is the low level representation of one segment of an I2C
 * transaction.  It is visible to drivers in the @i2c_transfer() procedure,
 * to userspace from i2c-dev, and to I2C adapter drivers through the
 * @i2c_adapter.@master_xfer() method.
 *
 * Except when I2C "protocol mangling" is used, all I2C adapters implement
 * the standard rules for I2C transactions.  Each transaction begins with a
 * START.  That is followed by the slave address, and a bit encoding read
 * versus write.  Then follow all the data bytes, possibly including a byte
 * with SMBus PEC.  The transfer terminates with a NAK, or when all those
 * bytes have been transferred and ACKed.  If this is the last message in a
 * group, it is followed by a STOP.  Otherwise it is followed by the next
 * @i2c_msg transaction segment, beginning with a (repeated) START.
 *
 * Alternatively, when the adapter supports I2C_FUNC_PROTOCOL_MANGLING then
 * passing certain @flags may have changed those standard protocol behaviors.
 * Those flags are only for use with broken/nonconforming slaves, and with
 * adapters which are known to support the specific mangling options they
 * need (one or more of IGNORE_NAK, NO_RD_ACK, NOSTART, and REV_DIR_ADDR).
 */
struct i2c_msg {
	__u16 addr;	/* slave address			*/
	__u16 flags;
#define I2C_M_TEN		0x0010	/* this is a ten bit chip address */
#define I2C_M_RD		0x0001	/* read data, from slave to master */
#define I2C_M_STOP		0x8000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NOSTART		0x4000	/* if I2C_FUNC_NOSTART */
#define I2C_M_REV_DIR_ADDR	0x2000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_IGNORE_NAK	0x1000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NO_RD_ACK		0x0800	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_RECV_LEN		0x0400	/* length will be first received byte */
	__u16 len;		/* msg length				*/
	__u8 *buf;		/* pointer to msg data			*/
};
</div>
</div>
</div>
</pre>


'''i2c_transfer''' executes a single or combined I2C message.<br />

'''Note''' that there is no requirement that each message be sent to the same slave address, although that is the most common model.<br />

Returns negative errno, else the number of messages executed.<br />

See https://www.kernel.org/doc/htmldocs/device-drivers/API-i2c-transfer.html.

As '''[[I2C_driver#i2c_master_send / i2c_master_recv| i2c_master_send]]''' and '''[[I2C_driver#i2c_master_send / i2c_master_recv| i2c_master_recv]]''' functions, first message will set the index reader position and second message will store data from the index reader.<pre class="brush:c; gutter:true; tab-size: 8">

u8 registerAddr = 0xXX;             /* XX is the register peripheral address */
u8 value;

struct i2c_msg msg[2] = {
	{
		.addr = client->addr,
		.flags = 0,
		.len = 1,
		.buf = &registerAddr,
	},
	{
		.addr = client->addr,
		.flags = I2C_M_RD,
		.len = 1,
		.buf = &value,
	},
};

ret = i2c_transfer(client->adapter, msg, 2);
if (ret != 2)
        dev_err(&client->dev, "Failed to perform i2c_transfer\n");</pre>


==Documentations and programming examples==
Brief tutorial :<br />

http://renjucnair.blogspot.fr/2012/01/writing-i2c-client-driver.html<br />


Further functions descriptions :<br />

http://www.embedded-bits.co.uk/2009/i2c-in-the-2632-linux-kernel<br />


Code example :<br />

https://code.google.com/archive/p/ldd-templates/source/default/source<br />


===API===
https://www.kernel.org/doc/htmldocs/device-drivers/i2c.html<br />


===Full example===
[[File:I2c-driver-example.png|right|500 px|link=|Implementation architecture]]
The driver example below communicates with a [http://www.st.com/web/en/resource/technical/document/datasheet/DM00134909.pdf sensor expansion board] for STM32 Nucleo.<br />

This board contains four sensor communicating via I2C :
* A capacitive digital sensor for relative humidity and temperature ([http://www.st.com/content/ccc/resource/technical/document/datasheet/4d/9a/9c/ad/25/07/42/34/DM00116291.pdf/files/DM00116291.pdf/jcr:content/translations/en.DM00116291.pdf HTS221]),
* A 3D accelerometer and 3D gyroscope ([http://www.st.com/content/ccc/resource/technical/document/datasheet/6e/09/28/0b/01/06/42/24/DM00101533.pdf/files/DM00101533.pdf/jcr:content/translations/en.DM00101533.pdf LSM6DS0]),
* A 3D magnetometer ([http://www.st.com/content/ccc/resource/technical/document/datasheet/54/2a/85/76/e3/97/42/18/DM00075867.pdf/files/DM00075867.pdf/jcr:content/translations/en.DM00075867.pdf LIS3MDL]),
* And a pressure sensor ([http://www.st.com/content/ccc/resource/technical/document/datasheet/9a/4c/aa/72/1f/45/4e/24/DM00141379.pdf/files/DM00141379.pdf/jcr:content/translations/en.DM00141379.pdf LPS25HB]).

This example informs the user if all peripherals included on the expansion board are correctly detected by reading their name registers.<br />

When a peripheral is bound with the driver, the '''probe''' function reads its register name and detects if is the good one or not.<br />

Instantiation of all peripherals into the device tree looks like :<div style="overflow:auto; height:25em;">
<pre class="brush:c; gutter:true; tab-size: 8">

i2c@9842000 {
	status = "okay";

	lsm6ds0@6b {
		compatible = "nucleo";
		reg = <0x6b>;
	};
	hts221@5f {
		compatible = "nucleo";
		reg = <0x5f>;
	};
	lps25hb@5d {
		compatible = "nucleo";
		reg = <0x5d>;
	};
	lis3mdl@1e {
		compatible = "nucleo";
		reg = <0x1e>;
	};
};</pre>
</div>


Result of the driver can be :<pre>

dmesg
nucleo driver 0-006b: [SUCCESS]The device LSM6DS0 is correctly detected
nucleo driver 0-005f: [SUCCESS]The device HTS221  is correctly detected
nucleo driver 0-005d: [SUCCESS]The device LPS25HB is correctly detected
nucleo driver 0-001e: [SUCCESS]The device LIS3MDL is correctly detected</pre>

or,<pre>

dmesg
nucleo driver 0-006b: [FAILED]The device is not detected, ID = 0x0
nucleo driver 0-005f: [FAILED]The device is not detected, ID = 0x0
nucleo driver 0-005d: [FAILED]The device is not detected, ID = 0x0
nucleo driver 0-001e: [FAILED]The device is not detected, ID = 0x0</pre>

GitHub of all sensor drivers : https://github.com/STMemsLinuxDrivers

[[Media:Hts221_driver.c| download source code]]<br />
<pre class="brush:c; gutter:true;">
<div class="NavFrame collapsed">
<div class="NavHead">nucleo_driver.c source code</div>
<div class="NavContent">
<div style="overflow:auto; height:25em;">


#include <linux/i2c.h>

#include <linux/init.h>

#include <linux/interrupt.h>

#include <linux/io.h>

#include <linux/kernel.h>

#include <linux/module.h>

#include <linux/slab.h>


#define WHO_IS_IT_REG		0x0F

#define HTS221_ID			0xBC
#define LPS25HB_ID			0xBD
#define LSM6DS0_ID			0x68
#define LIS3MDL_ID			0x3D

struct nucleo_sensor {
	struct i2c_client *client;

	/* Add driver properties here */
};

static int nucleo_read_smbus(struct i2c_client *client, u8 addr, u8 *buf)
{
	return *buf = i2c_smbus_read_byte_data(client, addr);
}

static int nucleo_read_method1(struct i2c_client *client, u8 addr, u8 *buf)
{
	u8 out_buf = addr;
	int ret = 0;

	ret = i2c_master_send(client, &out_buf, 1);
	if (ret != 1) {
		dev_err(&client->dev, "Failed to perform i2c_master_send\n");
	} else {
		ret = i2c_master_recv(client, buf, 1);
		if (ret != 1)
			dev_err(&client->dev, "Failed to perform i2c_master_recv\n");
	}

	return ret;
}

static int nucleo_read_method2(struct i2c_client *client, u8 addr, u8 *buf)
{
	u8 out_buf = addr;
	struct i2c_msg msg[2] = {
		{
			.addr = client->addr,
			.flags = 0,
			.len = 1,
			.buf = &out_buf,
		},
		{
			.addr = client->addr,
			.flags = I2C_M_RD,
			.len = 1,
			.buf = buf,
		},
	};

	return i2c_transfer(client->adapter, msg, 2);
}

static int nucleo_sensor_probe(struct i2c_client *client,
			const struct i2c_device_id *id)
{
	struct nucleo_sensor *dev;
	u8 who_is_it = 0x00;
	int ret = 0;

	if (!i2c_check_functionality(client->adapter,
		I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
		I2C_FUNC_SMBUS_I2C_BLOCK))
		return -ENODEV;

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (dev == NULL)
		return -ENOMEM;

	dev->client = client;

	/* Set private data */
	i2c_set_clientdata(client, dev);

	/* First method read the device name register using
	 * i2c_smbus_read_byte_data function */
	ret = nucleo_read_smbus(client, WHO_IS_IT_REG, &who_is_it);
	if (ret < 0)
		dev_err(&client->dev, "Failed to read device using smbus command\n");

	/* Second method read the device name register using
	 * i2c_master_send and i2c_master_recv functions */
	ret = nucleo_read_method1(client, WHO_IS_IT_REG, &who_is_it);
	if (ret < 0)
		dev_err(&client->dev, "Failed to read device using method1\n");

	/* Third method read the device name register using
	 * i2c_transfer function */
	ret = nucleo_read_method2(client, WHO_IS_IT_REG, &who_is_it);
	if (ret < 0)
		dev_err(&client->dev, "Failed to read device using method2\n");

	switch (who_is_it) {
	case HTS221_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device HTS221  is correctly detected\n");
		break;
	case LPS25HB_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device LPS25HB is correctly detected\n");
		break;
	case LSM6DS0_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device LSM6DS0 is correctly detected\n");
		break;
	case LIS3MDL_ID:
		dev_info(&client->dev,
			"[SUCCESS]The device LIS3MDL is correctly detected\n");
		break;
	default:
		dev_err(&client->dev,
			"[FAILED]The device is not detected, ID=0x%x\n",
			who_is_it);
	}

	return 0;
}

static int nucleo_sensor_remove(struct i2c_client *client)
{
	struct nucleo_sensor_temp *dev;

	/* Get private data */
	dev = i2c_get_clientdata(client);
	kfree(dev);

	return 0;
}

static const struct i2c_device_id nucleo_sensor_id[] = {
	{ "nucleo", 0 },
	{ }
};

static struct i2c_driver nucleo_sensor_driver = {
	.probe    = nucleo_sensor_probe,
	.remove   = nucleo_sensor_remove,
	.id_table = nucleo_sensor_id,
	.driver   = {
		.name = "nucleo driver",
	},
};

static int __init nucleo_sensor_init_driver(void)
{
	return i2c_add_driver(&nucleo_sensor_driver);
}

static void __exit nucleo_sensor_exit_driver(void)
{
	i2c_del_driver(&nucleo_sensor_driver);
}

module_init(nucleo_sensor_init_driver);
module_exit(nucleo_sensor_exit_driver);

MODULE_DESCRIPTION("nucleo_sensor client driver");
MODULE_LICENSE("GPL");
</div>
</div>
</div>
</pre>


Help for compilation : [[BitBake_cheat_sheet]]
<noinclude>

[[Category:I2C]]</noinclude>
(One intermediate revision by the same user not shown)
Line 1: Line 1:
  +
{{ReviewsComments|FGA W839: Discussed in domain weekly: Article should be renamed either I2C device driver, or How to write an I2C device driver... or similar<br/>
  +
Current "I2C driver" is confusing: other XXX Linux driver article exist, but deal with internal controller linux driver}}
  +
  +
== Register/Unregister i2c driver ==
  +
  +
To register an i2c driver with i2c-core, the '''i2c_add_driver(struct i2c_driver *driver)''' function is used :
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
static int __init sample_init_driver(void)
  +
{
  +
return(i2c_add_driver(&sample_driver));
  +
}
  +
</pre>
  +
  +
Unregister i2c driver using '''i2c_del_driver(struct i2c_driver *driver)''' :
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
static void __exit sample_exit_driver(void)
  +
{
  +
i2c_del_driver(&sample_driver);
  +
}
  +
</pre>
  +
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
<div class="NavFrame collapsed">
  +
  <div class="NavHead">'''Struct i2c_driver''' in detail found on {{Red| /linux/i2c.h}}</div>
  +
  <div class="NavContent">
  +
<div style="overflow:auto; height:25em;">
  +
  +
/**
  +
* struct i2c_driver - represent an I2C device driver
  +
* @class: What kind of i2c device we instantiate (for detect)
  +
* @attach_adapter: Callback for bus addition (deprecated)
  +
* @probe: Callback for device binding
  +
* @remove: Callback for device unbinding
  +
* @shutdown: Callback for device shutdown
  +
* @alert: Alert callback, for example for the SMBus alert protocol
  +
* @command: Callback for bus-wide signaling (optional)
  +
* @driver: Device driver model driver
  +
* @id_table: List of I2C devices supported by this driver
  +
* @detect: Callback for device detection
  +
* @address_list: The I2C addresses to probe (for detect)
  +
* @clients: List of detected clients we created (for i2c-core use only)
  +
*
  +
* The driver.owner field should be set to the module owner of this driver.
  +
* The driver.name field should be set to the name of this driver.
  +
*
  +
* For automatic device detection, both @detect and @address_list must
  +
* be defined. @class should also be set, otherwise only devices forced
  +
* with module parameters will be created. The detect function must
  +
* fill at least the name field of the i2c_board_info structure it is
  +
* handed upon successful detection, and possibly also the flags field.
  +
*
  +
* If @detect is missing, the driver will still work fine for enumerated
  +
* devices. Detected devices simply won't be supported. This is expected
  +
* for the many I2C/SMBus devices which can't be detected reliably, and
  +
* the ones which can always be enumerated in practice.
  +
*
  +
* The i2c_client structure which is handed to the @detect callback is
  +
* not a real i2c_client. It is initialized just enough so that you can
  +
* call i2c_smbus_read_byte_data and friends on it. Don't do anything
  +
* else with it. In particular, calling dev_dbg and friends on it is
  +
* not allowed.
  +
*/
  +
struct i2c_driver {
  +
unsigned int class;
  +
  +
/* Notifies the driver that a new bus has appeared. You should avoid
  +
* using this, it will be removed in a near future.
  +
*/
  +
int (*attach_adapter)(struct i2c_adapter *) __deprecated;
  +
  +
/* Standard driver model interfaces */
  +
int (*probe)(struct i2c_client *, const struct i2c_device_id *);
  +
int (*remove)(struct i2c_client *);
  +
  +
/* driver model interfaces that don't relate to enumeration  */
  +
void (*shutdown)(struct i2c_client *);
  +
  +
/* Alert callback, for example for the SMBus alert protocol.
  +
* The format and meaning of the data value depends on the protocol.
  +
* For the SMBus alert protocol, there is a single bit of data passed
  +
* as the alert response's low bit ("event flag").
  +
*/
  +
void (*alert)(struct i2c_client *, unsigned int data);
  +
  +
/* a ioctl like command that can be used to perform specific functions
  +
* with the device.
  +
*/
  +
int (*command)(struct i2c_client *client, unsigned int cmd, void *arg);
  +
  +
struct device_driver driver;
  +
const struct i2c_device_id *id_table;
  +
  +
/* Device detection callback for automatic device creation */
  +
int (*detect)(struct i2c_client *, struct i2c_board_info *);
  +
const unsigned short *address_list;
  +
struct list_head clients;
  +
};
  +
  +
</div>
  +
</div>
  +
</div>
  +
</pre>
  +
  +
Minimal configuration can be :
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
static const struct i2c_device_id sample_device_id[] = {
  +
{ "dummy_device", 0 },
  +
{ }
  +
};
  +
  +
static struct i2c_driver sample_driver = {
  +
.probe    = sample_driver_probe,
  +
.remove  = sample_driver_remove,
  +
.id_table = sample_device_id,
  +
.driver  = {
  +
.name = "sample driver example",
  +
},
  +
};
  +
</pre>
  +
'''probe''' is called when a peripheral is bind with the driver.<br />
  +
'''remove''' is the opposite of '''probe''' function.<br />
  +
'''id_table''' lists all peripherals matching with this driver.<br />
  +
'''driver''' are driver characteristics (its name for example).<br />
  +
Further structure details [https://www.kernel.org/doc/htmldocs/device-drivers/API-struct-i2c-driver.html here].
  +
  +
== Bind/Unbind a peripheral ==
  +
When an I2C peripheral is found and matching with the driver '''id_table''', '''probe''' function is called from i2c-core :
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
static int sample_driver_probe(struct i2c_client *client,
  +
const struct i2c_device_id *id)
  +
{
  +
struct private_data *dev;
  +
  +
if (!i2c_check_functionality(client->adapter,
  +
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
  +
I2C_FUNC_SMBUS_I2C_BLOCK))
  +
return -ENODEV;
  +
  +
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
  +
if (dev == NULL)
  +
return -ENOMEM;
  +
  +
/* Set private data */
  +
i2c_set_clientdata(client, dev);
  +
  +
return 0;
  +
}
  +
</pre>
  +
Passed along as a parameter to the probe function is a '''struct i2c_client''' structure that represents our I2C slave chip.<br />
  +
Typically a probe function will detect the compatibility between the I2C bus adapter and the I2C peripheral and allocate memory for the peripheral.<br />
  +
In order to check a functionality of the adapter, the '''i2c_check_functionality''' function is used with all functionality located at [https://www.kernel.org/doc/Documentation/i2c/functionality /Documentation/i2c/functionality].<br />
  +
'''i2c_set_clientdata''' function is used to set peripheral private data under an i2c_client structure to be able to retrieve it with '''i2c_get_clientdata'''.
  +
  +
When an I2C peripheral is unbind with the driver, '''remove''' function is called :
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
static int sample_driver_remove(struct i2c_client *client)
  +
{
  +
struct private_data *dev;
  +
  +
/* Get private data */
  +
dev = i2c_get_clientdata(client);
  +
kfree(dev);
  +
  +
return 0;
  +
}
  +
</pre>
  +
At remove time, release the peripheral memory allocated in probe function.
  +
  +
== Access I2C peripheral data ==
  +
After probing success, read and write peripheral registers using different methods
  +
  +
=== SMBus commands ===
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
<div class="NavFrame collapsed">
  +
  <div class="NavHead">SMBus command prototypes from {{Red| /linux/i2c.h}}</div>
  +
  <div class="NavContent">
  +
<div style="overflow:auto; height:25em;">
  +
  +
/* This is the very generalized SMBus access routine. You probably do not
  +
  want to use this, though; one of the functions below may be much easier,
  +
  and probably just as fast.
  +
  Note that we use i2c_adapter here, because you do not need a specific
  +
  smbus adapter to call this function. */
  +
extern s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
  +
  unsigned short flags, char read_write, u8 command,
  +
  int size, union i2c_smbus_data *data);
  +
  +
/* Now follow the 'nice' access routines. These also document the calling
  +
  conventions of i2c_smbus_xfer. */
  +
  +
extern s32 i2c_smbus_read_byte(const struct i2c_client *client);
  +
extern s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value);
  +
extern s32 i2c_smbus_read_byte_data(const struct i2c_client *client,
  +
    u8 command);
  +
extern s32 i2c_smbus_write_byte_data(const struct i2c_client *client,
  +
    u8 command, u8 value);
  +
extern s32 i2c_smbus_read_word_data(const struct i2c_client *client,
  +
    u8 command);
  +
extern s32 i2c_smbus_write_word_data(const struct i2c_client *client,
  +
    u8 command, u16 value);
  +
  +
static inline s32
  +
i2c_smbus_read_word_swapped(const struct i2c_client *client, u8 command)
  +
{
  +
s32 value = i2c_smbus_read_word_data(client, command);
  +
  +
return (value < 0) ? value : swab16(value);
  +
}
  +
  +
static inline s32
  +
i2c_smbus_write_word_swapped(const struct i2c_client *client,
  +
    u8 command, u16 value)
  +
{
  +
return i2c_smbus_write_word_data(client, command, swab16(value));
  +
}
  +
  +
/* Returns the number of read bytes */
  +
extern s32 i2c_smbus_read_block_data(const struct i2c_client *client,
  +
    u8 command, u8 *values);
  +
extern s32 i2c_smbus_write_block_data(const struct i2c_client *client,
  +
      u8 command, u8 length, const u8 *values);
  +
/* Returns the number of read bytes */
  +
extern s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client,
  +
u8 command, u8 length, u8 *values);
  +
extern s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client,
  +
  u8 command, u8 length,
  +
  const u8 *values);
  +
  +
</div>
  +
</div>
  +
</div>
  +
</pre>
  +
  +
If SMBus functionality is enable, access peripheral registers with a set of SMBus commands.<br />
  +
All functions are described at [https://www.kernel.org/doc/Documentation/i2c/writing-clients /Documentation/i2c/writing-clients].
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
/* Read a byte */
  +
char value;
  +
u8 registerAddr = 0xXX;            /* XX is the register peripheral address */
  +
value = i2c_smbus_read_byte_data(client, registerAddr);
  +
  +
/* Write a byte */
  +
char registerAddr = 0XX;            /* XX is the register peripheral address */
  +
char value = 0xXX;                  /* XX is the value to write */
  +
int err;
  +
err = i2c_smbus_write_byte_data(client, registerAddr, value);
  +
</pre>
  +
  +
=== i2c_master_send / i2c_master_recv ===
  +
<div class="NavFrame collapsed">
  +
  <div class="NavHead">function prototypes from {{Red| /linux/i2c.h}}</div>
  +
  <div class="NavContent">
  +
<pre class="brush:c; gutter:true; tab-size: 8;">
  +
/*
  +
* The master routines are the ones normally used to transmit data to devices
  +
* on a bus (or read from them). Apart from two basic transfer functions to
  +
* transmit one message at a time, a more complex version can be used to
  +
* transmit an arbitrary number of messages without interruption.
  +
* @count must be less than 64k since msg.len is u16.
  +
*/
  +
extern int i2c_master_send(const struct i2c_client *client, const char *buf,
  +
  int count);
  +
extern int i2c_master_recv(const struct i2c_client *client, char *buf,
  +
  int count);
  +
</pre>
  +
</div>
  +
</div>
  +
  +
Use '''i2c_master_send''' to set the index reader position at the register address to read and use '''i2c_master_recv''' to read data from the index reader.<br />
  +
Both functions return negative errno, or else the number of bytes write/read.
  +
<pre class="brush:c; gutter:true; tab-size: 8; highlight: [4,19,33];">
  +
int set_pointer(struct i2c_client *client, u8 addr)
  +
{
  +
int ret;
  +
ret = i2c_master_send(client, &addr, 1);
  +
if (ret != 1)
  +
dev_err(&client->dev, "Failed to perform i2c_master_send\n");
  +
  +
return ret;
  +
}
  +
  +
int read_register(struct i2c_client *client, u8 addr, u8 *buf)
  +
{
  +
int ret = 0;
  +
  +
ret = set_pointer(client, addr);
  +
if (ret < 0)
  +
return ret;
  +
  +
ret = i2c_master_recv(client, buf, 1);
  +
if (ret != 1)
  +
dev_err(&client->dev, "Failed to perform i2c_master_recv\n");
  +
  +
return ret;
  +
}
  +
  +
int write_register(struct i2c_client *client, u8 addr, u8 value)
  +
{
  +
int ret;
  +
u8 buf[2];
  +
buf[0] = addr;
  +
buf[1] = value;
  +
  +
ret = i2c_master_send(client, buf, 2);
  +
if (ret < 0)
  +
dev_err(&client->dev, "Failed to perform i2c_master_send\n");
  +
  +
return ret;
  +
}
  +
</pre>
  +
  +
=== i2c_transfer ===
  +
<div class="NavFrame collapsed">
  +
  <div class="NavHead">function prototypes from {{Red| /linux/i2c.h}}</div>
  +
  <div class="NavContent">
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
/* Transfer num messages.
  +
*/
  +
extern int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
  +
int num);
  +
</pre>
  +
</div>
  +
</div>
  +
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
<div class="NavFrame collapsed">
  +
  <div class="NavHead">'''Struct i2c_msg''' in detail found on {{Red| /uapi/linux/i2c.h}}</div>
  +
  <div class="NavContent">
  +
<div style="overflow:auto; height:25em;">
  +
  +
/**
  +
* struct i2c_msg - an I2C transaction segment beginning with START
  +
* @addr: Slave address, either seven or ten bits.  When this is a ten
  +
* bit address, I2C_M_TEN must be set in @flags and the adapter
  +
* must support I2C_FUNC_10BIT_ADDR.
  +
* @flags: I2C_M_RD is handled by all adapters.  No other flags may be
  +
* provided unless the adapter exported the relevant I2C_FUNC_*
  +
* flags through i2c_check_functionality().
  +
* @len: Number of data bytes in @buf being read from or written to the
  +
* I2C slave address.  For read transactions where I2C_M_RECV_LEN
  +
* is set, the caller guarantees that this buffer can hold up to
  +
* 32 bytes in addition to the initial length byte sent by the
  +
* slave (plus, if used, the SMBus PEC); and this value will be
  +
* incremented by the number of block data bytes received.
  +
* @buf: The buffer into which data is read, or from which it's written.
  +
*
  +
* An i2c_msg is the low level representation of one segment of an I2C
  +
* transaction.  It is visible to drivers in the @i2c_transfer() procedure,
  +
* to userspace from i2c-dev, and to I2C adapter drivers through the
  +
* @i2c_adapter.@master_xfer() method.
  +
*
  +
* Except when I2C "protocol mangling" is used, all I2C adapters implement
  +
* the standard rules for I2C transactions.  Each transaction begins with a
  +
* START.  That is followed by the slave address, and a bit encoding read
  +
* versus write.  Then follow all the data bytes, possibly including a byte
  +
* with SMBus PEC.  The transfer terminates with a NAK, or when all those
  +
* bytes have been transferred and ACKed.  If this is the last message in a
  +
* group, it is followed by a STOP.  Otherwise it is followed by the next
  +
* @i2c_msg transaction segment, beginning with a (repeated) START.
  +
*
  +
* Alternatively, when the adapter supports I2C_FUNC_PROTOCOL_MANGLING then
  +
* passing certain @flags may have changed those standard protocol behaviors.
  +
* Those flags are only for use with broken/nonconforming slaves, and with
  +
* adapters which are known to support the specific mangling options they
  +
* need (one or more of IGNORE_NAK, NO_RD_ACK, NOSTART, and REV_DIR_ADDR).
  +
*/
  +
struct i2c_msg {
  +
__u16 addr; /* slave address */
  +
__u16 flags;
  +
#define I2C_M_TEN 0x0010 /* this is a ten bit chip address */
  +
#define I2C_M_RD 0x0001 /* read data, from slave to master */
  +
#define I2C_M_STOP 0x8000 /* if I2C_FUNC_PROTOCOL_MANGLING */
  +
#define I2C_M_NOSTART 0x4000 /* if I2C_FUNC_NOSTART */
  +
#define I2C_M_REV_DIR_ADDR 0x2000 /* if I2C_FUNC_PROTOCOL_MANGLING */
  +
#define I2C_M_IGNORE_NAK 0x1000 /* if I2C_FUNC_PROTOCOL_MANGLING */
  +
#define I2C_M_NO_RD_ACK 0x0800 /* if I2C_FUNC_PROTOCOL_MANGLING */
  +
#define I2C_M_RECV_LEN 0x0400 /* length will be first received byte */
  +
__u16 len; /* msg length */
  +
__u8 *buf; /* pointer to msg data */
  +
};
  +
  +
</div>
  +
</div>
  +
</div>
  +
</pre>
  +
  +
'''i2c_transfer''' executes a single or combined I2C message.<br />
  +
'''Note''' that there is no requirement that each message be sent to the same slave address, although that is the most common model.<br />
  +
Returns negative errno, else the number of messages executed.<br />
  +
See https://www.kernel.org/doc/htmldocs/device-drivers/API-i2c-transfer.html.
  +
  +
As '''[[I2C_driver#i2c_master_send / i2c_master_recv| i2c_master_send]]''' and '''[[I2C_driver#i2c_master_send / i2c_master_recv| i2c_master_recv]]''' functions, first message will set the index reader position and second message will store data from the index reader.
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
u8 registerAddr = 0xXX;            /* XX is the register peripheral address */
  +
u8 value;
  +
  +
struct i2c_msg msg[2] = {
  +
{
  +
.addr = client->addr,
  +
.flags = 0,
  +
.len = 1,
  +
.buf = &registerAddr,
  +
},
  +
{
  +
.addr = client->addr,
  +
.flags = I2C_M_RD,
  +
.len = 1,
  +
.buf = &value,
  +
},
  +
};
  +
  +
ret = i2c_transfer(client->adapter, msg, 2);
  +
if (ret != 2)
  +
        dev_err(&client->dev, "Failed to perform i2c_transfer\n");
  +
</pre>
  +
  +
==Documentations and programming examples==
  +
Brief tutorial :<br />
  +
http://renjucnair.blogspot.fr/2012/01/writing-i2c-client-driver.html<br />
  +
  +
Further functions descriptions :<br />
  +
http://www.embedded-bits.co.uk/2009/i2c-in-the-2632-linux-kernel<br />
  +
  +
Code example :<br />
  +
https://code.google.com/archive/p/ldd-templates/source/default/source<br />
  +
  +
===API===
  +
https://www.kernel.org/doc/htmldocs/device-drivers/i2c.html<br />
  +
  +
===Full example===
  +
[[File:I2c-driver-example.png|right|500 px|link=|Implementation architecture]]
  +
The driver example below communicates with a [http://www.st.com/web/en/resource/technical/document/datasheet/DM00134909.pdf sensor expansion board] for STM32 Nucleo.<br />
  +
This board contains four sensor communicating via I2C :
  +
* A capacitive digital sensor for relative humidity and temperature ([http://www.st.com/content/ccc/resource/technical/document/datasheet/4d/9a/9c/ad/25/07/42/34/DM00116291.pdf/files/DM00116291.pdf/jcr:content/translations/en.DM00116291.pdf HTS221]),
  +
* A 3D accelerometer and 3D gyroscope ([http://www.st.com/content/ccc/resource/technical/document/datasheet/6e/09/28/0b/01/06/42/24/DM00101533.pdf/files/DM00101533.pdf/jcr:content/translations/en.DM00101533.pdf LSM6DS0]),
  +
* A 3D magnetometer ([http://www.st.com/content/ccc/resource/technical/document/datasheet/54/2a/85/76/e3/97/42/18/DM00075867.pdf/files/DM00075867.pdf/jcr:content/translations/en.DM00075867.pdf LIS3MDL]),
  +
* And a pressure sensor ([http://www.st.com/content/ccc/resource/technical/document/datasheet/9a/4c/aa/72/1f/45/4e/24/DM00141379.pdf/files/DM00141379.pdf/jcr:content/translations/en.DM00141379.pdf LPS25HB]).
  +
  +
This example informs the user if all peripherals included on the expansion board are correctly detected by reading their name registers.<br />
  +
When a peripheral is bound with the driver, the '''probe''' function reads its register name and detects if is the good one or not.<br />
  +
Instantiation of all peripherals into the device tree looks like :
  +
<div style="overflow:auto; height:25em;">
  +
<pre class="brush:c; gutter:true; tab-size: 8">
  +
i2c@9842000 {
  +
status = "okay";
  +
  +
lsm6ds0@6b {
  +
compatible = "nucleo";
  +
reg = <0x6b>;
  +
};
  +
hts221@5f {
  +
compatible = "nucleo";
  +
reg = <0x5f>;
  +
};
  +
lps25hb@5d {
  +
compatible = "nucleo";
  +
reg = <0x5d>;
  +
};
  +
lis3mdl@1e {
  +
compatible = "nucleo";
  +
reg = <0x1e>;
  +
};
  +
};
  +
</pre>
  +
</div>
  +
  +
Result of the driver can be :
  +
<pre>
  +
dmesg
  +
nucleo driver 0-006b: [SUCCESS]The device LSM6DS0 is correctly detected
  +
nucleo driver 0-005f: [SUCCESS]The device HTS221  is correctly detected
  +
nucleo driver 0-005d: [SUCCESS]The device LPS25HB is correctly detected
  +
nucleo driver 0-001e: [SUCCESS]The device LIS3MDL is correctly detected
  +
</pre>
  +
or,
  +
<pre>
  +
dmesg
  +
nucleo driver 0-006b: [FAILED]The device is not detected, ID = 0x0
  +
nucleo driver 0-005f: [FAILED]The device is not detected, ID = 0x0
  +
nucleo driver 0-005d: [FAILED]The device is not detected, ID = 0x0
  +
nucleo driver 0-001e: [FAILED]The device is not detected, ID = 0x0
  +
</pre>
  +
GitHub of all sensor drivers : https://github.com/STMemsLinuxDrivers
  +
  +
[[Media:Hts221_driver.c| download source code]]<br />
  +
<pre class="brush:c; gutter:true;">
  +
<div class="NavFrame collapsed">
  +
  <div class="NavHead">nucleo_driver.c source code</div>
  +
  <div class="NavContent">
  +
<div style="overflow:auto; height:25em;">
  +
  +
#include <linux/i2c.h>
  +
#include <linux/init.h>
  +
#include <linux/interrupt.h>
  +
#include <linux/io.h>
  +
#include <linux/kernel.h>
  +
#include <linux/module.h>
  +
#include <linux/slab.h>
  +
  +
#define WHO_IS_IT_REG 0x0F
  +
  +
#define HTS221_ID 0xBC
  +
#define LPS25HB_ID 0xBD
  +
#define LSM6DS0_ID 0x68
  +
#define LIS3MDL_ID 0x3D
  +
  +
struct nucleo_sensor {
  +
struct i2c_client *client;
  +
  +
/* Add driver properties here */
  +
};
  +
  +
static int nucleo_read_smbus(struct i2c_client *client, u8 addr, u8 *buf)
  +
{
  +
return *buf = i2c_smbus_read_byte_data(client, addr);
  +
}
  +
  +
static int nucleo_read_method1(struct i2c_client *client, u8 addr, u8 *buf)
  +
{
  +
u8 out_buf = addr;
  +
int ret = 0;
  +
  +
ret = i2c_master_send(client, &out_buf, 1);
  +
if (ret != 1) {
  +
dev_err(&client->dev, "Failed to perform i2c_master_send\n");
  +
} else {
  +
ret = i2c_master_recv(client, buf, 1);
  +
if (ret != 1)
  +
dev_err(&client->dev, "Failed to perform i2c_master_recv\n");
  +
}
  +
  +
return ret;
  +
}
  +
  +
static int nucleo_read_method2(struct i2c_client *client, u8 addr, u8 *buf)
  +
{
  +
u8 out_buf = addr;
  +
struct i2c_msg msg[2] = {
  +
{
  +
.addr = client->addr,
  +
.flags = 0,
  +
.len = 1,
  +
.buf = &out_buf,
  +
},
  +
{
  +
.addr = client->addr,
  +
.flags = I2C_M_RD,
  +
.len = 1,
  +
.buf = buf,
  +
},
  +
};
  +
  +
return i2c_transfer(client->adapter, msg, 2);
  +
}
  +
  +
static int nucleo_sensor_probe(struct i2c_client *client,
  +
const struct i2c_device_id *id)
  +
{
  +
struct nucleo_sensor *dev;
  +
u8 who_is_it = 0x00;
  +
int ret = 0;
  +
  +
if (!i2c_check_functionality(client->adapter,
  +
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
  +
I2C_FUNC_SMBUS_I2C_BLOCK))
  +
return -ENODEV;
  +
  +
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
  +
if (dev == NULL)
  +
return -ENOMEM;
  +
  +
dev->client = client;
  +
  +
/* Set private data */
  +
i2c_set_clientdata(client, dev);
  +
  +
/* First method read the device name register using
  +
* i2c_smbus_read_byte_data function */
  +
ret = nucleo_read_smbus(client, WHO_IS_IT_REG, &who_is_it);
  +
if (ret < 0)
  +
dev_err(&client->dev, "Failed to read device using smbus command\n");
  +
  +
/* Second method read the device name register using
  +
* i2c_master_send and i2c_master_recv functions */
  +
ret = nucleo_read_method1(client, WHO_IS_IT_REG, &who_is_it);
  +
if (ret < 0)
  +
dev_err(&client->dev, "Failed to read device using method1\n");
  +
  +
/* Third method read the device name register using
  +
* i2c_transfer function */
  +
ret = nucleo_read_method2(client, WHO_IS_IT_REG, &who_is_it);
  +
if (ret < 0)
  +
dev_err(&client->dev, "Failed to read device using method2\n");
  +
  +
switch (who_is_it) {
  +
case HTS221_ID:
  +
dev_info(&client->dev,
  +
"[SUCCESS]The device HTS221  is correctly detected\n");
  +
break;
  +
case LPS25HB_ID:
  +
dev_info(&client->dev,
  +
"[SUCCESS]The device LPS25HB is correctly detected\n");
  +
break;
  +
case LSM6DS0_ID:
  +
dev_info(&client->dev,
  +
"[SUCCESS]The device LSM6DS0 is correctly detected\n");
  +
break;
  +
case LIS3MDL_ID:
  +
dev_info(&client->dev,
  +
"[SUCCESS]The device LIS3MDL is correctly detected\n");
  +
break;
  +
default:
  +
dev_err(&client->dev,
  +
"[FAILED]The device is not detected, ID=0x%x\n",
  +
who_is_it);
  +
}
  +
  +
return 0;
  +
}
  +
  +
static int nucleo_sensor_remove(struct i2c_client *client)
  +
{
  +
struct nucleo_sensor_temp *dev;
  +
  +
/* Get private data */
  +
dev = i2c_get_clientdata(client);
  +
kfree(dev);
  +
  +
return 0;
  +
}
  +
  +
static const struct i2c_device_id nucleo_sensor_id[] = {
  +
{ "nucleo", 0 },
  +
{ }
  +
};
  +
  +
static struct i2c_driver nucleo_sensor_driver = {
  +
.probe    = nucleo_sensor_probe,
  +
.remove  = nucleo_sensor_remove,
  +
.id_table = nucleo_sensor_id,
  +
.driver  = {
  +
.name = "nucleo driver",
  +
},
  +
};
  +
  +
static int __init nucleo_sensor_init_driver(void)
  +
{
  +
return i2c_add_driver(&nucleo_sensor_driver);
  +
}
  +
  +
static void __exit nucleo_sensor_exit_driver(void)
  +
{
  +
i2c_del_driver(&nucleo_sensor_driver);
  +
}
  +
  +
module_init(nucleo_sensor_init_driver);
  +
module_exit(nucleo_sensor_exit_driver);
  +
  +
MODULE_DESCRIPTION("nucleo_sensor client driver");
  +
MODULE_LICENSE("GPL");
  +
  +
</div>
  +
</div>
  +
</div>
  +
</pre>
  +
  +
Help for compilation : [[BitBake_cheat_sheet]]
  +
 
<noinclude>
 
<noinclude>
{{ArticleMainWriter|Pierre-YvesM}}
 
{{ArticleApprovedVersion | Jean-ChristopheT | Nobody | No previous approved version | Automatic approval (article under construction) | 19Feb’19}}
 
 
[[Category:I2C]]
 
[[Category:I2C]]
 
</noinclude>
 
</noinclude>
{{UnderConstruction}}
 

Attachments

Discussions