SPI

What is SPI?

SPI is a communication protocol, it allows devices to communicate in a full-duplex mode (bidirectional) with one device serving as the Master and every other device as the Slave. Bidirectional means that the device can both recieve and send information at the same time. In contrast, a very popular communication method I2C is half-duplex as it can only either receive or send data at a single point in time.

_images/spi_three_slaves.png

It is possible that the pins get labeled with different but similar names:

  • SCLK = Serial Clock

  • MOSI = Master Out Slave In

  • MISO = Master In Slave Out

  • SS# = Slave Select

It is not important that you know the following but make sure that you are using the proper mode for the component that you will be using.

SPI Modes

Non-inverted clock polarity (SCLK is low when SS transitions to low)

  • Mode 0: Data is sampled on rising edge and shifted out on falling edge

  • Mode 1: Data is sampled on falling edge and shifted out on rising edge

Inverted clock polarity (SCLK is high when SS transitions to high)

  • Mode 2: Data is sampled on falling edge and shifted out on rising edge

  • Mode 3: Data is sampled on rising edge and shifted out on falling edge

Some devices will have pins that are specifically for SPI communication so make sure to look up the pinout of the device that you are using (arduino, raspberry pi, etc).

Arduino Pinout: arduinoPinout

Raspberry Pi Pinout: raspberrypiPinout

Library Installation and Usage

  1. To install we need to update the package information for all available sources

    $ sudo apt update
    
  2. This will install pip3 and the python3 developer tools

    $ sudo apt install python3-pip python3-dev -y
    
  3. Instal spidev library

    $ pip3 install spidev -y
    
  4. Test that the install was succesful by running the following on the terminal

    $ python3
    
    >>> import spidev
    

Enabling

Some devices (Arduino does not) require you to enable SPI mode. To enable SPI mode:

  1. Use Raspi-config

    $ sudo raspi-config
    
  2. Select Interfacing Options

  3. Select SPI

  4. Activate <Select>

  5. Activate <Yes>

  6. Reboot