Raspberry Pi SPI and I2C Tutorial

Contributors: Byron J., Shawn Hymel
Favorited Favorite 16

Background & Software Setup

The Raspberry Pi has three types of serial interface on the GPIO header. You're probably already familiar with the UART serial port, which allows you to open a login session from a serial terminal application, such as PuTTY.

The other two serial interfaces are the Serial Peripheral Interface (SPI) and Inter-Integrated-Circuit bus (I2C). SPI on the Pi allows for up to two attached devices, while I2C potentially allows for many devices, as long as their addresses don't conflict.

Software Details

The software landscape for the Raspberry Pi has evolved considerably since the introduction of the Pi. Many different operating systems have been ported to the Pi, and the device driver infrastructure has also changed quite a bit.

For this tutorial, we'll be using a recent version of Raspbian (installed via NOOBS), and the wiringPi I/O library for C/C++ (or spidev/smbus for Python).

With the implementation of device tree overlays in Raspbian, some of the specific interface enablement details have changed. If you're working with an older install, it might be worth backing up your SD card, and starting with a fresh install.

OS and Library Install

If you're starting from scratch, with a blank SD card, you'll want to install Raspbian. If you've already got a working Raspbian system, skip ahead to step 3.

If you would like alternative ways to set up your Pi, please refer to the following tutorials:

Raspberry Pi 3 Starter Kit Hookup Guide

Guide for getting going with the Raspberry Pi 3 Model B and Raspberry Pi 3 Model B+ starter kit.

Headless Raspberry Pi Setup

Configure a Raspberry Pi without a keyboard, mouse, or monitor.

Setting up a Raspberry Pi 3 as an Access Point

This guide will show you how to configure a Raspberry Pi as an access point and connect it to your local Ethernet network to share Internet to other WiFi devices.

How to Use Remote Desktop on the Raspberry Pi with VNC

Use RealVNC to connect to your Raspberry Pi to control the graphical desktop remotely across the network.

C/C++ (Wiring Pi) Setup

If you're planning on using C/C++, Follow the Wiring Pi Instructions to get git, update and upgrade your Rasbpian packages, then install WiringPi.

Be patient -- each of these steps takes a while.

Once you've got wiringPi installed, run the gpio commands shown below.

>gpio -v
>gpio readall

It should respond with some information about the wiringPi version and the Pi that its running on, then draw a table illustrating the configuration for the pins in the 40-pin connector.

The I2C and SPI interfaces each require some additional configuration and initialization, which we'll cover in later sections.

Python (spidev/smbus) Setup

Follow the Configure Your Pi section in the Python Programming Tutorial to set up Python 3 and install pip.