Raspberry Pi SPI

These are general notes, there are often caveats with GPIO/SPI applications on any embedded device.

Raspberry Pi SPI pinout shows two SPI ports spi0 spi1 for most Raspberry Pi models include Zero, 1, 2, 3 and Compute Module. The Compute Modules have three SPI ports, with the addition of spi2 that’s only available on the Compute Modules.

Software

Python is a popular way to access the Raspberry Pi SPI. spidev is a popular Python module to use SPI. For example, the Raspberry Pi SPI maximum clock speed is set to 1 MHz by

import spidev
spi = spidev.SpiDev()
spi.open(bus, device)
spi.max_speed_hz=1000000

As noted in later sections, having the correct maximum clock speed and correct polarity is essential for SPI communications to work.

Synchronous

You might be familiar with asynchronous protocols such as used in RS232 connections, where the baud rate must be agreed upon in advance by master and slave. Only the SPI master initiates communications, and the master must know how many bytes to receive for a given command so as not to cut off the communications too early. Be sure polarity and phase are compatible between devices.

SPI consists of four wires: clock, slave select, MISO and MOSI.

Clock

The clock line is unidirectional from the master to slave, and so the slave cannot initiate communications. Faster clocks require shorter wires, as remember a 10 MHz square wave needs several harmonics to keep usable shape–perhaps up to 100 MHz. How good of a transmission line is your knotted hookup wire at 100 MHz? not so good perhaps.

Consider clock speed if a slave is not responding, or responding erratically, especially considering that the Raspberry Pi 2/3 SPI clock varies with the VPU speed.

Slave Select

The Raspberry Pi can select more than two slaves by using a binary decoder chip, assuming you have a recent kernel and the appropriate software and configuration.

MISO

MISO is unidirectional from each slave to master. The MISO line is shared between all slaves. Only one slave, selected by Slave Select line may use MISO at once.

MOSI

MOSI is unidirectional from master to all slaves. The MOSI line is shared between all slaves. Only the slave selected by Slave Select should respond to MOSI on MISO.

Full duplex

SPI is a full-duplex protocol, that is, the master can send while the slave transmits (for capable hardware).

Debugging

Debugging SPI is most convenient with a four-channel oscilloscope, particularly if the scope has SPI decode.

Notes

Note: In some peripherals, MISO is daisy-chained with MOSI, but your datasheet would tell you for those cases.

See /boot/overlays/README for more details on configuring the GPIO for SPI.

Leave a Comment