Serial Peripheral Interface (SPI): the four wires (MOSI, MISO, SCK, CS), how a transaction works, its pros and cons versus I2C, and a simple Arduino example.

SPI stands for Serial Peripheral Interface, a way for electronic devices like microcontrollers to communicate with sensors or displays. One device (the master) sends a piece of data, the other device (the slave) sends a piece back, and they keep going until the message is complete. SPI uses four wires: MOSI, MISO, SCK, and CS.
For communication, the master sends a series of bits over MOSI while sending clock pulses over SCK. The slave responds over MISO. Each transfer is a “transaction,” and multiple transactions can occur in a row as long as the master keeps CS low to keep the slave selected. Once done, the master raises CS to deselect that slave and can move to another.
Arduino has built-in hardware support for SPI. On most boards the SPI pins are labelled MOSI, MISO, SCK, and SS (sometimes CS). SPI.begin() initializes the interface; digitalWrite(SS, LOW) selects the slave; SPI.transfer() sends and receives data; digitalWrite(SS, HIGH) deselects the slave.
#include <SPI.h>
int csPin = __; // CS pin of the SPI device
void setup() { SPI.begin(); // Initialize SPI interface pinMode(csPin, OUTPUT); // Set CS pin as output digitalWrite(csPin, HIGH); // Deselect the device Serial.begin(9600);}
void loop() { digitalWrite(csPin, LOW); // Select the device SPI.transfer(0x55); // Send data to the device int response = SPI.transfer(0x00); // Receive data from the device digitalWrite(csPin, HIGH); // Deselect the device
Serial.print("Response: "); Serial.println(response); delay(1000);}Here the Arduino sends a byte (0x55) to an SPI device, reads a byte back, and prints it every second. You may need to adjust the SPI mode and clock speed for your specific device.
Originally published on sslabs.in.