Skip to content
systemcoding.dev
Kernels

Talk to I2C Devices From User Space With i2c-dev and i2c-tools

Load i2c-dev, scan a bus with i2cdetect, read and write registers with i2cget and i2cset, and do the same in C through /dev/i2c-N and ioctl on Linux.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, Arm and C logos.

Before you write a kernel driver for an I2C chip, you should be able to talk to it from the command line. If you can read its ID register with a one-line command, you know the wiring, the address and the power are right, and every problem left is software. Linux provides this through the i2c-dev driver, which exposes each I2C bus as a character device, and the i2c-tools package, which wraps it in simple commands. This post walks through installing them, scanning a bus, reading and writing registers, then doing the same in a C program using the same device node. It uses Linux 6.12 and i2c-tools 4.3 on a Raspberry Pi style board, and every output is an example, since addresses and values depend on your hardware. The kernel's i2c-dev interface document is the primary reference.

Enable the interface

i2c-dev is a kernel module, and it must be present for /dev/i2c-N to exist. Check for the nodes, and load the module if they are missing:

Shell
ls /dev/i2c-* 2>/dev/null || sudo modprobe i2c-dev
ls /dev/i2c-*
Text
/dev/i2c-1

The number is the bus number the kernel gave the adapter. On a Raspberry Pi, i2c-1 is the header's bus once I2C is enabled in the configuration. On other boards, list the adapters to match numbers to controllers:

Shell
i2cdetect -l
Text
i2c-1	i2c       	bcm2835 (i2c@7e804000)          	I2C adapter
i2c-2	i2c       	bcm2835 (i2c@7e205600)          	I2C adapter

Install the tools with your package manager. On Debian-based systems:

Shell
sudo apt install i2c-tools

To use them without sudo, add your user to the i2c group that the udev rules on most distributions assign to /dev/i2c-*.

Scan the bus

i2cdetect -y 1 probes every address on bus 1 and prints a table. The -y flag skips the confirmation prompt:

Shell
i2cdetect -y 1
Text
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:                         -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- 48 -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- --

A number means a device acknowledged that address: here 48 is a device at 0x48. A -- means no reply. The text UU instead of a number means the address is claimed by a kernel driver, so user space must not touch it. The scan works by attempting a quick read or write at each address, and some devices react badly to the probe type used, so on boards with unusual chips, read the i2cdetect manual page before scanning.

An empty table usually means the wiring or pull-ups are wrong, the device is unpowered, or the bus number is wrong.

Read and write registers

i2cget reads one value. The arguments are the bus, the device address, the register, and optionally the access mode, where b is a byte, w a 16-bit word and i a block:

Shell
i2cget -y 1 0x48 0x00 w
Text
0x8019

This asks the device at 0x48 for register 0 as a word. The result 0x8019 is what the SMBus word read returned: the two bytes arrive low byte first, so a chip that sends the high byte first, as many sensors do, appears byte-swapped. For a TMP102 temperature sensor this reads as raw 0x1980, which is 25.0 degrees Celsius after dropping the low four bits and multiplying by 0.0625. The values are an example, not from a specific board.

i2cset writes. To set register 0x01 to 0x60:

Shell
i2cset -y 1 0x48 0x01 0x60
i2cget -y 1 0x48 0x01
Text
0x60

i2cdump prints a range of registers at once, which is ideal for comparing chips against datasheets:

Shell
i2cdump -y 1 0x48 b | head -4
Text
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f    0123456789abcdef
00: 19 80 4b 00 50 00 00 00 00 00 00 00 00 00 00 00    ??K.P...........
10: 19 80 4b 00 50 00 00 00 00 00 00 00 00 00 00 00    ??K.P...........

Be careful with i2cset on devices you do not know. Writing to the wrong register of an EEPROM can erase data, and some PMICs can be misconfigured into damaging the board. Read the datasheet first, and prefer -r read-back verification when available.

Do it in C

