0
0
Iot-protocolsHow-ToBeginner · 3 min read

How to Interface SPI Device with Raspberry Pi: Step-by-Step Guide

To interface an SPI device with a Raspberry Pi, enable the SPI interface via raspi-config, connect the device to the SPI pins (MOSI, MISO, SCLK, CE), and use a library like spidev in Python to send and receive data. This allows your Raspberry Pi to communicate with SPI sensors, displays, or other peripherals.
📐

Syntax

Using the spidev Python library, the basic syntax to communicate with an SPI device is:

  • spi.open(bus, device): Opens SPI bus and device (chip select).
  • spi.max_speed_hz = speed: Sets communication speed.
  • spi.xfer2([data]): Sends and receives data list over SPI.
  • spi.close(): Closes the SPI connection.
python
import spidev

spi = spidev.SpiDev()
spi.open(0, 0)  # Open bus 0, device 0 (CE0)
spi.max_speed_hz = 50000  # Set speed to 50kHz

response = spi.xfer2([0x01, 0x02, 0x03])  # Send 3 bytes and receive response
print(response)

spi.close()
Output
[0, 0, 0]
💻

Example

This example shows how to read data from an SPI device connected to Raspberry Pi using the spidev library. It sends a command byte and reads the response bytes.

python
import spidev
import time

spi = spidev.SpiDev()
spi.open(0, 0)  # Bus 0, Device 0 (CE0)
spi.max_speed_hz = 1000000  # 1 MHz

try:
    # Send command 0x9F to read device ID (common for SPI flash)
    response = spi.xfer2([0x9F, 0x00, 0x00, 0x00])
    print(f"Device ID response: {response}")
finally:
    spi.close()
Output
Device ID response: [159, 0, 0, 0]
⚠️

Common Pitfalls

  • SPI not enabled: The SPI interface must be enabled in Raspberry Pi settings using sudo raspi-config under Interface Options.
  • Wrong wiring: Connect MOSI, MISO, SCLK, and CE pins correctly; wrong connections cause no communication.
  • Incorrect bus/device: Use correct bus (usually 0) and device (0 or 1) matching your chip select pin.
  • Speed too high: Some devices require lower SPI clock speeds; start low and increase carefully.
python
import spidev

spi = spidev.SpiDev()
# Wrong device number example
# spi.open(0, 2)  # Device 2 does not exist, causes error

# Correct way
spi.open(0, 0)
spi.max_speed_hz = 500000
spi.close()
📊

Quick Reference

Remember these key points when working with SPI on Raspberry Pi:

  • Enable SPI via raspi-config.
  • Use pins: MOSI (GPIO 10), MISO (GPIO 9), SCLK (GPIO 11), CE0 (GPIO 8), CE1 (GPIO 7).
  • Use spidev Python library for easy SPI communication.
  • Match bus/device numbers to chip select pins.
  • Start with low SPI clock speed and adjust as needed.

Key Takeaways

Enable SPI interface on Raspberry Pi before connecting devices.
Connect SPI device pins correctly to Raspberry Pi SPI pins.
Use the spidev Python library to open, communicate, and close SPI connections.
Match the SPI bus and device numbers to your hardware chip select pins.
Start with a low SPI clock speed and increase only if the device supports it.