Enabling The SPI Port

The SPI port needs to be enabled in Raspberry Pi OS before it can be used. See here.

Test the SPI Port

Test the SPI port is working on the command line by typing:

ls /dev/spidev*

You should see the following:

/dev/spidev0.0  /dev/spidev0.1

There are 2 spidev devices shown (or more on newer Pi’s).  The first number refers to the SPI peripheral which in both cases is 0 (the RPi only has 1 SPI port), the second number represents the chip select pins CS0 and CS1 .

Install spi library

May well already be present with Raspberry Pi OS, but if you need to:

sudo apt-get update
sudo apt-get upgrade
sudo apt install python3-spidev

SPI access

#!/usr/bin/python

import spidev

bus = 0						#Select SPI bus 0
device_cs = 1				#CS pin. Select 0 or 1, depending on the connection to the RPi
spi = spidev.SpiDev()		# Enable SPI
spi.open(bus, device_cs)	#Open connection to the device
spi.max_speed_hz = 500000
spi.mode = 0


#Send a byte
data_tx = [0x76]
spi.xfer2(data_tx)

#Send and receive a byte
data_tx = [0x00]
data_rx = spi.xfer2(data_tx)


#Send and receive bytes
data_tx = [0x24, 0x33, 0x18]
data_rx = spi.xfer2(data_tx)
if (data_rx[0] == 0x11):
	pass