The tools are thin wrappers over /dev/i2c-N. A program opens the node, selects the target address with the I2C_SLAVE ioctl, then uses ordinary read and write. This one reads the 16-bit temperature register of a TMP102 at 0x48:

i2c_temp.cc
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>

int main(void)
{
    int fd = open("/dev/i2c-1", O_RDWR);
    uint8_t reg = 0x00;
    uint8_t buf[2];

    if (fd < 0) {
        perror("open /dev/i2c-1");
        return 1;
    }
    if (ioctl(fd, I2C_SLAVE, 0x48) < 0) {
        perror("ioctl I2C_SLAVE");
        return 1;
    }
    if (write(fd, &reg, 1) != 1) {
        perror("write register pointer");
        return 1;
    }
    if (read(fd, buf, 2) != 2) {
        perror("read temperature");
        return 1;
    }
    int raw = ((buf[0] << 8) | buf[1]) >> 4;
    printf("raw=0x%03x temp=%.4f C\n", raw, raw * 0.0625);
    close(fd);
    return 0;
}

Compile with gcc -Wall -o i2c_temp i2c_temp.c using GCC 14. With the register bytes 0x19 0x80 from the earlier example, the program prints:

Text
raw=0x198 temp=25.5000 C

Check the arithmetic: 0x1980 >> 4 is 0x198, which is 408, and 408 times 0.0625 is 25.5. The write sets the chip's register pointer, and the read fetches two bytes, which is the sequence a controller performs as a write followed by a read, with a stop in between. To get a repeated start instead, use the I2C_RDWR ioctl with two messages in one call, which the next paragraph shows in outline.

The combined transfer

Some chips require a repeated start between the register write and the read, because a stop resets their internal pointer. The I2C_RDWR ioctl takes an array of struct i2c_msg and sends them as one transaction:

i2c_rdwr.cc
struct i2c_msg msgs[2] = {
    { .addr = 0x48, .flags = 0,        .len = 1, .buf = &reg },
    { .addr = 0x48, .flags = I2C_M_RD, .len = 2, .buf = buf  },
};
struct i2c_rdwr_ioctl_data data = { .msgs = msgs, .nmsgs = 2 };

if (ioctl(fd, I2C_RDWR, &data) < 0)
    perror("I2C_RDWR");

The first message writes the register number and the second reads two bytes, with a repeated start between them and no stop. It is the same shape the kernel's own i2c_transfer uses.

Common problems

  • **Permission denied opening /dev/i2c-1.** Add yourself to the i2c group, or use sudo.

  • **ioctl I2C_SLAVE fails with Device or resource busy.** A kernel driver already owns that address. Use I2C_SLAVE_FORCE only if you know the driver is not using the device, or unbind the driver first.

  • **Reads return 0xff or zeros.** The chip is not responding and the bus floats high, or the register address is wrong.

  • **Remote I/O error.** The device sent a NACK, so the address or the device state is wrong.

Boundaries

User-space access is for bring-up, scripting and low-rate use. It cannot receive interrupts, share the bus safely with a kernel driver for the same device, or meet real-time deadlines. Once the chip works, a kernel driver exposes it through a proper subsystem, as the later posts show.

A small shell workflow for bring-up

Once the three commands work, a short routine saves time on every new chip. First, power the board and run i2cdetect -y N with the chip connected and then disconnected, so the difference proves which address is the chip. Second, read the identification register the datasheet lists, which almost every chip has, and compare it with the documented value. A match proves the address, the bus speed and the wiring in one step. Third, read the default values of the control registers and compare them with the datasheet's reset table. Fourth, change one setting at a time and read it back.

Keep a log of the exact commands. When you later write the kernel driver, those commands translate directly into register constants and probe code: the ID check becomes a sanity test in probe, and the sequence that worked becomes the initialization routine. It also helps to script the sequence as a shell function, so you can rerun it after every power cycle and catch devices that need a delay after reset before they respond.

Also inEmbedded
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.