Spi Module
Spi Module
Spi Module
There may be other naming conventions such as Serial Data In [SDI] in place of MOSI and Serial Data Out
[SDO] for MISO.
Among these four logic signals, two of them MOSI & MISO can be grouped as data lines and other two SS &
SCLK as control lines.
As we already know, in SPI-bus communication there can be one master with multiple slaves. In single-master
protocol, usually one SPI device acts as the SPI Master and controls the data flow by generating the clock signal
(SCLK) and activating the slave it wants to communicate with slave-select signal (SS), then receives and or
transmits data via the two data lines. A master, usually the host micro controller, always provides clock signal to
all devices on a bus whether it is selected or not.
The usage of these each four pins may depend on the devices. For example, SDI pin may not be present if a
device does not require an input (ADC for example), or SDO pin may not be present if a device does not require
an output (LCD controllers for example). If a microcontroller only needs to talk to 1 SPI Peripheral or one slave,
then the CS pin on that slave may be grounded. With multiple slave devices, an independent SS signal is needed
from the master for each slave device.
How do they communicate:
The communication is initiated by the master all the time. The master first configures the clock, using a
frequency, which is less than or equal to the maximum frequency that the slave device supports. The master then
select the desired slave for communication by pulling the chip select (SS) line of that particular slave-peripheral
to "low" state. If a waiting period is required (such as for analog-to-digital conversion) then the master must wait
for at least that period of time before starting to issue clock cycles.
The slaves on the bus that has not been activated by the master using its slave select signal will disregard the
input clock and MOSI signals from the master, and must not drive MISO. That means the master selects only one
slave at a time.
Most devices/peripherals have tri-state outputs, which goes to high impedance state (disconnected) when the
device is not selected. Devices without this tri-state outputs cannot share SPI bus with other devices, because
such slave's chip-select may not get activated.
A full duplex data transmission can occur during each clock cycle. That means the master sends a bit on the
MOSI line; the slave reads it from that same line and the slave sends a bit on the MISO line; the master reads it
from that same line.
Data transfer is organized by using Shift register with some given word size such as 8- bits (remember, its not
limited to 8-bits), in both master and slave. They are connected in a ring. While master shifts register value out
through MOSI line, the slave shifts data in to its shift register.
Data are usually shifted out with the MSB first, while shifting a new LSB into the same register. After that register
has been shifted out, the master and slave have exchanged their register values. Then each device takes that
value and does the necessary operation with it (for example, writing it to memory). If there are more data to be
exchanged, the shift registers are loaded with new data and the process is repeated. When there are no more
data to be transmitted, the master stops its clock. Normally, it then rejects the slave.
There is a "multiple byte stream mode" available with SPI bus interface. In this mode the master can shift bytes
continuously. In this case, the slave select (SS) is kept low until all stream process gets finished.
SPI devices sometimes use another signal line to send an interrupt signal to a host CPU. Some of the examples
for these type of signals are pen-down interrupts from touch-screen sensors, thermal limit alerts from
temperature sensors, alarms issued by real time clock chips, and headset jack insertions from the sound codec
in a cell phone.
Significance of the clock polarity and phase:
Another pair of parameters called clock polarity (CPOL) and clock phase (CPHA) determine the edges of the
clock signal on which the data are driven and sampled.
That means, in addition to setting the clock frequency, the master must also configure the clock polarity (CPOL)
and phase (CPHA) with respect to the data. Since the clock serves as synchronization of the data
communication, there are four possible modes that can be used in an SPI protocol, based on this CPOL and
CPHA.
SPI Mode
CPOL
CPHA
If the phase of the clock is zero (i.e. CPHA = 0) data is latched at the rising edge of the clock with CPOL = 0, and
at the falling edge of the clock with CPOL = 1.
If CPHA = 1, the polarities are reversed. Data is latched at the falling edge of the clock with CPOL = 0, and at the
rising edge with CPOL = 1.
The micro-controllers allow the polarity and the phase of the clock to be adjusted. A positive polarity results in
latching data at the rising edge of the clock. However data is put on the data line already at the falling edge in
order to stabilize. Most peripherals, which can only be slaves, work with this configuration. If it should become
necessary to use the other polarity, transitions are reversed.
Different types of configurations:
Suppose a master-microcontroller needs to talk to multiple SPI Peripherals. There are 2 ways to set things up:
1. Cascaded slaves or daisy-chained slaves
2. Independent slaves or parallel configuration
Daisy-chained slave configuration:
In cascaded slave configuration, all the clock lines (SCLK) are connected together. And also all the chip select
(CS) pins are connected together. The data flows out the microcontroller, through each peripheral in turn, and
back to the microcontroller. The data output of the preceding slave-device is tied to the data input of the next,
thus forming a wider shift register. So the cascaded slave-devices are evidently looked at as one larger device
and receive therefore the same chip select signal. This means, only a single SS line is required from the master,
rather than a separate SS line for each slave.
But we have to remember that the daisy-chain will not work with devices which support or require multiple bytes
operation.
Independent slave configuration:
This is the typical SPI-bus configuration with one SPI-master and multiple slaves/peripherals. In this independent
or parallel slave configuration,
1. All the clock lines (SCLK) are connected together.
2. All the MISO data lines are connected together.
3. All the MOSI data lines are connected together.
4. But the Chip Select (CS) pin from each peripheral must be connected to a separate Slave Select (SS)
on the master-microcontroller.
pin
Advantages of SPI
1. Full duplex communication
2. Higher throughput than IC protocol
3. Not limited to 8-bit words in the case of bit-transferring
4. Arbitrary choice of message size, contents, and purpose
5. Simple hardware interfacing
6. Typically lower power requirements than IC due to less circuitry.
7. No arbitration or associated failure modes.
8. Slaves use the master's clock, and don't need precision oscillators.
Introduction
Serial Peripheral Interface (SPI) is an interface bus commonly used to send data between
microcontrollers and small peripherals such as shift registers, sensors, and SD cards. It uses
separate clock and data lines, along with a select line to choose the device you wish to talk to.
Suggested Reading
Stuff that would be helpful to know before reading this tutorial:
Binary
Serial Communication
Shift registers
Logic Levels
To work around this problem, asynchronous serial connections add extra start and stop bits to
each byte help the receiver sync up to data as it arrives. Both sides must also agree on the
transmission speed (such as 9600 bits per second) in advance. Slight differences in the
transmission rate arent a problem because the receiver re-syncs at the start of each byte.
(By the way, if you noticed that 11001010 does not equal 0x53 in the above diagram, kudos to
your attention to detail. Serial protocols will often send the least significant bits first, so the
smallest bit is on the far left. The lower nybble is actually 0011 = 0x3, and the upper nybble is
0101 = 0x5.)
Asynchronous serial works just fine, but has a lot of overhead in both the extra start and stop bits
sent with every byte, and the complex hardware required to send and receive data. And as
youve probably noticed in your own projects, if both sides arent set to the same speed, the
received data will be garbage. This is because the receiver is sampling the bits at very specific
times (the arrows in the above diagram). If the receiver is looking at the wrong times, it will see
the wrong bits.
A Synchronous Solution
SPI works in a slightly different manner. Its a synchronous data bus, which means that it uses
separate lines for data and a clock that keeps both sides in perfect sync. The clock is an
oscillating signal that tells the receiver exactly when to sample the bits on the data line. This
could be the rising (low to high) or falling (high to low) edge of the clock signal; the datasheet will
specify which one to use. When the receiver detects that edge, it will immediately look at the data
line to read the next bit (see the arrows in the below diagram). Because the clock is sent along
with the data, specifying the speed isnt important, although devices will have a top speed at
which they can operate (Well discuss choosing the proper clock edge and speed in a bit).
One reason that SPI is so popular is that the receiving hardware can be a simple shift register.
This is a much simpler (and cheaper!) piece of hardware than the full-up UART (Universal
Asynchronous Receiver / Transmitter) that asynchronous serial requires.
Receiving Data
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? Heres 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 master, and the other side is called the slave.
There is always only one master (which is almost always your microcontroller), but there can be
multiple slaves (more on this in a bit).
When data is sent from the master to a slave, its sent on a data line called MOSI, for Master Out
/ Slave In. If the slave needs to send a response back to the master, the master will continue to
generate a prearranged number of clock cycles, and the slave will put the data onto a third data
line called MISO, for Master In / Slave Out.
Notice we said prearranged in the above description. Because the master always generates the
clock signal, it must know in advance when a slave 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 isnt 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 master
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 devices datasheet will tell
you if this is possible.
The SS line is normally held high, which disconnects the slave from the SPI bus. (This type of
logic is known as active low, and youll often see used it for enable and reset lines.) Just before
data is sent to the slave, the line is brought low, which activates the slave. When youre done
using the slave, the line is made high again. In a shift register, this corresponds to the latch
input, which transfers the received data to the output lines.
Multiple slaves
There are two ways of connecting multiple slaves to an SPI bus:
1. In general, each slave will need a separate SS line. To talk to a particular slave, youll
make that slaves SS line low and keep the rest of them high (you dont want two slaves
activated at the same time, or they may both try to talk on the same MISO line resulting in
garbled data). Lots of slaves will require lots of SS lines; if youre running low on outputs,
there are binary decoder chips that can multiply your SS outputs.
1. On the other hand, some parts prefer to be daisy-chained together, with the MISO
(output) of one going to the MOSI (input) of the next. In this case, a single SS line goes
to all the slaves. Once all the data is sent, the SS line is raised, which causes all the
chips to be activated simultaneously. This is often used for daisy-chained shift registers
and addressable LED drivers.
Note that, for this layout, data overflows from one slave to the next, so to send data to
any one slave, youll need to transmit enough data to reach all of them. Also, keep in mind that
the first piece of data you transmit will end up in thelast slave.
This type of layout is typically used in output-only situations, such as driving LEDs where you
dont need to receive any data back. In these cases you can leave the masters MISO line
disconnected. However, if data does need to be returned to the master, you can do this by closing
the daisy-chain loop (blue wire in the above diagram). Note that if you do this, the return data
from slave 1 will need to pass through all the slaves before getting back to the master, so be sure
to send enough receive commands to get the data you need.
you (yes, you!) can write your own routines to manipulate the I/O lines in the proper sequence to
transfer data. (A good example is on the Wikipedia SPI page.)
If youre using an Arduino, there are two ways you can communicate with SPI devices:
1. You can use the shiftIn() and shiftOut() commands. These are software-based
commands that will work on any group of pins, but will be somewhat slow.
2. Or you can use the SPI Library, which takes advantage of the SPI hardware built into the
microcontroller. This is vastly faster than the above commands, but it will only work on
certain pins.
You will need to select some options when setting up your interface. These options must match
those of the device youre talking to; check the devices datasheet to see what it requires.
The interface can send data with the most-significant bit (MSB) first, or least-significant
bit (LSB) first. In the Arduino SPI library, this is controlled by the setBitOrder() function.
The slave will read the data on either the rising edge or the falling edge of the clock
pulse. Additionally, the clock can be considered idle when it is high or low. In the
Arduino SPI library, both of these options are controlled by the setDataMode() function.
SPI can operate at extremely high speeds (millions of bytes per second), which may be
too fast for some devices. To accommodate such devices, you can adjust the data rate. In
the Arduino SPI library, the speed is set by the setClockDivider() function, which divides
the master clock (16MHz on most Arduinos) down to a frequency between 8MHz (/2) and
125kHz (/128).
If youre using the SPI Library, you must use the provided SCK, MOSI and MISO pins, as
the hardware is hardwired to those pins. There is also a dedicated SS pin that you can
use (which must, at least, be set to an output in order for the SPI hardware to function),
but note that you can use any other available output pin(s) for SS to your slave device(s)
as well.
On older Arduinos, youll need to control the SS pin(s) yourself, making one of them low
before your data transfer and high afterward. Newer Arduinos such as the Due can
control each SS pin automatically as part of the data transfer; see the Due SPI
documentation page for more information.