Bird
0
0
Raspberry Piprogramming~5 mins

spidev library usage in Raspberry Pi

Choose your learning style9 modes available
Introduction

The spidev library helps your Raspberry Pi talk to devices using SPI, a way to send data quickly between chips.

You want to read data from a sensor connected via SPI.
You need to control an SPI-based display or LED driver.
You want to send commands to an SPI flash memory chip.
You are building a project that communicates with an SPI device like an ADC or DAC.
You want to learn how to connect and communicate with hardware using Raspberry Pi.
Syntax
Raspberry Pi
import spidev

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

response = spi.xfer2(data_bytes)

spi.close()

bus and device select which SPI channel and device you use (usually bus 0, device 0 or 1).

spi.xfer2() sends and receives data at the same time, returning the response from the device.

Examples
This example opens SPI bus 0 device 0, sends three bytes, and prints the response.
Raspberry Pi
import spidev

spi = spidev.SpiDev()
spi.open(0, 0)  # Open SPI bus 0, device 0
spi.max_speed_hz = 50000

response = spi.xfer2([0x01, 0x02, 0x03])
print(response)

spi.close()
This example communicates with device 1 on bus 0, sending one byte and printing the reply.
Raspberry Pi
import spidev

spi = spidev.SpiDev()
spi.open(0, 1)  # Open SPI bus 0, device 1
spi.max_speed_hz = 1000000

response = spi.xfer2([0xAA])
print(response)

spi.close()
Sample Program

This program opens SPI bus 0 device 0, sends one byte (0x10), prints what it sends and receives, then closes the connection safely.

Raspberry Pi
import spidev
import time

# Create SPI object
spi = spidev.SpiDev()

# Open SPI bus 0, device 0
spi.open(0, 0)

# Set SPI speed to 100kHz
spi.max_speed_hz = 100000

try:
    # Send a byte and receive response
    send_data = [0x10]
    print(f"Sending: {send_data}")
    response = spi.xfer2(send_data)
    print(f"Received: {response}")

    # Wait a bit
    time.sleep(1)

finally:
    # Close SPI connection
    spi.close()
OutputSuccess
Important Notes

Make sure SPI is enabled on your Raspberry Pi using raspi-config before using spidev.

Use spi.xfer2() to send and receive data in one call; it returns a list of bytes received.

Always close the SPI connection with spi.close() to free the device.

Summary

spidev lets your Raspberry Pi talk to SPI devices by sending and receiving bytes.

Open the SPI bus and device, set speed, use xfer2() to communicate, then close it.

Enable SPI on your Pi first and always close the connection when done.