How to connect and control an I2C device under Linux

An I2C bus can be searched to identity which addresses are in use using the i2cdetect command as shown below.

$ i2cdetect 1
WARNING! This program can confuse your I2C bus, cause data loss and worse!
I will probe file /dev/i2c-1.
I will probe address range 0x03-0x77.
Continue? [Y/n] Y
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- UU -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- 2d -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- 49 -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

The output in the above example indicates that there are three devices on bus 1. Devices were identified at addresses 2d and 49. The ‘–‘ symbol indicates that these address were probed but that no device responded, whilst the ‘UU’ at address 08 indicates that this address was not probed as it was being held by another driver.

Having identified that a device is present you can interact with the device using the i2ctranfser command. In the first example given below a value is 0x80 is written to address 0x503d on the device located at I2C address 0x3c. The second example reads two bytes of data from address 0x300a on the same device. In this case the device responds with the values 0x36 and 0x4c, the correct product ID for the queried OV3640 camera device.

$ i2ctransfer -f -y 1 w3@0x3c 0x50 0x3d 0x80
$ i2ctransfer -f -y 1 w2@0x3c 0x30 0x0a r2
0x36 0x4c

Alternatively, if a suitable driver exists within the kernel then you can connect it as shown below and interact with it using sysfs. In the example given I have connected a ds1621 digital thermometer located at I2C address 0x3c and read the temperature of 29.5 C

$ echo ds1621 0x3c > /sys/bus/i2c/devices/i2c-1/new_device
$ cat /sys/class/hwmon/hwmon1/temp1_input
29500