Sub topic 6
Bit order and word size
This chapter covers two settings that decide how the bits of each byte are arranged on the wire: bit order and word size. A wrong value for either one gives you data that looks almost right but is scrambled. That is a hard fault to spot, so it is worth understanding both settings before you meet them in a datasheet.
Prerequisites
This chapter assumes you can:
- Write a basic sketch with
setupandloop. - Use binary and hexadecimal numbers and the bitwise operators
<<,>>,&and|. - Recognize the four SPI signals and the shift-register exchange from the earlier chapters.
- Name the SPI mode (CPOL and CPHA) that a peripheral needs.
What bit order means
SPI sends the bits of a word one at a time, one bit per clock cycle. Bit order decides which bit goes first.
- MSB first (most significant bit first) sends bit 7 first and bit 0 last. The value
0xA5(binary10100101) goes out as1, 0, 1, 0, 0, 1, 0, 1. - LSB first (least significant bit first) sends bit 0 first and bit 7 last. The same
0xA5goes out as1, 0, 1, 0, 0, 1, 0, 1read from the other end.
0xA5 is a palindrome in binary, so both orders look identical. That makes it a bad test value. Use 0x01 instead:
| Value | Binary | MSB first on the wire | LSB first on the wire |
|---|---|---|---|
| `0x01` | `00000001` | `0 0 0 0 0 0 0 1` | `1 0 0 0 0 0 0 0` |
| `0x80` | `10000000` | `1 0 0 0 0 0 0 0` | `0 0 0 0 0 0 0 1` |
| `0xB2` | `10110010` | `1 0 1 1 0 0 1 0` | `0 1 0 0 1 1 0 1` |
If the controller and the peripheral disagree, the peripheral receives the bit-reversed value. Sending 0x01 to a chip that expects MSB first while you transmit LSB first delivers 0x80.
Why most devices use MSB first
Nearly all SPI peripherals expect MSB first. This matches how multi-bit numbers are written, and it lets a receiver build a value by shifting each new bit in from the right. The bit-banged example from the topic's code shows this pattern:
// Bit-banged SPI mode 0 (CPOL=0, CPHA=0), most significant bit first.
// Data is placed on MOSI while SCK is low and sampled on the rising edge.
const uint8_t SCK_PIN = 13;
const uint8_t MOSI_PIN = 11;
const uint8_t MISO_PIN = 12;
uint8_t softTransferMode0(uint8_t out) {
uint8_t in = 0;
for (int8_t bit = 7; bit >= 0; bit--) {
digitalWrite(MOSI_PIN, (out >> bit) & 1); // set up data while the clock is low
digitalWrite(SCK_PIN, HIGH); // rising edge: both sides sample
in = (in << 1) | (digitalRead(MISO_PIN) ? 1 : 0);
digitalWrite(SCK_PIN, LOW); // falling edge: the next bit is shifted out
}
return in;
}
void setup() {
pinMode(SCK_PIN, OUTPUT);
pinMode(MOSI_PIN, OUTPUT);
pinMode(MISO_PIN, INPUT);
digitalWrite(SCK_PIN, LOW); // idle low for CPOL = 0
}
void loop() {}The loop counts bit from 7 down to 0, so bit 7 leaves first. To make this LSB first, count from 0 up to 7 for sending. On the receive side you would also have to place each incoming bit at its own position instead of shifting left, because the first bit received is now bit 0:
// LSB-first version of the loop body (mode 0 timing unchanged).
for (uint8_t bit = 0; bit < 8; bit++) {
digitalWrite(MOSI_PIN, (out >> bit) & 1);
digitalWrite(SCK_PIN, HIGH);
if (digitalRead(MISO_PIN)) in |= (1 << bit);
digitalWrite(SCK_PIN, LOW);
}Setting bit order in the Arduino library
The Arduino SPI library takes bit order as the second argument of SPISettings. The constants are MSBFIRST and LSBFIRST.
#include <SPI.h>
const uint8_t CS_PIN = 10;
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
SPI.beginTransaction(SPISettings(1000000, LSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
uint8_t reply = SPI.transfer(0x01); // goes out as 1 0 0 0 0 0 0 0
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
Serial.println(reply, HEX);
}
void loop() {}Because the order is part of SPISettings, it is applied at beginTransaction and can differ from one peripheral to the next on the same bus. The multi-device chapter builds on this.
The older calls SPI.setBitOrder(), SPI.setDataMode() and SPI.setClockDivider() still compile on many boards but are deprecated. They change global state outside any transaction, so prefer SPISettings.
What a datasheet says about bit order
Datasheets state bit order in one of three ways:
- Directly, for example "data is shifted MSB first".
- Through a timing diagram, where the first bit after chip select falls is labeled D7 (MSB first) or D0 (LSB first).
- Not at all. Most chips then default to MSB first, but confirm it with a test.
Some devices mix orders. A few LED drivers and shift registers take LSB first, and some chips send multi-byte numbers with the low byte first, which is a separate matter described below.
Bit order versus byte order
Do not confuse bit order with byte order, which is also called endianness. Bit order controls the order of bits inside one byte on the wire. Byte order controls which byte of a multi-byte value comes first, and the SPI hardware has no knowledge of it.
A 16-bit reading such as 0x1234 can arrive as 0x12 then 0x34 (big-endian) or 0x34 then 0x12 (little-endian). Each byte is still sent MSB first. You combine them in code:
// Combine two received bytes into a 16-bit value.
uint16_t fromBigEndian(uint8_t first, uint8_t second) {
return (static_cast<uint16_t>(first) << 8) | second;
}
uint16_t fromLittleEndian(uint8_t first, uint8_t second) {
return (static_cast<uint16_t>(second) << 8) | first;
}Choose the function the datasheet describes. Setting LSBFIRST does not swap bytes.
Word size
Word size is the number of bits in one unit of transfer. The Arduino SPI hardware on AVR boards works with 8-bit words. SPI.transfer() moves one byte, SPI.transfer16() moves two bytes in a single call, and SPI.transfer(buffer, size) moves an array.
Many peripherals use other lengths: 12-bit ADC results, 10-bit DAC codes, or 24-bit and 32-bit commands. SPI itself places no limit on the count of clock pulses while chip select is low. A "word" is therefore a convention between you and the device, not a feature of the bus.
Building odd word sizes from bytes
When a device wants a length that is not a multiple of eight, it usually pads the frame to whole bytes. A typical 12-bit DAC takes a 16-bit frame: four control bits, then 12 data bits.
#include <SPI.h>
const uint8_t CS_PIN = 10;
// Frame layout (example, check your datasheet):
// bits 15..12 = control, bits 11..0 = data
void writeDac12(uint16_t code) {
uint16_t frame = 0x3000 | (code & 0x0FFF); // control nibble 0x3 is a placeholder
SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
SPI.transfer16(frame); // sends the high byte first when MSBFIRST is set
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void setup() {
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
}
void loop() {
writeDac12(0x0800); // mid-scale
delay(100);
}Mask the data with & 0x0FFF so a stray high bit cannot overwrite the control field.
A 12-bit result read back
An ADC may return 12 bits inside a 16-bit reply, with leading zeros or a null bit. Extract the bits with a shift and a mask according to the datasheet:
uint16_t raw = SPI.transfer16(0x0000); // clock out zeros to read the reply
uint16_t result = (raw >> 1) & 0x0FFF; // example: one trailing pad bit, 12 data bitsThe shift amount depends entirely on the device, so read its timing diagram.
How LSBFIRST affects transfer16
With MSBFIRST, transfer16 sends the high byte and then the low byte. With LSBFIRST on AVR, the library still sends the high byte first on some implementations and sends the low byte first on others, depending on the core. Test with a logic analyzer or a loopback wire before relying on it. Sending two separate transfer calls inside one chip-select frame avoids the uncertainty.
Edge cases
- Frames longer than 8 bits and chip select. Keep chip select low for the whole frame. Raising it between bytes ends the transaction on most devices and discards the partial word.
- Partial bytes. If a device needs 10 bits, sending 16 may be fine when the extra bits fall before the data and the chip ignores them. Others count clock pulses and reject a frame of the wrong length. The datasheet decides.
- Dummy bytes on reads. A read of N bytes needs N bytes clocked out, so you send filler such as
0x00. The filler is in the same bit order as real data. - Reversing bits in software. If a board's hardware cannot do LSB first, reverse the byte before sending. A loop over eight bits does this correctly.
uint8_t reverseBits(uint8_t value) {
uint8_t result = 0;
for (uint8_t i = 0; i < 8; i++) {
result = (result << 1) | (value & 1);
value >>= 1;
}
return result;
}Calling SPI.transfer(reverseBits(x)) with MSBFIRST has the same effect on the wire as sending x with LSBFIRST.
Recognizing a bit order fault
The symptoms of a wrong bit order are specific:
- A command that should turn on one feature turns on a different one. Value
0x01acts like0x80. - Readings are repeatable but wrong. A constant input gives a constant output, which is bit-reversed.
- Reading a device ID register returns a value whose bits are the mirror image of the expected ID. For
0x71(01110001) you would see0x8E(10001110) if the bits are inverted, but you would see0x8Eonly by chance. The reversed value is0x8Efor the pattern01110001read backwards:10001110. This is exactly the mirror image, so check for it.
A mirror-image result points at bit order. A random-looking result points more toward a wrong SPI mode.
Exercise
A chip's datasheet says it expects the 8-bit command 0x06 sent LSB first. You use SPISettings(1000000, MSBFIRST, SPI_MODE0) and call SPI.transfer(0x06). Which value does the chip actually receive, and what single change to the code fixes it without changing the settings?
Show answer
Sent MSB first, 0x06 (00000110) goes out as 0 0 0 0 0 1 1 0. The chip, reading LSB first, assembles the bits as 01100000, which is 0x60. Either change the settings to LSBFIRST, or keep MSBFIRST and send the bit-reversed byte reverseBits(0x06), which is 0x60.
Exercise
A 12-bit ADC returns its result in a 16-bit reply with the data in bits 14 to 3 and zeros elsewhere. Write the expression that extracts the 12-bit value from raw.
Show answer
uint16_t result = (raw >> 3) & 0x0FFF; Shifting right by 3 moves bit 3 to bit 0, and the mask keeps 12 bits.