0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use SPI on Raspberry Pi: Simple Guide and Example

To use SPI on Raspberry Pi, first enable SPI in the Raspberry Pi configuration settings, then use the spidev Python library to communicate with SPI devices. You open the SPI bus, send and receive data, and close the connection when done.
📐

Syntax

Using SPI on Raspberry Pi with Python involves these steps:

  • Import spidev: Load the SPI library.
  • Open SPI bus: Use spi.open(bus, device) where bus is usually 0 and device is 0 or 1 depending on the chip select pin.
  • Set SPI speed: Define the clock speed with spi.max_speed_hz.
  • Transfer data: Use spi.xfer2([data]) to send and receive bytes.
  • Close SPI: Use spi.close() to release the bus.
python
import spidev

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

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

spi.close()
💻

Example

This example shows how to send three bytes over SPI and print the response from the device. It assumes SPI is enabled on your Raspberry Pi.

python
import spidev
import time

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

try:
    # Send bytes 0xDE, 0xAD, 0xBE and receive response
    response = spi.xfer2([0xDE, 0xAD, 0xBE])
    print("Received:", response)
finally:
    spi.close()
Output
Received: [0, 0, 0]
⚠️

Common Pitfalls

Common mistakes when using SPI on Raspberry Pi include:

  • Not enabling SPI in raspi-config before running code.
  • Using wrong bus or device numbers; usually bus 0 and device 0 or 1.
  • Forgetting to set max_speed_hz, which can cause communication errors.
  • Not closing the SPI connection, which can block further access.
  • Ignoring wiring errors like incorrect MOSI, MISO, SCLK, or CS pins.
python
import spidev

spi = spidev.SpiDev()
# Wrong: Not opening SPI bus before transfer
# response = spi.xfer2([0x01])  # This will cause error

# Correct way:
spi.open(0, 0)
spi.max_speed_hz = 50000
response = spi.xfer2([0x01])
spi.close()
📊

Quick Reference

CommandDescription
spi.open(bus, device)Open SPI bus and device (chip select)
spi.max_speed_hz = valueSet SPI clock speed in Hz
spi.xfer2([data])Send and receive list of bytes
spi.close()Close SPI connection
sudo raspi-configEnable SPI interface in Raspberry Pi settings

Key Takeaways

Enable SPI in Raspberry Pi settings before using it in code.
Use the spidev Python library to open, communicate, and close SPI connections.
Set the SPI clock speed with max_speed_hz to match your device requirements.
Always close the SPI connection to free the bus for other uses.
Double-check wiring and bus/device numbers to avoid communication errors.