SPI Communication
High-speed SPI communication using the SPI library, SPI settings, and SPI devices.
Key idea:
SPI (Serial Peripheral Interface) uses four wires for high-speed full-duplex communication: MOSI, MISO, SCK, and SS/CS. It's faster than I2C but requires more pins.
SPI Wiring
Arduino MOSI (Pin 11) ─────── MOSI
Arduino MISO (Pin 12) ─────── MISO
Arduino SCK (Pin 13) ─────── SCK
Arduino SS (Pin 10) ─────── CS/SS
3.3V/5V ────────────────────── VCC
GND ────────────────────────── GND
Arduino SPI Library
#include <SPI.h>
#define CS_PIN 10
void setup() {
Serial.begin(9600);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin(); // Initialize SPI
SPI.setClockDivider(SPI_CLOCK_DIV16); // Set clock speed (1MHz @ 16MHz)
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
}
void loop() {
// Select device
digitalWrite(CS_PIN, LOW);
// Send command and read response
byte response = SPI.transfer(0x00); // Send dummy byte, receive response
// Deselect device
digitalWrite(CS_PIN, HIGH);
Serial.print("Response: 0x");
Serial.println(response, HEX);
delay(100);
}SPI Settings
| Setting | Options | Description |
|---|---|---|
| Clock Speed | SPI_CLOCK_DIV2 to SPI_CLOCK_DIV128 | Divider from system clock |
| Bit Order | MSBFIRST, LSBFIRST | Most/Least significant bit first |
| Data Mode | SPI_MODE0-SPI_MODE3 | Clock polarity/phase (CPOL/CPHA) |
Multiple SPI Devices
#define CS_SENSOR1 10
#define CS_SENSOR2 9
void readSensor(int csPin, byte cmd) {
digitalWrite(csPin, LOW);
byte result = SPI.transfer(cmd);
digitalWrite(csPin, HIGH);
return result;
}
void loop() {
byte s1 = readSensor(CS_SENSOR1, 0x00);
byte s2 = readSensor(CS_SENSOR2, 0x00);
// Process both sensors
}Key Takeaways
SPI.begin()andSPI.transfer()for communication- SPI settings: clock speed, bit order, mode
- MOSI, MISO, SCK, and SS pins
- Connecting multiple SPI devices with separate CS pins
Resources
- Arduino.cc - SPI Library: https://www.arduino.cc/reference/en/language/functions/communication/spi/
- Article: Arduino SPI Communication - https://www.arduino.cc/en/Tutorial/BuiltInExamples/BarometricPressureSensor