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.
- Make sure you’re using
sudoor switch to root if you have the root account enabled.
- Edit the blacklist using any editor (as long as you run it with root permissions) at
- Comment out the line
Now that I2C is enabled, you have to also enable it in the kernel.
- Edit the
- Add the line
i2c-devto the end of the file
I2C is now enabled but we need to install and configure the necessary packages to interface properly.
- Install the packages by running
sudo apt-get install i2c-tools python-smbus
- Once the packages have installed (if they fail try a
sudo apt-get update) run
sudo adduser pi i2cto 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:
address = 0x28
bytearrytowrite = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
for i in a:
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.