Sub topic 8
Using the Arduino SPI library and SPISettings
This chapter assumes you know the four SPI signals (SCLK, MOSI, MISO and chip select), the four SPI modes, and the basics of bit order. You should also be comfortable with pinMode, digitalWrite and hexadecimal values. Here you will turn that knowledge into working Arduino code.
What the library does
The Arduino SPI library wraps the hardware SPI peripheral of the microcontroller. The hardware generates the clock and shifts bits in and out for you. Your sketch only decides what to send, when to select a device, and how the bus is configured.
The library gives you one global object, SPI. You include it with #include <SPI.h>. The object exposes these calls:
| Call | Purpose |
|---|---|
| `SPI.begin()` | Configures the SPI pins and enables the hardware as controller |
| `SPI.end()` | Disables the hardware and releases the pins |
| `SPI.beginTransaction(settings)` | Applies clock rate, bit order and mode for one exchange |
| `SPI.endTransaction()` | Releases the bus after an exchange |
| `SPI.transfer(byte)` | Sends one byte and returns the byte received |
| `SPI.transfer(buffer, length)` | Exchanges a whole buffer in place |
| `SPI.transfer16(word)` | Exchanges a 16-bit value |
The library does not manage chip select. You drive that pin yourself with digitalWrite, because only you know which device you want to talk to.
Starting the bus with SPI.begin
SPI.begin() sets the hardware SCLK and MOSI pins as outputs, sets MISO as an input, and drives SCLK and MOSI low. On classic AVR boards such as the Uno it also makes the hardware SS pin (pin 10) an output. This matters because the AVR hardware drops out of controller mode if SS is configured as an input and something pulls it low. Keeping pin 10 as an output avoids that surprise, even if you use another pin for chip select.
Call SPI.begin() once in setup(). Set up each chip-select pin as an output and drive it HIGH (deselected) before or right after you call it, so no peripheral sees a spurious selection while the bus starts.
Describing the bus with SPISettings
An SPISettings object holds three values:
- The maximum clock speed in hertz.
- The bit order,
MSBFIRSTorLSBFIRST. - The data mode,
SPI_MODE0,SPI_MODE1,SPI_MODE2orSPI_MODE3.
SPISettings adcSettings(1000000, MSBFIRST, SPI_MODE0);Take all three values from the peripheral's datasheet. The clock speed is a ceiling, not a promise. The hardware picks the fastest clock it can produce that does not exceed your request. On an Uno running at 16 MHz, the available SPI clocks are 8, 4, 2, 1 MHz and so on, in powers of two. Asking for 3 MHz gives you 2 MHz.
The constants map to the clock polarity (CPOL) and clock phase (CPHA) you studied earlier:
| Constant | CPOL | CPHA | Clock idles | Data sampled on |
|---|---|---|---|---|
| `SPI_MODE0` | 0 | 0 | Low | Rising edge |
| `SPI_MODE1` | 0 | 1 | Low | Falling edge |
| `SPI_MODE2` | 1 | 0 | High | Falling edge |
| `SPI_MODE3` | 1 | 1 | High | Rising edge |
Define settings objects once, as globals or constants, and reuse them. Building one per call works but wastes time.
Wrapping an exchange in a transaction
A transaction is the unit of work on the bus. You begin it, select the device, exchange bytes, deselect, and end it.
#include <SPI.h>
const uint8_t CS_PIN = 10;
const uint8_t READ_FLAG = 0x80; // device-specific: many chips use the top address bit to mean read
uint8_t readRegister(uint8_t reg) {
SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
SPI.transfer(reg | READ_FLAG); // command byte: register address plus read flag
uint8_t value = SPI.transfer(0x00); // send a dummy byte to clock the reply out
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
return value;
}
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH); // keep the peripheral deselected
SPI.begin();
}
void loop() {
Serial.println(readRegister(0x0F), HEX); // register address is an example; take it from your datasheet
delay(1000);
}The order inside the function matters:
beginTransactionfirst, so the hardware is configured before chip select falls.- Chip select LOW next, which starts the frame.
- The transfers.
- Chip select HIGH, which ends the frame.
endTransactionlast.
The 0x80 read flag and the register 0x0F are examples. Many chips use the top address bit to mean "read", but some use a separate command byte or a different bit. Always follow your datasheet.
Notice that SPI.transfer(0x00) is a dummy write. SPI is full duplex, so every byte sent produces a byte received. To read, you must clock, and clocking means sending something. The value 0x00 is a common filler. The byte you get back during the command byte (the first transfer) is usually meaningless, and the code above discards it.
Why transactions exist
Without transactions, you called SPI.setClockDivider(), SPI.setDataMode() and SPI.setBitOrder() once and hoped nothing changed them. Those calls are deprecated. They break as soon as two libraries share the bus with different settings, for example an SD card library and a display library. Each would silently overwrite the other's configuration.
beginTransaction re-applies the full configuration on every exchange, so each caller gets the settings it asked for. On some platforms it also disables interrupts that use SPI, through SPI.usingInterrupt(), to stop an interrupt handler from touching the bus mid-transfer. On many ARM and ESP boards it can take a lock on the bus.
Keep these rules:
- Never nest transactions. Call
endTransactionbefore starting another. - Keep a transaction short. On platforms where it blocks interrupts, a long transaction delays them.
- Do not call
digitalWriteon a chip-select pin outside a transaction unless you are only deselecting it during setup. - Do not leave a transaction open across a
delay()or aSerial.printcall.
Sending data: the transfer family
transfer sends a byte and returns the received byte. Use the return value when it carries data, and ignore it when it does not.
uint8_t reply = SPI.transfer(0xA5);transfer16 sends two bytes in the bit order from the active settings. With MSBFIRST, the high byte goes first. Use it for devices with 16-bit words, such as many DACs.
uint16_t sample = SPI.transfer16(0x0000); // read a 16-bit conversion resultThe buffer form exchanges many bytes in one call:
SPI.transfer(buffer, sizeof(buffer));The bytes you sent are overwritten with the bytes received. If you need to keep the original data, copy it first. A later chapter covers buffers and throughput.
Two devices with different settings
Because each transaction carries its own settings, you can mix devices cleanly. This sketch talks to a sensor that needs mode 3 and a flash chip that needs mode 0.
#include <SPI.h>
const uint8_t CS_SENSOR = 9;
const uint8_t CS_FLASH = 10;
SPISettings sensorSettings(2000000, MSBFIRST, SPI_MODE3);
SPISettings flashSettings(8000000, MSBFIRST, SPI_MODE0);
void selectAndSend(uint8_t csPin, const SPISettings &settings, uint8_t command) {
SPI.beginTransaction(settings);
digitalWrite(csPin, LOW);
SPI.transfer(command);
digitalWrite(csPin, HIGH);
SPI.endTransaction();
}
void setup() {
pinMode(CS_SENSOR, OUTPUT);
pinMode(CS_FLASH, OUTPUT);
digitalWrite(CS_SENSOR, HIGH);
digitalWrite(CS_FLASH, HIGH);
SPI.begin();
}
void loop() {
selectAndSend(CS_SENSOR, sensorSettings, 0x01); // command values are placeholders
selectAndSend(CS_FLASH, flashSettings, 0x02);
delay(100);
}Both chip-select pins are driven HIGH before SPI.begin() finishes, so neither device listens while the other is addressed.
Platform differences
The API is the same on most boards, but details differ.
- Pins. On the Uno, MOSI, MISO and SCK are pins 11, 12 and 13. On a Mega they are 51, 50 and 52. Many ARM and ESP boards have their own pin maps, and some let you choose pins. Check your board's pinout.
- Clock accuracy. AVR boards use power-of-two dividers. ARM cores usually allow finer steps, so the real clock is closer to the requested value.
- Speed limits. A 16 MHz AVR tops out at 8 MHz. Faster boards reach tens of megahertz, but the wiring and the peripheral usually limit you first.
- Voltage. A 5 V board talking to a 3.3 V peripheral needs level shifting. The library does nothing about this.
Common errors
- Reading all 0xFF or all 0x00. MISO is floating or disconnected, the peripheral is not selected, or the mode is wrong. A peripheral that is not driving MISO often reads as 0xFF because of a pull-up, or as 0x00 if the line is shorted low.
- Data shifted by one bit. The mode is wrong. Compare CPOL and CPHA with the datasheet timing diagram.
- Bytes reversed within a word. Bit order or
transfer16byte order does not match the device. - Works at 1 MHz, fails at 8 MHz. The wiring or the peripheral cannot keep up. Lower the speed first, then investigate.
- One device works until another is added. A second chip-select pin is floating, or two devices were given the same pin.
- Compile error on
SPISettingsas a parameter. Pass it byconst SPISettings &, as in the example above.
Exercise
A sketch sets up an accelerometer that needs 4 MHz, MSB first, with the clock idling high and data sampled on the rising edge. Write the SPISettings declaration. Then say what clock the hardware produces on a 16 MHz Uno if you request 3 MHz instead.
Show answer
Idle high with sampling on the rising edge is CPOL 1 and CPHA 1, which is SPIMODE3. The declaration is `SPISettings accelSettings(4000000, MSBFIRST, SPIMODE3);`. On a 16 MHz Uno the available clocks are powers-of-two divisions of the system clock (8, 4, 2, 1 MHz and so on), and the hardware never exceeds the request, so a 3 MHz request gives 2 MHz.
Exercise
A read function returns 0xFF every time, even though the datasheet says the register should hold 0x33. List three causes you would check first.
Show answer
Check that the chip-select pin is set to OUTPUT and actually goes LOW during the transfer. Check that MISO is wired to the peripheral's output pin and that the peripheral is powered at a compatible voltage. Check that the SPISettings mode matches the datasheet. A wrong read flag or register address, or a clock speed above the device's limit, are further candidates.