Sub topic 12
Bulk transfers and getting more throughput
This chapter assumes you can already send single bytes with SPI.transfer(), wrap exchanges in SPI.beginTransaction() and SPI.endTransaction(), and read a datasheet's command format. It covers what limits SPI throughput on an Arduino and how to raise it.
Where the time goes
The clock rate in SPISettings sets how fast bits move while the hardware is shifting. It does not set how many bytes per second your sketch moves. Between bytes, your code spends time on things the clock rate does not affect:
- The function call for each
SPI.transfer(). - Waiting for the hardware to finish shifting a byte.
- Toggling chip select with
digitalWrite(), which is slow on many AVR boards. - Starting and ending a transaction.
- Any reads or writes of command and address bytes before the payload.
At 8 MHz, one byte takes 1 µs on the wire. If each call adds several microseconds of overhead, the bus sits idle most of the time. Raising the clock then gains almost nothing. The fix is to send more data per call and per chip-select frame.
Frames: one chip select per burst
Many peripherals, such as flash chips, displays and SD cards, accept a command followed by a long run of data bytes, all inside one chip-select frame. If you release chip select after every byte, the device treats each byte as a new command. That is both slow and wrong.
A burst frame has three benefits. It removes N−1 chip-select toggles, it removes N−1 transaction setups, and it matches how the device expects to receive the data. Check the datasheet for a maximum burst length. Some devices wrap around inside a page, and some limit a write to 256 bytes.
Buffer transfers with SPI.transfer(buffer, size)
The Arduino SPI library has a form that takes a pointer and a length:
SPI.transfer(buffer, size);It sends each byte of buffer and replaces that byte with the byte received at the same time. This works because SPI is full duplex. The call returns nothing, and the original data is gone after it returns.
#include <SPI.h>
const uint8_t CS_PIN = 10;
uint8_t buffer[64];
void setup() {
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
for (uint8_t i = 0; i < sizeof(buffer); i++) {
buffer[i] = i; // data to send
}
SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
SPI.transfer(buffer, sizeof(buffer)); // received bytes overwrite buffer in place
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void loop() {}On AVR boards, the library's buffer loop is tighter than calling SPI.transfer(byte) 64 times from your own code. On some other cores, the buffer call also uses DMA (direct memory access, where hardware copies data without the CPU). The exact speedup depends on your board and core, so measure it.
Writing without keeping the replies
When you only write, the received bytes are junk, and overwriting your buffer destroys data you may want to resend. Two options exist:
- Copy the data to a scratch buffer first, then transfer the copy.
- On cores that provide it, use the three-argument form
SPI.transfer(txBuffer, rxBuffer, size). It leavestxBufferuntouched. This overload is not available on every core, so check your board's SPI library.
Reading a block
To read, send dummy bytes. Fill the buffer with 0x00 (or whatever the datasheet says to send during a read), transfer it, and use the buffer afterwards as received data.
#include <SPI.h>
const uint8_t CS_PIN = 10;
const uint8_t CMD_READ = 0x03; // typical "read data" command on SPI flash; confirm in your datasheet
void readBlock(uint32_t address, uint8_t *dest, size_t length) {
SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
SPI.transfer(CMD_READ);
SPI.transfer((address >> 16) & 0xFF);
SPI.transfer((address >> 8) & 0xFF);
SPI.transfer(address & 0xFF);
memset(dest, 0x00, length); // dummy bytes to clock the data out
SPI.transfer(dest, length); // dest now holds the received data
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
uint8_t data[16];
readBlock(0, data, sizeof(data));
for (uint8_t i = 0; i < sizeof(data); i++) {
Serial.println(data[i], HEX);
}
}
void loop() {}The command and address use single-byte calls, which is fine. They are four bytes against a payload that may be hundreds. The saving comes from the payload.
Measuring throughput
Do not guess. Time a known transfer with micros() and compute bytes per second.
#include <SPI.h>
const uint8_t CS_PIN = 10;
uint8_t buf[128];
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
}
void loop() {
SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
uint32_t start = micros();
for (uint8_t i = 0; i < sizeof(buf); i++) {
SPI.transfer(buf[i]); // byte by byte
}
uint32_t byteLoop = micros() - start;
start = micros();
SPI.transfer(buf, sizeof(buf)); // one call
uint32_t bulk = micros() - start;
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
Serial.print("byte loop us: ");
Serial.println(byteLoop);
Serial.print("bulk us: ");
Serial.println(bulk);
delay(2000);
}Run it with nothing attached to MISO, or with a device that tolerates stray clocks while deselected. In this test chip select drives a pin with no device listening, which keeps the test harmless. Compare the two times against the ideal: 128 bytes at 8 MHz is 128 µs of pure shifting. The gap between your measured time and 128 µs is overhead.
Ways to get more throughput
Work through these in order. Each one costs more effort than the one before.
| Step | What to do | Typical effect | Risk |
|---|---|---|---|
| 1 | Use burst frames: one chip select per burst | Removes per-byte CS and transaction cost | Device may limit burst length |
| 2 | Use `SPI.transfer(buffer, size)` | Cuts call overhead | Overwrites your buffer |
| 3 | Raise the clock toward the device maximum | Shortens time per byte | Fails if wiring or the device cannot keep up |
| 4 | Use fast pin writes for chip select | Cuts CS toggle time | Board-specific code |
| 5 | Use DMA or a core with asynchronous SPI | CPU is free during the transfer | Depends on the core, more complex |
| 6 | Use dual or quad SPI on devices that support it | More data lines per clock | Needs matching hardware and a different library |
Step 3 deserves caution. A higher clock only helps if the signal stays clean. Long jumper wires on a breadboard often fail above a few MHz, as the earlier chapter on wiring and signal integrity explains. Raise the clock in steps and verify the data at each step, for example by writing a pattern and reading it back.
Also remember the controller's own limit. A classic AVR Arduino runs SPI at up to half the CPU clock, so 8 MHz on a 16 MHz board. Asking for more gives you the highest rate the hardware allows, not what you requested.
Common mistakes
- Reusing a buffer after
transfer(buffer, size). The data you meant to send again is now the reply. Reload it each time. - Releasing chip select mid-burst. The device restarts its command parser, and the rest of your bytes are read as new commands.
- Exceeding the device's page or burst limit. Writes may wrap and overwrite earlier data in the same page. Split long writes at page boundaries.
- Sending a buffer larger than RAM allows. A 2 KB buffer on a board with 2 KB of RAM will crash. Move data in chunks of 64 to 256 bytes.
- Raising the clock before fixing the framing. If overhead dominates, a faster clock changes almost nothing.
- Ignoring write-completion time. Flash and EEPROM devices need time after a write command to finish internally. Throughput there is limited by the device's program time, which no clock rate changes. Poll the status register as the datasheet describes.
Chunking large payloads
For data larger than your buffer, loop over chunks inside one chip-select frame. The frame stays open across the loop, so the device sees one continuous burst.
#include <SPI.h>
const uint8_t CS_PIN = 10;
void sendLarge(const uint8_t *data, size_t total) {
uint8_t chunk[32];
SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
size_t sent = 0;
while (sent < total) {
size_t n = min(sizeof(chunk), total - sent);
memcpy(chunk, data + sent, n); // copy, because transfer overwrites it
SPI.transfer(chunk, n);
sent += n;
}
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void setup() {
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
static uint8_t image[200];
sendLarge(image, sizeof(image));
}
void loop() {}The copy into chunk also protects the source array, so you can resend it later.
Exercise
A sketch sends 256 bytes to a display by calling SPI.transfer(byte) in a loop. Each iteration also toggles chip select low and high with digitalWrite. The clock is 4 MHz, yet the transfer takes far longer than 512 µs, and the display shows garbage. Give two changes that fix the speed and one reason the display shows garbage.
Show answer
Lower chip select once before the loop and raise it once after it, so the whole payload is one frame. Then use SPI.transfer(buffer, size), possibly in chunks, to cut per-call overhead. The garbage appears because toggling chip select after every byte makes the display restart its command parser each time, so it reads data bytes as new commands. (256 bytes at 4 MHz is 256 × 8 bits ÷ 4 MHz = 512 µs of pure shifting.)
Exercise
After calling SPI.transfer(buf, 16) to write a block, you call it again with the same buf to write the same block to a second device. The second device receives unexpected values. Why, and how do you fix it?
Show answer
The first call replaced each byte in buf with the byte received from the first device. The second call sent those received bytes. Fix it by restoring buf from a copy before each transfer, or by using a transfer overload with separate transmit and receive buffers if your core provides one.