Using Raspberry Pi SPI in Python



We already learnt how to use Raspberry Pi with GPIB interface to communicate with lab instruments. How about using SPI port, to talk with external SPI devices, such as ADC/DAC chips?

Software setup

  1. Comment blacklist spi-bcm2708 to enable SPI in /etc/modprobe.d/raspi-blacklist.conf
  1. Make sure your SPI port is visible in lsmod
root@tin:/etc/modprobe.d# lsmod
Module                  Size  Used by
i2c_dev                 6970  0
spidev                  6533  0
i2c_bcm2708             5306  0
spi_bcm2708             6578  0
  1. Make folder and install python-spi library
root@tin:/home# mkdir python-spi
root@tin:/home# cd python-spi
root@tin:/home/python-spi# wget
--2015-11-24 08:24:53--
Resolving (
Connecting to (||:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: [following]
--2015-11-24 08:24:59--
Resolving (
Connecting to (||:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 21177 (21K) [application/zip]
Saving to: `'
100%[=========================================================>] 21,177      93.9K/s   in 0.2s
  1. Now we can unpack it and install
root@tin:/home/python-spi# unzip
root@tin:/home/python-spi# cd py-spidev-master/
root@tin:/home/python-spi/py-spidev-master# python install
running install
running build
running build_ext
building 'spidev' extension
running install_egg_info
Writing /usr/local/lib/python2.7/dist-packages/spidev-3.0.egg-info

Example Python program

Let’s create simple test python app:

import spidev
import time
spi = spidev.SpiDev(),0)
while True:
   resp = spi.xfer2([0xDE])
   print resp[0]

Correct output should be

root@tin:/repo/spitest# python ./
SPI Test tool
Author: Ilya Tsemenko
Created: Nov. 24, 2015, 8:41 a.m.
Modified: Nov. 24, 2015, 8:56 a.m.