Sub topic 2
Bit order and word size
This chapter assumes you can write a basic sketch with setup() and loop(), use digitalWrite, and read hexadecimal values and bitwise operators.
Bit order and word size
An SPI transfer sends one byte at a time. The bit order sets which bit leaves the controller first. MSBFIRST sends bit 7 first, and LSBFIRST sends bit 0 first. Most peripherals use MSBFIRST, but the datasheet states the order you must use.
A mismatch reverses each byte. If you send 0x01 to a peripheral that expects LSBFIRST, it reads 0x80. The word size is the number of bits per transfer. The Arduino SPI.transfer() call moves 8 bits.
Choosing a clock rate within device and board limits
Pick the slowest rate that meets your timing needs, and never exceed the device's maximum SCK frequency from its datasheet. Start near 1 MHz, then raise the rate while you test. Long jumper wires and breadboards add ringing at high clock speeds, so a rate that works on the bench can fail in the final wiring.
Using the Arduino SPI library and SPISettings
SPISettings bundles the clock rate, bit order and mode into one object. The following sketch reads one byte from a device. It assumes the device's command byte is 0x9F, which you must replace with the value from your datasheet.
#include <SPI.h>
const uint8_t CS_PIN = 10;
const SPISettings deviceSettings(1000000, MSBFIRST, SPI_MODE0);
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
}
void loop() {
SPI.beginTransaction(deviceSettings);
digitalWrite(CS_PIN, LOW);
uint8_t reply = SPI.transfer(0x9F);
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
Serial.println(reply);
delay(500);
}Transactions: keeping settings correct on a shared bus
beginTransaction applies the settings and holds the bus until endTransaction runs. Place chip select inside the transaction. Then a second device with different settings cannot change the clock or bit order partway through your exchange.
> Each beginTransaction needs a matching endTransaction. A missing call can leave interrupts disabled and the bus settings applied for the rest of the program.
Exercise:
Exercise
A peripheral expects LSBFIRST, but your code uses MSBFIRST. You send 0x01 and read back 0x80. Why?
Show answer
The bit order reverses within each byte. Bit 0 (the 1) is sent as the last bit under MSBFIRST, and the receiver reads it as the top bit, giving 0x80. Set LSBFIRST to match the datasheet.