पाठ 12 / 25
SPI and Using Libraries Responsibly
Fast buses and third-party code.
SPI, and choosing a bus
SPI uses a clock (SCK), data out (COPI/MOSI), data in (CIPO/MISO) and one chip select (CS) line per device. It is full-duplex and typically much faster than I2C, which suits displays, SD cards and fast ADCs, at the cost of more pins. Devices differ in clock speed, bit order and SPI mode, so wrap each exchange in SPI.beginTransaction(SPISettings(...)). On the Uno R3 SPI is on pins 11 (COPI), 12 (CIPO), 13 (SCK) and usually 10 (CS); check your board's pinout. Rule of thumb: UART for PC links and modules like GPS, I2C for many slow sensors on two wires, SPI for speed. Libraries hide register details, but read their examples, check which pins, timers and how much RAM they use, prefer actively maintained ones, and pin versions in your project.
One SPI transaction
Reads a register from a hypothetical device; the command byte and settings come from your device's datasheet.
#include <SPI.h>
const uint8_t CS_PIN = 10;
uint8_t readRegister(uint8_t reg) {
SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0)); // 1 MHz
digitalWrite(CS_PIN, LOW); // select the device
SPI.transfer(reg | 0x80); // many devices use bit 7 = read
uint8_t value = SPI.transfer(0x00); // clock out a dummy byte, read reply
digitalWrite(CS_PIN, HIGH); // deselect
SPI.endTransaction();
return value;
}
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH); // idle = not selected
SPI.begin();
Serial.println(readRegister(0x0F), HEX);
}
void loop() {}Libraries cost RAM
A display library may allocate a full frame buffer; a 128x64 monochrome OLED buffer is 1 KB, half of an Uno R3's 2 KB SRAM. Check memory usage after compiling.
त्वरित जाँच: Which bus is usually best for a fast display or SD card?
- I2C at 100 kHz
- SPI
- A software UART at 9600 baud
- analogWrite
Answer
SPI — SPI is full-duplex and typically supports much higher clock speeds.