A Single Script to Setup I2C on Your Raspberry Pi

I2C is a data bus that uses two bidirectional lines (SDA and SCL) to connect multiple peripherals to computers and embedded systems. The GPIO 2 and 3 on Raspberry Pi could be used as the SDA and SCL lines for I2C devices. There are many I2C devices could work with your Raspberry Pi, but they are not “plug and play” since Raspberry Pi doesn’t enable I2C by default. You can, of course find some great tutorials on the Internet to enable I2C step by step, such as this one and this one. It is not a difficult task and will not take long time to get it done.
I would like to share a script that could have all these configurations done. This script is extracted from Witty Pi‘s software installing script, and it is proven to work well. This script will enable I2C on your Raspberry Pi and install i2c-tools (if it is not installed yet).

#!/bin/bash
# file: setup_i2c.sh
#
# This script will enable I2C and install i2c-tools on your Raspberry Pi
#
# check if sudo is used
if [ "$(id -u)" != 0 ]; then
  echo 'Sorry, you need to run this script with sudo'
  exit 1
fi
# enable I2C on Raspberry Pi
echo '>>> Enable I2C'
if grep -q 'i2c-bcm2708' /etc/modules; then
  echo 'Seems i2c-bcm2708 module already exists, skip this step.'
else
  echo 'i2c-bcm2708' >> /etc/modules
fi
if grep -q 'i2c-dev' /etc/modules; then
  echo 'Seems i2c-dev module already exists, skip this step.'
else
  echo 'i2c-dev' >> /etc/modules
fi
if grep -q 'dtparam=i2c1=on' /boot/config.txt; then
  echo 'Seems i2c1 parameter already set, skip this step.'
else
  echo 'dtparam=i2c1=on' >> /boot/config.txt
fi
if grep -q 'dtparam=i2c_arm=on' /boot/config.txt; then
  echo 'Seems i2c_arm parameter already set, skip this step.'
else
  echo 'dtparam=i2c_arm=on' >> /boot/config.txt
fi
if [ -f /etc/modprobe.d/raspi-blacklist.conf ]; then
  sed -i 's/^blacklist spi-bcm2708/#blacklist spi-bcm2708/' /etc/modprobe.d/raspi-blacklist.conf
  sed -i 's/^blacklist i2c-bcm2708/#blacklist i2c-bcm2708/' /etc/modprobe.d/raspi-blacklist.conf
else
  echo 'File raspi-blacklist.conf does not exist, skip this step.'
fi
# install i2c-tools
echo '>>> Install i2c-tools'
if hash i2cget 2>/dev/null; then
  echo 'Seems i2c-tools is installed already, skip this step.'
else
  apt-get install -y i2c-tools
fi

You will need to have your Raspberry Pi connected to the Internet, and use “sudo sh setup-i2c.sh” to run this script.

See also

Join Waitlist We will inform you when the product arrives in stock. Please leave your valid email address below.