Write an I2C Client Driver for a Temperature Sensor
Build a complete I2C client driver for a TMP102-style sensor on Linux 6.12: id tables, probe, SMBus reads, a sysfs attribute, device tree node and test output.

An I2C client driver is the piece of code that knows one chip: where its registers are, what the bytes mean, and how to hand the result to the rest of the system. Writing one end to end is the best way to learn the I2C subsystem, and a temperature sensor is a good first chip because it has one meaningful register and nothing dangerous to misconfigure. This post writes a driver for a TMP102-compatible sensor, using the i2c_driver structure, both an of_match_table and an i2c_device_id table, probe, SMBus register reads, and a sysfs attribute that prints the temperature. It targets Linux 6.12 and GCC 14. The register layout comes from the TMP102 datasheet: register 0 holds a 12-bit signed temperature in the top bits of a 16-bit word, with 0.0625 degrees Celsius per count. The code was written against the kernel's I2C client documentation, not executed, and the outputs are worked out from it. A later post replaces the custom sysfs file with the standard hwmon interface, which is what a production driver does.
The device tree node
The driver binds to a child of the I2C controller, with the 7-bit address in reg:
&i2c1 {
status = "okay";
temp@48 {
compatible = "acme,tmp102demo";
reg = <0x48>;
};
};The vendor prefix acme and the name tmp102demo are invented so the example does not collide with the real ti,tmp102 driver in the kernel.
The skeleton
An I2C driver includes <linux/i2c.h>, defines per-device state, and registers an i2c_driver. Start with the state and the register constants:
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/of.h>
#define TMP_REG_TEMP 0x00
#define TMP_REG_CONFIG 0x01
struct tmp102demo {
struct i2c_client *client;
};Reading the temperature
I2C devices speak in registers, and the SMBus helper functions cover the usual register access patterns without building i2c_msg arrays by hand. The datasheet says the temperature register is 16 bits, sent most significant byte first. The SMBus word helpers assume the low byte arrives first, so the kernel provides i2c_smbus_read_word_swapped for devices like this one, which swaps the bytes after reading:
static int tmp102demo_read_mc(struct tmp102demo *tmp, int *millicelsius)
{
s32 raw = i2c_smbus_read_word_swapped(tmp->client, TMP_REG_TEMP);
int counts;
if (raw < 0)
return raw;
/* 12-bit two's complement in bits 15..4; arithmetic shift keeps the sign */
counts = ((s16)raw) >> 4;
*millicelsius = counts * 625 / 10;
return 0;
}Work through the number format with two examples. A raw word of 0x1980 is 0x198 after the shift, which is 408 counts, and 408 times 0.0625 is 25.5 degrees, so the code returns 25500 millidegrees. A raw word of 0xE480 is negative as a signed 16-bit value; the shift yields -440 counts, and -440 * 625 / 10 is -27500, meaning minus 27.5 degrees. Casting to s16 before shifting matters, because shifting the unsigned raw would turn a negative temperature into a large positive number.
Return values follow the kernel convention: a negative errno on failure, which for I2C is -EIO when the device does not respond, -ENXIO on a NACK, and -ETIMEDOUT when the bus hangs.
A sysfs attribute
To get the value to user space without a subsystem, the driver can create a device attribute. The macro DEVICE_ATTR_RO generates the structure from a show function whose name is the attribute's name plus _show:
static ssize_t temp_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct tmp102demo *tmp = dev_get_drvdata(dev);
int mc, ret;
ret = tmp102demo_read_mc(tmp, &mc);
if (ret)
return ret;
return sysfs_emit(buf, "%d\n", mc);
}
static DEVICE_ATTR_RO(temp);
static struct attribute *tmp102demo_attrs[] = {
&dev_attr_temp.attr,
NULL,
};
ATTRIBUTE_GROUPS(tmp102demo);sysfs_emit is the safe replacement for sprintf in show functions, since it knows the buffer is one page. ATTRIBUTE_GROUPS makes the tmp102demo_groups array the driver core can create when the device binds, so no explicit create or remove calls are needed.
Probe
probe for an I2C client in Linux 6.12 takes only the client, since the older form that also took the matching i2c_device_id was removed. First check that the adapter can do the SMBus word reads the driver needs, then allocate state and verify the chip by reading a register:
static int tmp102demo_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
struct tmp102demo *tmp;
int mc, ret;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_WORD_DATA))
return dev_err_probe(dev, -EOPNOTSUPP,
"adapter lacks SMBus word access\n");
tmp = devm_kzalloc(dev, sizeof(*tmp), GFP_KERNEL);
if (!tmp)
return -ENOMEM;
tmp->client = client;
i2c_set_clientdata(client, tmp);
ret = tmp102demo_read_mc(tmp, &mc);
if (ret)
return dev_err_probe(dev, ret, "cannot read temperature\n");
dev_info(dev, "sensor found, %d.%03d C\n", mc / 1000, abs(mc) % 1000);
return 0;
}The functionality check is not decoration. Some adapters, such as certain GPIO bit-banged or firmware-driven ones, support only plain I2C transfers, and i2c_smbus_read_word_swapped would then be emulated or fail. Failing early with a clear message beats a mystery error on first read. The dev_info line is the proof of life: it also confirms the chip really answers, because a device that is wired wrongly makes the first read fail and probe returns the error.
Tables and registration
static const struct of_device_id tmp102demo_of_match[] = {
{ .compatible = "acme,tmp102demo" },
{ }
};
MODULE_DEVICE_TABLE(of, tmp102demo_of_match);
static const struct i2c_device_id tmp102demo_id[] = {
{ "tmp102demo" },
{ }
};
MODULE_DEVICE_TABLE(i2c, tmp102demo_id);
static struct i2c_driver tmp102demo_driver = {
.driver = {
.name = "tmp102demo",
.of_match_table = tmp102demo_of_match,
.dev_groups = tmp102demo_groups,
},
.probe = tmp102demo_probe,
.id_table = tmp102demo_id,
};
module_i2c_driver(tmp102demo_driver);
MODULE_DESCRIPTION("Demo I2C temperature sensor driver");
MODULE_LICENSE("GPL");Both tables matter. The of_match_table binds the device from the tree. The i2c_device_id table serves devices created from code or by new_device in sysfs, and it is also needed for module autoloading of I2C clients from some paths. There is no remove, because managed allocation and the attribute group cover cleanup. module_i2c_driver generates init and exit that register and unregister the driver.
Build, load and observe
A standard out-of-tree Makefile with obj-m += tmp102demo.o builds the module. With the node in the device tree and the sensor reading 25.5 degrees:
sudo insmod tmp102demo.ko
dmesg | tail -1
cat /sys/bus/i2c/devices/1-0048/temp[ 310.442190] tmp102demo 1-0048: sensor found, 25.500 C
25500The kernel message shows that probe read the chip. The sysfs file returns the value in millidegrees, the unit the hwmon subsystem uses too, so the number is already in the conventional form. Heat the sensor with a finger and read the file again, and the number rises by a few thousand.
If the device does not bind, use the checks from the matching post: look for 1-0048 under /sys/bus/i2c/devices, check its driver link, and read devices_deferred. If probe ran and failed, the log shows cannot read temperature: -121, and -121 is -EREMOTEIO, meaning the device NACKed, which points to a wrong address or missing power.
Why this is not the finished form
A custom file named temp in the device directory is invisible to standard tools. Every sensor driver that invents its own name forces applications to special-case it, which is the problem the hwmon and IIO subsystems solve. Real drivers also read the configuration register, support shutdown and conversion rate settings, handle alert interrupts and report errors through the framework. Treat this driver as the learning version and move to the hwmon post for the interface that lm-sensors and monitoring tools understand.
Boundaries
SMBus helpers assume a register-addressed protocol, which fits most sensors. A chip with a command-stream protocol, such as a display controller, needs i2c_transfer with explicit messages. Sleeping in probe is fine, but the show function runs in process context under no lock, so concurrent reads issue concurrent bus transfers, which the I2C core serializes per adapter. Chips with multi-step operations must take their own mutex.


