Using Serial Peripheral Interface (SPI) in Raspberry Pi

SPI (Serial Peripheral Interface), establishes communication between multiple peripheral devices or microcontrollers. The SPI interface bus exchanges data between microcontrollers. It also interfaces small peripherals such as shift registers, sensors, and SD cards in Pi. It uses the different clock and data lines along with a select line to choose to communicate with which device. Learn using SPI in Raspberry Pi.

Generally, there are three lines common to all the devices, MISO (Master In, Slave Out) and MOSI (Master Out, Slave In). For device selection, we use SCK Clock Line. Now, let’s see how SPI Communication in Raspberry Pi works.

Configure of SPI in Raspberry Pi

First of all, we will enable SPI in Pi because SPI is turned off by default in the Raspberry Pi. To enable follow below-given steps.

  1. Run sudo raspi-config
  2. Go down and select 5 Interfacing Options
  3. Arrow down and P4 SPI
  4. Select Yes in enable SPI option
  5. Go down and select the Finish button
  6. Select Yes when it asks for a reboot

Sample Python code

Finally, it is code time. This is a sample code for using SPI.

Here first, we enabled SPI in code by, spi = spidev.SpiDev() After that, open a connection to a specific bus and device. Set the SPI Speed in Hz and at last transfer 8-bit value to SPI. So, by using you can transfer or communicate two hardware devices.

For running the python code in Raspberry Pi official link.
Learn basic hardware information about Raspberry Pi 3.

2 thoughts on “Using Serial Peripheral Interface (SPI) in Raspberry Pi”

  1. I wish that you would know better not to make statements like this: “For device selection, we use SCK Clock Line”. SCK Clock line is to manage the data flow. In multi-slave systems the specific Slave Device is selected by Master by activating dedicated CS line.

  2. how to alter this code for multiple sensor connection via spi interface? for example connecting seven same sensors. (sensor detail: ADXL345 accelerometer sensor)

Leave a Reply