Bird
0
0
Arduinoprogramming~5 mins

SPI library usage in Arduino

Choose your learning style9 modes available
Introduction

The SPI library helps your Arduino talk to other devices fast using a simple wire connection.

When you want to connect sensors like temperature or light sensors to your Arduino.
When you need to control displays such as LCD or OLED screens.
When communicating with memory chips like SD cards.
When connecting to other microcontrollers or modules that use SPI communication.
Syntax
Arduino
SPI.begin();
SPI.transfer(data);

SPI.begin() starts the SPI bus.

SPI.transfer(data) sends and receives one byte of data.

Examples
Start SPI and send the byte 0x42, then save the reply in response.
Arduino
SPI.begin();
byte response = SPI.transfer(0x42);
Set SPI speed to 4 MHz, send 0xFF, then end the transaction.
Arduino
SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
SPI.transfer(0xFF);
SPI.endTransaction();
Sample Program

This program starts SPI, sends one byte (0x55), and prints what it sent and received on the Serial Monitor.

Arduino
#include <SPI.h>

void setup() {
  Serial.begin(9600);
  SPI.begin();
  byte dataToSend = 0x55;
  byte receivedData = SPI.transfer(dataToSend);
  Serial.print("Sent: 0x");
  Serial.println(dataToSend, HEX);
  Serial.print("Received: 0x");
  Serial.println(receivedData, HEX);
}

void loop() {
  // Nothing here
}
OutputSuccess
Important Notes

SPI.transfer sends and receives data at the same time.

Always call SPI.begin() before using SPI functions.

Use SPI.beginTransaction() and SPI.endTransaction() to set speed and mode safely.

Summary

SPI library lets Arduino talk fast with other devices using a few wires.

Use SPI.begin() to start and SPI.transfer() to send/receive bytes.

Set speed and mode with SPI.beginTransaction() for better control.