Use the Raspberry Pi SPI Interface to Connect to a 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 board.

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

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_MOSI), GPIO 9 (SPI0_MISO), 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, MOSI, and MISO 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 5 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

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

Was this topic helpful?