Using Raspberry Pi I2C with Python

 Getting The Pi I2C Ready

First you’ll need to enable I2C. (Yes I know it’s really I2C but most people are too lazy to make a superscript) I2C is disable by default on the Raspberry Pi.

  1. Make sure you’re using sudo or switch to root if you have the root account enabled.
  2. Edit the blacklist using any editor (as long as you run it with root permissions) at /etc/modprobe.d/raspi-blacklist.conf
  3. Comment out the line blacklist i2c-bcm2708

Now that I2C is enabled, you have to also enable it in the kernel.

  1. Edit the /etc/modules file
  2. Add the line i2c-dev to the end of the file

I2C is now enabled but we need to install and configure the necessary packages to interface properly.

  1. Install the packages by running sudo apt-get install i2c-tools python-smbus
  2. Once the packages have installed (if they fail try a sudo apt-get update) run sudo adduser pi i2c to add our account to the I2C access group

Your I2C should now be ready to use, do a quick sudo reboot and we’ll give it a shot! Once your RasPi has rebooted run the command i2cdetect -y 0 to check if anything connected to your device.

Using I2C in Python

Using I2C in python is actually quite simple once you have the right ideas. In a similar manner to other serial formats you will write bits and read bits. In python your writing of bits will look like this:

import smbus
bus=smbus.SMBus(0)
address  = 0x28
bytearrytowrite = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
def toWrite(a):
    for i in a:
        bus.write_byte(address, i)
toWrite(bytearraytowrite)

This code will write the string “Hello World!” (translated to ASCII Decimal) via a byte array to the I2C device at the address 0×28.



Leave a Comment


× two = 4