The I2c Interface

I2C (Inter-Integrated Circuit) is a serial, bus based, hardware interface for connecting peripheral devices, especially those with lower speed requirements. SMBus (System Management Bus) is derived from I2C but for the Raspberry Pi the terms are often used interchangeably.

The Raspberry Pi has two I2C buses (0 and 1) but only the second one is commonly used. Theoretically up 127 devices can be attached to each bus because each attached device is addressed with a 7-bit number but in practice this number is much lower because of electrical constraints and because certain addresses are reserved.

I2C interfaces are disabled by default. To activate them add the following lines to /boot/config.txt and reboot:

Bus Config Line
0 (uncommon) dtparam=spi=onbcm2708.vc_i2c_override=1
1 dtparam=i2c_arm=on

You should see a subset of the following Linux devices if everything is configured properly.

Linux device bus pins
/dev/i2c-0 I2C0 SDA, SCL
/dev/i2c-1 I2C1 SDA, SCL

The table below shows where to find the I2C bus interface on the Raspberry Pi’s header.

Description BCM Pin Pin BCM Description
3.3VCC 01 02 5VCC
I2C1 SDA 02 03 04 5VCC
I2C1 SDA 02 03 04
I2C1 SCL 03 05 06
04 07 08 14
GND 09 10 15
17 11 12 18
27 13 14 GND
22 15 16 23
3.3VCC 17 18 24
10 19 20 GND
09 21 22 25
11 23 24 08
GND 25 26 07
I2C0 SDA 00 27 28 01 I2C0 SCL
05 29 30 GND
06 31 32 12
13 33 34 GND
19 35 36 16
26 37 38 20
39 40 21
GND

Note that only two wires are necessary for carrying the I2C signals.

Command Line Access

A handy diagnostic tool for I2C is i2cdetect1.

This invocation will show all devices listening on the bus 1 which is useful for obtaining the 7-bit device addresses needed for communication.

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

I this case we have two devices listening on the bus with addresses 0x34 and 0x51 respectively.

Python Access

In Python you get access to I2C via the smbus library2

Sample code for sending data to a device looks like this:

import smbus

BUS_NO= 1
DEVICE_ADDR = 0x51
bus = smbus.SMBus(BUS_NO)

bus.write_byte_data(DEVICE_ADDR, 0x00, 0x01)

  1. sudo apt install i2c-tools↩︎

  2. sudo apt install python3-smbus↩︎