Sub topic 10
Reading a datasheet: commands, addresses and registers
SPI defines how bits move on the wires. It says nothing about what the bytes mean. Each peripheral defines its own command format, and the datasheet is the only place that format is written down. This chapter shows how to find that format and turn it into Arduino code.
This chapter assumes you can already:
- Open a transaction with
SPI.beginTransaction, drive chip select, and callSPI.transfer. - Choose an SPI mode and clock rate.
- Work with hexadecimal values and the bitwise operators
&,|,~and<<.
Where to look in a datasheet
Datasheets are long. For SPI work you need four parts:
- The serial interface section. It gives the mode, the maximum clock rate, the bit order and the frame layout.
- The timing diagram. It shows which bytes the controller sends and which bytes the peripheral returns.
- The register map. It lists every register's address, name, access type (read-only, read/write) and reset value.
- The register descriptions. They explain each bit field, including reserved bits.
The register map usually includes an identification register, often called WHO_AM_I, CHIP_ID or DEVICE_ID. It holds a fixed value. Reading it is the best first test of a new wiring setup, because a correct answer proves that the mode, the clock and the chip select all work.
Two common command styles
Most peripherals fall into one of two styles.
| Style | First byte | Typical devices | Watch for |
|---|---|---|---|
| Register style | Register address combined with a read/write flag, sometimes also an auto-increment flag | Accelerometers, gyroscopes, radio transceivers, ADCs | The flag bit position differs between chips |
| Opcode style | An opcode that names an operation, followed by an address and data | Serial flash, EEPROM, FRAM | Some operations need a write-enable command first |
In register style, one address byte selects a register. A common layout uses the top bit as the read flag: 1 means read and 0 means write. Many chips also use a second bit to make the register address increment automatically, so you can read several consecutive registers in one frame. The flag positions are device-specific. Do not copy them from another chip.
In opcode style, a flash chip might define 0x9F as "read JEDEC ID" and 0x03 as "read data starting at a 24-bit address". The datasheet's command table lists every opcode, the number of address bytes, the number of dummy bytes and the direction of each phase.
Anatomy of one frame
A frame is everything between chip select going low and chip select going high. Because SPI is full duplex, every byte you send also clocks one byte back in. The byte that comes back while you send the command is usually meaningless. The useful reply arrives while you send the next byte, which is normally a dummy byte of 0x00.
Some datasheets also require one or more extra dummy bytes between the address and the data. Flash chips use them for high-speed read commands. The timing diagram shows these as blank cycles on MOSI while MISO is already active. Count them.
Worked example: a register-style device
The sketch below talks to a made-up sensor. The register addresses, the flag bits and the ID value are placeholders. Replace them with the values from your own datasheet. The structure stays the same for real parts.
#include <SPI.h>
const uint8_t CS_PIN = 10;
// Command byte layout (placeholder, device-specific):
// bit 7 = read flag, bit 6 = auto-increment, bits 5..0 = register address
const uint8_t READ_FLAG = 0x80;
const uint8_t AUTO_INC = 0x40;
const uint8_t ADDR_MASK = 0x3F;
const uint8_t REG_WHO_AM_I = 0x0F;
const uint8_t REG_CTRL1 = 0x20;
const uint8_t REG_OUT_L = 0x28; // first of six data registers
const uint8_t EXPECTED_ID = 0x33;
const uint8_t CTRL1_ENABLE = 0x01; // bit 0 turns measurement on
const SPISettings deviceSettings(1000000, MSBFIRST, SPI_MODE0);
uint8_t readRegister(uint8_t reg) {
SPI.beginTransaction(deviceSettings);
digitalWrite(CS_PIN, LOW);
SPI.transfer((reg & ADDR_MASK) | READ_FLAG);
uint8_t value = SPI.transfer(0x00);
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
return value;
}
void writeRegister(uint8_t reg, uint8_t value) {
SPI.beginTransaction(deviceSettings);
digitalWrite(CS_PIN, LOW);
SPI.transfer(reg & ADDR_MASK); // read flag stays 0
SPI.transfer(value);
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void readRegisters(uint8_t reg, uint8_t *buf, size_t len) {
SPI.beginTransaction(deviceSettings);
digitalWrite(CS_PIN, LOW);
SPI.transfer((reg & ADDR_MASK) | READ_FLAG | AUTO_INC);
for (size_t i = 0; i < len; i++) {
buf[i] = SPI.transfer(0x00);
}
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void updateRegister(uint8_t reg, uint8_t mask, uint8_t bits) {
uint8_t current = readRegister(reg);
writeRegister(reg, (current & ~mask) | (bits & mask));
}
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
uint8_t id = readRegister(REG_WHO_AM_I);
Serial.print("WHO_AM_I = 0x");
Serial.println(id, HEX);
if (id != EXPECTED_ID) {
Serial.println("Unexpected ID: check wiring, mode and chip select");
while (true) {}
}
updateRegister(REG_CTRL1, CTRL1_ENABLE, CTRL1_ENABLE);
}
void loop() {
uint8_t raw[6];
readRegisters(REG_OUT_L, raw, sizeof(raw));
int16_t x = (int16_t)((uint16_t)raw[1] << 8 | raw[0]); // low byte first
int16_t y = (int16_t)((uint16_t)raw[3] << 8 | raw[2]);
int16_t z = (int16_t)((uint16_t)raw[5] << 8 | raw[4]);
Serial.print(x); Serial.print(' ');
Serial.print(y); Serial.print(' ');
Serial.println(z);
delay(100);
}Several details in this code come directly from the datasheet:
- The address mask.
reg & ADDR_MASKkeeps a wrong address from setting the flag bits by accident. - The auto-increment read. One command byte followed by six clocked bytes reads six consecutive registers in a single frame. This is faster than six separate frames, and it returns values from the same measurement.
- Byte order. The datasheet states whether the low byte or the high byte comes first in memory. Here the low byte is at the lower address, so the code shifts the second byte left.
- Signed values. Sensor outputs are often two's complement, so the combined value is cast to
int16_t.
Worked example: an opcode-style device
Serial flash chips follow the opcode style. The JEDEC ID command (0x9F) is common across many parts. It returns a manufacturer byte and two device bytes.
#include <SPI.h>
const uint8_t CS_PIN = 10;
const SPISettings flashSettings(4000000, MSBFIRST, SPI_MODE0);
void readJedecId(uint8_t id[3]) {
SPI.beginTransaction(flashSettings);
digitalWrite(CS_PIN, LOW);
SPI.transfer(0x9F);
for (uint8_t i = 0; i < 3; i++) {
id[i] = SPI.transfer(0x00);
}
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void readData(uint32_t address, uint8_t *buf, size_t len) {
SPI.beginTransaction(flashSettings);
digitalWrite(CS_PIN, LOW);
SPI.transfer(0x03); // read data opcode
SPI.transfer((address >> 16) & 0xFF); // 24-bit address, most significant byte first
SPI.transfer((address >> 8) & 0xFF);
SPI.transfer(address & 0xFF);
for (size_t i = 0; i < len; i++) {
buf[i] = SPI.transfer(0x00);
}
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
}
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
uint8_t id[3];
readJedecId(id);
Serial.print("JEDEC ID: ");
for (uint8_t i = 0; i < 3; i++) {
Serial.print(id[i], HEX);
Serial.print(' ');
}
Serial.println();
uint8_t first[8];
readData(0, first, sizeof(first));
for (uint8_t i = 0; i < sizeof(first); i++) {
Serial.print(first[i], HEX);
Serial.print(' ');
}
Serial.println();
}
void loop() {}Reads need no preparation, but writes and erases do. Flash chips ignore a program or erase command until you send a separate write-enable opcode in its own frame. After a program or erase, the chip stays busy for a while. You must poll a status register until its busy bit clears before sending the next command.
Common mistakes
- Reading the reply to the command byte. The byte returned while you send the address is not the data. Use the byte returned during the dummy byte.
- Wrong flag polarity. Some chips use 1 for read and others use 1 for write. Check the first row of the command table.
- Forgetting the dummy bytes. A fast-read opcode with one required dummy byte returns shifted data if you skip it. The values look plausible but are off by one position.
- Releasing chip select too early. Splitting one logical command across two frames resets the peripheral's command decoder.
- Misreading multi-byte order. If a 16-bit value looks wildly wrong but changes smoothly, the bytes are probably swapped.
- Trusting the datasheet's example values. Reset values apply only after a reset. A register you have already written may hold something else.
Exercise
A datasheet says a register read is performed by sending the address with bit 7 set, then clocking one more byte. You want to read register 0x0A. What do you send on MOSI, and which received byte holds the register value?
Show answer
Send 0x8A (0x0A | 0x80) as the command byte, then a dummy byte such as 0x00. The register value is the byte received during the dummy byte, which is the second byte of the frame. The byte received during the command byte is ignored.
Exercise
A control register holds the value 0xB5. You must set bit 1 and clear bits 7 to 4, leaving bits 3 to 0 otherwise unchanged. Which mask and bits arguments would you pass to updateRegister, and what is the new register value?
Show answer
Use mask 0xF2 (bits 7 to 4 and bit 1) and bits 0x02 (only bit 1 set). The new value is (0xB5 & ~0xF2) | (0x02 & 0xF2) = 0x05 | 0x02 = 0x07.