
Talking and listening
On SPI every byte the controller sends is a byte it receives. There is no way to only listen, so to read a peripheral you send it something to make the clock run, and what you send is thrown away.
An SPI transfer is a swap. While the controller shifts a byte out on MOSI, the peripheral shifts a byte out on MISO, and each shifts the other's in. The two shift registers form a ring, and after eight ticks each end holds what the other had.
Motorola's own block guide for the interface says data is transmitted and received simultaneously.
Reading is sending
The controller cannot receive without clocking, and it cannot clock without sending, because the same eight ticks move a byte in each direction. To read a register from a peripheral, the controller sends a byte and keeps only what comes back. The byte it sends for that is called a dummy byte, and any value will do. Zero and 0xFF are the usual choices.
Most peripherals need a real byte first. A BME280, for instance, is sent the register address with its top bit set to 1 for a read. That byte is not a dummy: the peripheral acts on it. The byte that came back while it was being sent is meaningless, because the peripheral has not yet been asked anything. The answer comes back on the next byte, while the controller sends a dummy one. To read n bytes, clock n bytes.
Writing is reading
The same rule applies the other way. When the controller writes a register, the peripheral is sending something back on MISO at the same moment, and the controller receives eight bits it never asked for. Usually they are ignored. A driver that treats them as an answer can report a failure that is not there.
What it costs
A byte read from the wrong place is a common bug. The answer is one byte later than you expect, because the byte that returned while you were asking was for the question before. Code that reads the first byte back gets the previous reply, or a value with nothing in it.
Common mistakes
- Reading the byte that came back during the command. The answer is in the next one.
- Sending a dummy byte the chip takes as a command. Use a value the datasheet allows.
- Expecting to receive without transmitting. The clock runs only while bytes go out.
Edit this page — content/fundamentals/spi/talking-and-listening.mdx
Discuss this article
Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.