Serial Peripheral Interface (SPI)

Contributors: MikeGrusin
Favorited Favorite 88

Receiving Data

Note: You may not recognize the COPI/CIPO labels for SPI pins. SparkFun has joined with other members of OSHWA in a resolution to move away from using "Master" and "Slave" to describe signals between the controller and the peripheral. Check out this page for more on our reasoning behind this change. You can also see OSHWA's resolution here.

You might be thinking to yourself, self, that sounds great for one-way communications, but how do you send data back in the opposite direction? Here's where things get slightly more complicated.

In SPI, only one side generates the clock signal (usually called CLK or SCK for Serial ClocK). The side that generates the clock is called the "controller", and the other side is called the "peripheral". There is always only one controller (which is almost always your microcontroller), but there can be multiple peripherals (more on this in a bit).

When data is sent from the controller to a peripheral, it's sent on a data line called COPI, for "Controller Out / Peripheral In". If the peripheral needs to send a response back to the controller, the controller will continue to generate a prearranged number of clock cycles, and the peripheral will put the data onto a third data line called CIPO, for "Controller In / Peripheral Out".

Basic Signalling

Notice we said "prearranged" in the above description. Because the controller always generates the clock signal, it must know in advance when a peripheral needs to return data and how much data will be returned. This is very different than asynchronous serial, where random amounts of data can be sent in either direction at any time. In practice this isn't a problem, as SPI is generally used to talk to sensors that have a very specific command structure. For example, if you send the command for "read data" to a device, you know that the device will always send you, for example, two bytes in return. (In cases where you might want to return a variable amount of data, you could always return one or two bytes specifying the length of the data and then have the controller retrieve the full amount.)

Note that SPI is "full duplex" (has separate send and receive lines), and, thus, in certain situations, you can transmit and receive data at the same time (for example, requesting a new sensor reading while retrieving the data from the previous one). Your device's datasheet will tell you if this is possible.