RPi I2C 2017

(older version of RPi I2C)

This version presents an easy more flexible method of using I2C on a Raspberry Pi. This version is for 2017-03-02-raspbian-jessie.

Set Up

I2C is disabled by default and so needs enabling either via

sudo raspi-config

sudo raspi-config' or through the RPi desktop. It is also advisable to install i2c tools:

sudo apt-get install -y i2c-tools

You can then use

i2cdetect -y 1

to check that the hardware is connected okay

Voltage Levels

This troubles some. The master I2C, in this case the RPi has pull up resistors that go the to 3.3V supply. I2C has two logic states 'off' and 'zero'. The master will drive the I2C bus to zero by effectively switching the pin to ground. When a logic 1 is required the master simple switched the pin to high impedance (or it should - hopefully). The pull up resisters will then take the pin to logic 1.

It should then be clear that even on a 5V system, logic 1 is determined by the pull up resistors. If follows then that provided the master and slave behave correctly a 5V device can be connected to a 3.3V device provided the pull up resistors go to 3.3V

Software

Thanks to Raju for the conversion of the old notSMB written in C to a pure python script this now works with all of the RPi releases.

use wget http://www.byvac.com/downloads/py/easyi2c.py

The above, very simple python program is the bases for the new libraries. It can be used stand alone.

Example:

Reading and writing to a 24C32 or similar EEPROM

>>> import easyi2c
>>> dev = easyi2c.IIC(0x50,1) # address and bus - always 1 unless very old RPi
>>> dev.i2c([0,0],5) # reads 5 bytes from address 0

The module uses lists to work i2c([send to i2c],receive # bytes from i2c)

These is only 1 function that does all of the work, it will return a list if the second parameter is not 0. There is also i2c.close() to free up the bus.

Some more examples:

dev.i2c([1,2,3],0) # send 3 bytes to the bus and return nothing
dev.i2c([156],10) # send byte value 156 to the i2c and return 5 bytes