Main Content

Use Raspberry Pi SPI Interface to Connect to Device

This example shows how to exchange data with an SPI device.


Excessive voltage and current can damage the Raspberry Pi® hardware. Observe the manufacturer’s precautions for handling the Raspberry Pi hardware and connecting it to other devices. For more information, see

Create a connection to the Raspberry Pi hardware using raspi.

mypi = raspi
mypi = 

  raspi with properties:

           DeviceAddress: 'raspberrypi-computername'
                    Port: 18725
               BoardName: 'Raspberry Pi Model B Rev 2'
           AvailableLEDs: {'led0'}
    AvailableDigitalPins: [4 7 8 9 10 11 14 15 17 18 22 23 24 25 27 30 31]
    AvailableSPIChannels: {}
      AvailableI2CBuses: {'i2c-0'  'i2c-1'}
             I2CBusSpeed: 100000

  Supported peripherals


If you encounter errors after running the above command, try using additional arguments (as listed in raspi) or refer to Troubleshoot Connecting Issues to Raspberry Pi Hardware.

By default, SPI is disabled, so AvailableSPIChannels does not show any channels.

Enable SPI and get the channels.

ans = 

    'CE0'    'CE1'

Show the location of the SPI pins, such as GPIO 10 (SPI0_SDO), GPIO 9 (SPI0_SDI), and GPIO 11 (SPI0_SCLK) in the following illustration.


Before continuing, research the manufacturer’s product information to determine which settings the SPI device supports.

Physically connect the Raspberry Pi hardware to one or two SPI devices. Connect the SCLK, SDO, and SDI pins to their counterparts on the SPI devices. Connect the CE0 pin on Raspberry Pi hardware to the CE pin on one SPI device. Connect the CE1 pin on Raspberry Pi hardware to the CE pin on other SPI device.

Create a connection to one of the SPI devices.

myspidevice = spidev(mypi,'CE1')
myspidevice = 
spidev with properties:
           Channel: 'CE1'
              Mode: 0 
       BitsPerWord: 8
             Speed: 500000

The SPI device determines the data speed. Raspberry Pi hardware supports speeds from 500 kHz to 32 MHz (myspidevice.Speed from 500000 to 32000000)

SPI is full duplex. Perform read or write operations concurrently using writeRead. To read data from SPI, send dummy values. To write data to SPI, discard the data it returns.

out = writeRead(myspidevice,[hex2dec('08') hex2dec('D4')])
out = 
         7 211

Clear the SPI device.

clear myspidevice

If you are not using SPI, disable SPI to make additional GPIO pins available.


Clear raspi object.

clear mypi