Sub topic 9
Transactions: keeping settings correct on a shared bus
This chapter assumes you can write an Arduino sketch that uses SPI.transfer(). It also assumes you know what the four SPI modes mean and how chip select frames a transfer. The goal is to show why every exchange should be wrapped in SPI.beginTransaction() and SPI.endTransaction(), and what those calls do.
The problem: one bus, several sets of settings
A single SPI bus often carries peripherals that need different configurations. A sensor might need mode 3 at 2 MHz. A flash chip might need mode 0 at 8 MHz. The controller has one SPI hardware block, so one set of settings is active at any moment.
If you configure the bus once in setup(), you have three problems:
- Each peripheral needs its own settings, so you must reconfigure the bus before each exchange.
- Changing settings between exchanges is easy to forget. The bug shows up as garbled data from only one device.
- Code that runs asynchronously, such as an interrupt handler or a library you did not write, may change the settings or use the bus while your exchange is in progress.
Transactions address all three. A transaction is a bracketed region of code in which the bus is configured for one peripheral and protected from interference.
The API
SPI.beginTransaction(SPISettings(clock, bitOrder, dataMode));
// ... assert chip select, transfer, release chip select ...
SPI.endTransaction();SPISettings bundles the three values the peripheral's datasheet specifies: maximum clock rate in hertz, bit order (MSBFIRST or LSBFIRST), and mode (SPI_MODE0 to SPI_MODE3). beginTransaction() applies them to the hardware. endTransaction() marks the bus as free for the next user.
Older sketches use setClockDivider(), setDataMode() and setBitOrder(). These change global state with no scope and are deprecated. Use SPISettings in new code.
| Approach | Where settings live | Safe with several devices | Safe with interrupts using SPI |
|---|---|---|---|
| `setDataMode()` and related calls | Global, set once or ad hoc | Only if you remember to reset them every time | No |
| `beginTransaction()` with `SPISettings` | Per exchange | Yes | Yes, when used as described below |
The correct order of calls
The order matters:
SPI.beginTransaction(settings)- Drive chip select low.
- Transfer bytes.
- Drive chip select high.
SPI.endTransaction()
The settings go in before chip select goes low because the mode determines the idle level of SCLK. If the previous device used mode 0 (idle low) and this one needs mode 3 (idle high), changing the mode moves SCLK from low to high. If the target peripheral is already selected, it sees that change as a clock edge and may shift in a spurious bit. Applying the settings while every chip select is high means no peripheral is listening during the change.
Chip select goes high before endTransaction() for the mirror reason: the frame is closed while the settings it was opened under are still in force.
A helper that cannot forget the pairing
The most common transaction bug is an early return between beginTransaction() and endTransaction(). Chip select stays low and the bus stays claimed. A small C++ guard object removes that risk, because its destructor runs on every exit path.
#include <SPI.h>
class SpiFrame {
public:
SpiFrame(uint8_t csPin, const SPISettings &settings) : cs_(csPin) {
SPI.beginTransaction(settings);
digitalWrite(cs_, LOW);
}
~SpiFrame() {
digitalWrite(cs_, HIGH);
SPI.endTransaction();
}
private:
uint8_t cs_;
};
const uint8_t CS_SENSOR = 9;
const uint8_t CS_FLASH = 10;
const SPISettings sensorSettings(2000000, MSBFIRST, SPI_MODE3);
const SPISettings flashSettings(8000000, MSBFIRST, SPI_MODE0);
uint8_t readSensor(uint8_t reg) {
SpiFrame frame(CS_SENSOR, sensorSettings);
SPI.transfer(reg | 0x80); // read flag is device-specific
return SPI.transfer(0x00); // dummy byte clocks the reply out
}
uint8_t readFlashStatus() {
SpiFrame frame(CS_FLASH, flashSettings);
SPI.transfer(0x05); // placeholder command; use your chip's opcode
return SPI.transfer(0x00);
}
void setup() {
Serial.begin(115200);
pinMode(CS_SENSOR, OUTPUT);
pinMode(CS_FLASH, OUTPUT);
digitalWrite(CS_SENSOR, HIGH);
digitalWrite(CS_FLASH, HIGH);
SPI.begin();
}
void loop() {
Serial.println(readSensor(0x0F), HEX);
Serial.println(readFlashStatus(), HEX);
delay(1000);
}Each function returns from inside the frame's scope. The destructor still raises chip select and ends the transaction. Placeholder opcodes and register addresses must come from your datasheets.
The SPISettings objects are built once, at file scope. Constructing them is cheap, but on some cores the constructor computes a clock divider. Building them once keeps that work out of the exchange.
What `beginTransaction()` protects against
The guarantee depends on the board's core, so check its documentation. The usual pieces are these:
- Settings are applied every time. Whatever the previous user configured is replaced. This is the portable guarantee that works on every core.
- Interrupt protection on AVR. The classic AVR core does not disable all interrupts. It masks only the interrupts you registered with
SPI.usingInterrupt(). Other interrupts keep running, and if their handlers touch SPI, you get corrupted exchanges. - Bus locking on some other cores. Some cores, such as ESP32's, take a lock in
beginTransaction()and release it inendTransaction(). This keeps other tasks from using the bus mid-exchange.
Keeping interrupts away from the bus
The simplest and most portable pattern is to avoid SPI inside the handler. Set a flag in the handler and do the exchange in loop().
#include <SPI.h>
const uint8_t CS_PIN = 10;
const uint8_t IRQ_PIN = 2; // data-ready line from the peripheral
volatile bool dataReady = false;
void onDataReady() {
dataReady = true; // no SPI calls here
}
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
pinMode(IRQ_PIN, INPUT);
SPI.begin();
attachInterrupt(digitalPinToInterrupt(IRQ_PIN), onDataReady, FALLING);
}
void loop() {
if (dataReady) {
dataReady = false;
SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
uint8_t value = SPI.transfer(0x00);
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
Serial.println(value, HEX);
}
}If you cannot avoid SPI in a handler, on AVR call SPI.usingInterrupt(digitalPinToInterrupt(IRQ_PIN)) in setup(). Then beginTransaction() will mask that interrupt for the duration of the transaction, and it fires after endTransaction(). The cost is added interrupt latency, which is bounded by the longest transaction. Keep transactions short.
Transaction length and what belongs inside
A transaction should cover one chip-select frame, not a whole task. Keep these points in mind:
- Put only bus activity inside. Do not call
delay(),Serial.print()or sensor math inside. Every microsecond spent there delays any interrupt masked byusingInterrupt()and, on locking cores, other tasks that need the bus. - Keep a multi-byte frame in one transaction. Many peripherals treat a rise of chip select as the end of a command. Splitting one command across two chip-select frames usually breaks it.
- Do not nest transactions. Calling
beginTransaction()twice withoutendTransaction()between them is not supported. On a locking core it can deadlock. A function that opens a transaction should not be called from inside another one. - Some operations need several frames. A flash write often needs a write-enable frame, then the write frame, then status polling. Each is its own transaction with chip select raised in between, because the chip requires it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| One device works, the other returns constant `0xFF` or `0x00` | The second device runs with the first device's mode or clock | Give each device its own `SPISettings` and wrap every exchange |
| Occasional corrupted reads that disappear when interrupts are off | An interrupt handler uses SPI inside a transaction | Use a flag, or register the interrupt with `usingInterrupt()` on AVR |
| Bus stops responding after a code change | An early `return` skipped `endTransaction()` or the chip-select release | Use a guard object like `SpiFrame` |
| First byte after switching devices is wrong | Chip select was lowered before the new settings were applied | Call `beginTransaction()` first, then lower chip select |
Exercise
A sketch reads a sensor that needs SPIMODE3 and a flash chip that needs SPIMODE0. A teammate writes digitalWrite(CS_SENSOR, LOW); SPI.beginTransaction(sensorSettings); .... The sensor sometimes returns a wrong first bit. Explain why, and give the corrected order.
Show answer
The flash chip left SCLK idle low (mode 0), and the sensor needs it idle high (mode 3). Because chip select is already low when the settings are applied, the sensor sees SCLK rise as a clock edge and shifts in a spurious bit. The correct order is SPI.beginTransaction(sensorSettings), then digitalWrite(CS_SENSOR, LOW), then the transfer, then digitalWrite(CS_SENSOR, HIGH), then SPI.endTransaction().
Exercise
Why is it a bad idea to call Serial.println() between beginTransaction() and endTransaction() on an AVR board where an interrupt was registered with SPI.usingInterrupt()?
Show answer
While the transaction is open, that registered interrupt is masked. Serial output is slow, so the interrupt is delayed for the whole print and events can be missed or handled late. Only bus activity belongs inside a transaction, so read the data into a variable and print it after endTransaction().