Hubbry Logo
Serial Peripheral InterfaceSerial Peripheral InterfaceMain
Open search
Serial Peripheral Interface
Community hub
Serial Peripheral Interface
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Serial Peripheral Interface
Serial Peripheral Interface
from Wikipedia
Serial Peripheral Interface (SPI)
Type Serial communication bus
Production history
Designer Motorola
Designed Around early 1980s[note 1]
Manufacturer Various
Daisy chain Depends on devices
Connector Unspecified
Electrical
Max. voltage Unspecified
Max. current Unspecified
Data
Width 1 bit (bidirectional)
Max. devices Multidrop limited by slave selects. Daisy chaining unlimited.
Protocol Full-duplex serial
Pinout
MOSI Master Out Slave In
MISO Master In Slave Out
SCLK Serial Clock
SS Slave Select (one or more)
(pins may have alternative names)

Serial Peripheral Interface (SPI) is a de facto standard (with many variants) for synchronous serial communication, used primarily in embedded systems for short-distance wired communication between integrated circuits.

SPI follows a master–slave architecture,[1] where a master device orchestrates communication with one or more slave devices by driving the clock and chip select signals. Some devices support changing master and slave roles on the fly.

Motorola's original specification (from the early 1980s) uses four logic signals, aka lines or wires, to support full duplex communication. It is sometimes called a four-wire serial bus to contrast with three-wire variants which are half duplex, and with the two-wire I²C and 1-Wire serial buses.

Typical applications include interfacing microcontrollers with peripheral chips for Secure Digital cards, liquid crystal displays, analog-to-digital and digital-to-analog converters, flash and EEPROM memory, and various communication chips.

Although SPI is a synchronous serial interface,[2] it is different from Synchronous Serial Interface (SSI). SSI employs differential signaling and provides only a single simplex communication channel.

Operation

[edit]
Single master to single slave: basic SPI wiring

Commonly, SPI has four logic signals. Variations may use different names or have different signals.

Abbr. Name Description
SS
Slave Select
Active-low chip select signal from master to
enable communication with a specific slave device
SCLK
Serial Clock
Clock signal from master
MOSI
Master Out Slave In
Serial data output from master
MISO
Master In Slave Out
Serial data output from slave

MOSI on a master outputs to MOSI on a slave. MISO on a slave outputs to MISO on a master.

Each device internally uses a shift register for serial communication, which together forms an inter-chip circular buffer.

Slave devices should use tri-state outputs so their MISO signal becomes high impedance (electrically disconnected) when the device is not selected. Slaves without tri-state outputs cannot share a MISO line with other slaves without using an external tri-state buffer.

Data transmission

[edit]
A typical hardware setup using two shift registers to form an inter-chip circular buffer

To begin communication, the SPI master first selects a slave device by pulling its SS low. (The bar above SS indicates it is an active low signal, so a low voltage means "selected", while a high voltage means "not selected")

If a waiting period is required, such as for an analog-to-digital conversion, the master must wait for at least that period of time before issuing clock cycles.[note 2]

During each SPI clock cycle, full-duplex transmission of a single bit occurs. The master sends a bit on the MOSI line while the slave sends a bit on the MISO line, and then each reads their corresponding incoming bit. This sequence is maintained even when only one-directional data transfer is intended.

Transmission using a single slave involves one shift register in the master and one shift register in the slave, both of some given word size (e.g. 8 bits). The transmissions often consist of eight-bit words, but other word-sizes are also common, for example, sixteen-bit words for touch-screen controllers or audio codecs, such as the TSC2101 by Texas Instruments, or twelve-bit words for many digital-to-analog or analog-to-digital converters.

Data is usually shifted out with the most-significant bit (MSB) first but the original specification has a LSBFE ("LSB-First Enable") to control whether data is transferred least (LSB) or most significant bit (MSB) first. On the clock edge, both master and slave shift out a bit to its counterpart. On the next clock edge, each receiver samples the transmitted bit and stores it in the shift register as the new least-significant bit. After all bits have been shifted out and in, the master and slave have exchanged register values. If more data needs to be exchanged, the shift registers are reloaded and the process repeats. Transmission may continue for any number of clock cycles. When complete, the master stops toggling the clock signal, and typically deselects the slave.

If a single slave device is used, its SS pin may be fixed to logic low if the slave permits it. With multiple slave devices, a multidrop configuration requires an independent SS signal from the master for each slave device, while a daisy-chain configuration only requires one SS signal.

Every slave on the bus that has not been selected should disregard the input clock and MOSI signals. And to prevent contention on MISO, non-selected slaves must use tristate output. Slaves that are not already tristate will need external tristate buffers to ensure this.[3]

Clock polarity and phase

[edit]

In addition to setting the clock frequency, the master must also configure the clock polarity and phase with respect to the data. Motorola[4][5] named these two options as CPOL and CPHA (for clock polarity and clock phase) respectively, a convention most vendors have also adopted.

SPI timing diagram for both clock polarities and phases. Data bits output on blue lines if CPHA=0, or on red lines if CPHA=1, and sample on opposite-colored lines. Numbers identify data bits. Z indicates high impedance.

The SPI timing diagram shown is further described below:

  • CPOL represents the polarity of the clock. Polarities can be converted with a simple inverter.
    • SCLKCPOL=0 is a clock which idles at the logical low voltage.
    • SCLKCPOL=1 is a clock which idles at the logical high voltage.
  • CPHA represents the phase of each data bit's transmission cycle relative to SCLK.
    • For CPHA=0:
      • The first data bit is output immediately when SS activates.
      • Subsequent bits are output when SCLK transitions to its idle voltage level.
      • Sampling occurs when SCLK transitions from its idle voltage level.
    • For CPHA=1:
      • The first data bit is output on SCLK's first clock edge after SS activates.
      • Subsequent bits are output when SCLK transitions from its idle voltage level.
      • Sampling occurs when SCLK transitions to its idle voltage level.
    • Conversion between these two phases is non-trivial.
    • MOSI and MISO signals are usually stable (at their reception points) for the half cycle until the next bit's transmission cycle starts, so SPI master and slave devices may sample data at different points in that half cycle, for flexibility, despite the original specification.

Mode numbers

[edit]

The combinations of polarity and phases are referred to by these "SPI mode" numbers with CPOL as the high order bit and CPHA as the low order bit:

SPI mode Clock polarity
(CPOL)
Clock phase
(CPHA)
Data is shifted out on Data is sampled on
0 0 0 falling SCLK, and when SS activates rising SCLK
1 0 1 rising SCLK falling SCLK
2 1 0 rising SCLK, and when SS activates falling SCLK
3 1 1 falling SCLK rising SCLK

Notes:

  • Another commonly used notation represents the mode as a (CPOL, CPHA) tuple; e.g., the value '(0, 1)' would indicate CPOL=0 and CPHA=1.
  • In Full Duplex operation, the master device could transmit and receive with different modes. For instance, it could transmit in Mode 0 and be receiving in Mode 1 at the same time.
  • Different vendors may use different naming schemes, like CKE for clock edge or NCPHA for the inversion of CPHA.

Valid communications

[edit]

Some slave devices are designed to ignore any SPI communications in which the number of clock pulses is greater than specified. Others do not care, ignoring extra inputs and continuing to shift the same output bit. It is common for different devices to use SPI communications with different lengths, as, for example, when SPI is used to access an IC's scan chain by issuing a command word of one size (perhaps 32 bits) and then getting a response of a different size (perhaps 153 bits, one for each pin in that scan chain).

Interrupts

[edit]

Interrupts are outside the scope of SPI; their usage is neither forbidden nor specified, and so may be implemented optionally.

From master to slave

[edit]

Microcontrollers configured as slave devices may have hardware support for generating interrupt signals to themselves when data words are received or overflow occurs in a receive FIFO buffer,[6] and may also set up an interrupt routine when their slave select input line is pulled low or high.

From slave to master

[edit]

SPI slaves sometimes use an out-of-band signal (another wire) to send an interrupt signal to a master. Examples include pen-down interrupts from touchscreen sensors, thermal limit alerts from temperature sensors, alarms issued by real-time clock chips, SDIO[note 3] and audio jack insertions for an audio codec. Interrupts to master may also be faked by using polling (similarly to USB 1.1 and 2.0).

Software design

[edit]

SPI lends itself to a "bus driver" software design. Software for attached devices is written to call a "bus driver" that handles the actual low-level SPI hardware. This permits the driver code for attached devices to port easily to other hardware or a bit-banging software implementation.

Bit-banging the protocol

[edit]

The pseudocode below outlines a software implementation ("bit-banging") of SPI's protocol as a master with simultaneous output and input. This pseudocode is for CPHA=0 and CPOL=0, thus SCLK is pulled low before SS is activated and bits are inputted on SCLK's rising edge while bits are outputted on SCLK's falling edge.

  • Initialize SCLK as low and SS as high
  • Pull SS low to select the slave
  • Loop for however many number of bytes to transfer:[note 4]
    • Initializebyte_outwith the next output byte to transmit
    • Loop 8 times:
      • Left-Shift[note 5] the next output bit frombyte_outto MOSI
      • NOP for the slave's setup time
      • Pull SCLK high
      • Left-Shift the next input bit from MISO intobyte_in
      • NOP for the slave's hold time
      • Pull SCLK low
    • byte_innow contains that recently-received byte and can be used as desired
  • Pull SS high to unselect the slave

Bit-banging a slave's protocol is similar but different from above. An implementation might involve busy waiting for SS to fall or triggering an interrupt routine when SS falls, and then shifting in and out bits when the received SCLK changes appropriately for however long the transfer size is.

Bus topologies

[edit]

Though the previous operation section focused on a basic interface with a single slave, SPI can instead communicate with multiple slaves using multidrop, daisy chain, or expander configurations.

Multidrop configuration

[edit]
Multidrop SPI bus

In the multidrop bus configuration, each slave has its own SS, and the master selects only one at a time. MISO, SCLK, and MOSI are each shared by all devices. This is the way SPI is normally used.

Since the MISO pins of the slaves are connected together, they are required to be tri-state pins (high, low or high-impedance), where the high-impedance output must be applied when the slave is not selected. Slave devices not supporting tri-state may be used in multidrop configuration by adding a tri-state buffer chip controlled by its SS signal.[3] (Since only a single signal line needs to be tristated per slave, one typical standard logic chip that contains four tristate buffers with independent gate inputs can be used to interface up to four slave devices to an SPI bus)

Caveat: All SS signals should start high (to indicate no slaves are selected) before sending initialization messages to any slave, so other uninitialized slaves ignore messages not addressed to them. This is a concern if the master uses general-purpose input/output (GPIO) pins (which may default to an undefined state) for SS and if the master uses separate software libraries to initialize each device. One solution is to configure all GPIOs used for SS to output a high voltage for all slaves before running initialization code from any of those software libraries. Another solution is to add a pull-up resistor on each SS, to ensure that all SS signals are initially high.[3]

Daisy chain configuration

[edit]
Daisy-chained SPI

Some products that implement SPI may be connected in a daisy chain configuration, where the first slave's output is connected to the second slave's input, and so on with subsequent slaves, until the final slave, whose output is connected back to the master's input. This effectively merges the individual communication shift registers of each slave to form a single larger combined shift register that shifts data through the chain. This configuration only requires a single SS line from the master, rather than a separate SS line for each slave.[7]

In addition to using SPI-specific slaves, daisy-chained SPI can include discrete shift registers for more pins of inputs (e.g. using the parallel-in serial-out 74xx165)[8] or outputs (e.g. using the serial-in parallel-out 74xx595)[9] chained indefinitely. Other applications that can potentially interoperate with daisy-chained SPI include SGPIO, JTAG,[10] and I2C.

Expander configurations

[edit]

Expander configurations use SPI-controlled addressing units (e.g. binary decoders, demultiplexers, or shift registers) to add chip selects.

For example, one SS can be used for transmitting to a SPI-controlled demultiplexer an index number controlling its select signals, while another SS is routed through that demultiplexer according to that index to select the desired slave.[11]

Pros and cons

[edit]

Advantages

[edit]
  • Full duplex communication in the default version of this protocol
  • Push-pull drivers (as opposed to open drain) provide relatively good signal integrity and high speed
  • Higher throughput than I²C or SMBus
    • SPI's protocol has no maximum clock speed, however:
      • Individual devices specify acceptable clock frequencies
      • Wiring and electronics limit frequency
  • Complete protocol flexibility for the bits transferred
    • Not limited to 8-bit symbols
    • Arbitrary choice of message size, content, and purpose
  • Simple hardware and interfacing
    • Hardware implementation for slaves only requires a selectable shift register
      • Slaves use the master's clock and hence do not need precision oscillators
      • Slaves do not need a unique address – unlike I²C or GPIB or SCSI
      • Masters only additionally require generation of clock and SS signals
      • Results in simple bit-banged software implementation
    • Uses only four pins on IC packages, and wires in board layouts or connectors, much fewer than parallel interfaces
      • At most one unique signal per device (SS); all others are shared
        • The daisy-chain configuration does not need more than one shared SS
    • Typically lower power requirements than I²C or SMBus due to less circuitry (including pull up resistors)
    • Single master means no bus arbitration (and associated failure modes) - unlike CAN-bus
    • Transceivers are not needed - unlike CAN-bus
    • Signals are unidirectional, allowing for easy galvanic isolation

Disadvantages

[edit]
  • Requires more pins on IC packages than I²C, even in three-wire variants
  • Only handles short distances compared to RS-232, RS-485, or CAN-bus (though distance can be extended with the use of transceivers like RS-422)
  • Extensibility severely reduced when multiple slaves using different SPI Modes are required
    • Access is slowed down when master frequently needs to reinitialize in different modes
  • No formal standard
    • So validating conformance is not possible
    • Many existing variations complicate support
  • No built-in protocol support for some conveniences:
    • No hardware flow control by the slave (but the master can delay the next clock edge to slow the transfer rate)
    • No hardware slave acknowledgment (the master could be transmitting to nowhere and not know it)
    • No error-checking protocol
    • No hot swapping (dynamically adding nodes)
    • Interrupts are outside the scope of SPI (see § Interrupts)

Applications

[edit]
SPI Memory by Atmel
Fairchild EEPROM using Microwire
Microchip 32-Mbit SQI Flash Memory

SPI is used to talk to a variety of peripherals, such as

Board real estate and wiring savings compared to a parallel bus are significant, and have earned SPI a solid role in embedded systems. That is true for most system-on-a-chip processors, both with higher-end 32-bit processors such as those using ARM, MIPS, or PowerPC and with lower-end microcontrollers such as the AVR, PIC, and MSP430. These chips usually include SPI controllers capable of running in either master or slave mode. In-system programmable AVR controllers (including blank ones) can be programmed using SPI.[12]

Chip or FPGA based designs sometimes use SPI to communicate between internal components; on-chip real estate can be as costly as its on-board cousin. And for high-performance systems, FPGAs sometimes use SPI to interface as a slave to a host, as a master to sensors, or for flash memory used to bootstrap if they are SRAM-based.

The full-duplex capability makes SPI very simple and efficient for single master/single slave applications. Some devices use the full-duplex mode to implement an efficient, swift data stream for applications such as digital audio, digital signal processing, or telecommunications channels, but most off-the-shelf chips stick to half-duplex request/response protocols.

Variations

[edit]

SPI implementations have a wide variety of protocol variations. Some devices are transmit-only; others are receive-only. Slave selects are sometimes active-high rather than active-low. Some devices send the least-significant bit first. Signal levels depend entirely on the chips involved. And while the baseline SPI protocol has no command codes, every device may define its own protocol of command codes. Some variations are minor or informal, while others have an official defining document and may be considered to be separate but related protocols.

Original definition

[edit]

Motorola in 1983 listed[13] three 6805 8-bit microcomputers that have an integrated "Serial Peripheral Interface", whose functionality is described in a 1984 manual.[14]

AN991

[edit]

Motorola's 1987 Application Node AN991 "Using the Serial Peripheral Interface to Communicate Between Multiple Microcomputers"[15] (now under NXP, last revised 2002[5]) informally serves as the "official" defining document for SPI.

Timing variations

[edit]

Some devices have timing variations from Motorola's CPOL/CPHA modes. Sending data from slave to master may use the opposite clock edge as master to slave. Devices often require extra clock idle time before the first clock or after the last one, or between a command and its response.

Some devices have two clocks, one to read data, and another to transmit it into the device. Many of the read clocks run from the slave select line.

Transmission size

[edit]

Different transmission word sizes are common. Many SPI chips only support messages that are multiples of 8 bits. Such chips can not interoperate with the JTAG or SGPIO protocols, or any other protocol that requires messages that are not multiples of 8 bits.

No slave select

[edit]

Some devices do not use slave select, and instead manage protocol state machine entry/exit using other methods.

Connectors

[edit]

Anyone needing an external connector for SPI defines their own or uses another standard connection such as: UEXT, Pmod, various JTAG connectors, Secure Digital card socket, etc.

Flow control

[edit]

Some devices require an additional flow control signal from slave to master, indicating when data is ready. This leads to a 5-wire protocol instead of the usual 4. Such a ready or enable signal is often active-low, and needs to be enabled at key points such as after commands or between words. Without such a signal, data transfer rates may need to be slowed down significantly, or protocols may need to have dummy bytes inserted, to accommodate the worst case for the slave response time. Examples include initiating an ADC conversion, addressing the right page of flash memory, and processing enough of a command that device firmware can load the first word of the response. (Many SPI masters do not support that signal directly, and instead rely on fixed delays.)

SafeSPI

[edit]

SafeSPI[16] is an industry standard for SPI in automotive applications. Its main focus is the transmission of sensor data between different devices.

High reliability modifications

[edit]

In electrically noisy environments, since SPI has few signals, it can be economical to reduce the effects of common mode noise by adapting SPI to use low-voltage differential signaling.[17] Another advantage is that the controlled devices can be designed to loop-back to test signal integrity.[18]

Intelligent SPI controllers

[edit]

A Queued Serial Peripheral Interface (QSPI; different to but has same abbreviation as Quad SPI described in § Quad SPI) is a type of SPI controller that uses a data queue to transfer data across an SPI bus.[19] It has a wrap-around mode allowing continuous transfers to and from the queue with only intermittent attention from the CPU. Consequently, the peripherals appear to the CPU as memory-mapped parallel devices. This feature is useful in applications such as control of an A/D converter. Other programmable features in Queued SPI are chip selects and transfer length/delay.

SPI controllers from different vendors support different feature sets; such direct memory access (DMA) queues are not uncommon, although they may be associated with separate DMA engines rather than the SPI controller itself, such as used by Multichannel Buffered Serial Port (MCBSP).[note 6] Most SPI master controllers integrate support for up to four slave selects,[note 7] although some require slave selects to be managed separately through GPIO lines.

Note that Queued SPI is different from Quad SPI, and some processors even confusingly allow a single "QSPI" interface to operate in either quad or queued mode![20]

Microwire

[edit]

Microwire,[21] often spelled μWire, is essentially a predecessor of SPI and a trademark of National Semiconductor. It's a strict subset of SPI: half-duplex, and using SPI mode 0. Microwire chips tend to need slower clock rates than newer SPI versions; perhaps 2 MHz vs. 20 MHz. Some Microwire chips also support a three-wire mode.

Microwire/Plus

[edit]

Microwire/Plus[22] is an enhancement of Microwire and features full-duplex communication and support for SPI modes 0 and 1. There was no specified improvement in serial clock speed.

Three-wire

[edit]

Three-wire variants of SPI restricted to a half-duplex mode use a single bidirectional data line called SISO (slave out/slave in) or MOMI (master out/master in) instead of SPI's two unidirectional lines (MOSI and MISO). Three-wire tends to be used for lower-performance parts, such as small EEPROMs used only during system startup, certain sensors, and Microwire. Few SPI controllers support this mode, although it can be easily bit-banged in software.

Dual SPI

[edit]

For instances where the full-duplex nature of SPI is not used, an extension uses both data pins in a half-duplex configuration to send two bits per clock cycle. Typically a command byte is sent requesting a response in dual mode, after which the MOSI line becomes SIO0 (serial I/O 0) and carries even bits, while the MISO line becomes SIO1 and carries odd bits. Data is still transmitted most-significant bit first, but SIO1 carries bits 7, 5, 3 and 1 of each byte, while SIO0 carries bits 6, 4, 2 and 0.

This is particularly popular among SPI ROMs, which have to send a large amount of data, and comes in two variants:[23][24]

  • Dual read sends the command and address from the master in single mode, and returns the data in dual mode.
  • Dual I/O sends the command in single mode, then sends the address and return data in dual mode.

Quad SPI

[edit]

Quad SPI (QSPI; different to but has same abbreviation as Queued-SPI described in § Intelligent SPI controllers) goes beyond dual SPI, adding two more I/O lines (SIO2 and SIO3) and sends 4 data bits per clock cycle. Again, it is requested by special commands, which enable quad mode after the command itself is sent in single mode.[23][24]

SQI Type 1
Commands sent on single line but addresses and data sent on four lines
SQI Type 2
Commands and addresses sent on a single line but data sent/received on four lines

QPI/SQI

[edit]

Further extending quad SPI, some devices support a "quad everything" mode where all communication takes place over 4 data lines, including commands.[25] This is variously called "QPI"[24] (not to be confused with Intel QuickPath Interconnect) or "serial quad I/O" (SQI)[26]

This requires programming a configuration bit in the device and requires care after reset to establish communication.

Double data rate

[edit]

In addition to using multiple lines for I/O, some devices increase the transfer rate by using double data rate transmission.[27][28]

JTAG

[edit]

Although there are some similarities between SPI and the JTAG (IEEE 1149.1-2013) protocol, they are not interchangeable. JTAG is specifically intended to provide reliable test access to the I/O pins from an off-board controller with less precise signal delay and skew parameters, while SPI has many varied applications. While not strictly a level sensitive interface, the JTAG protocol supports the recovery of both setup and hold violations between JTAG devices by reducing the clock rate or changing the clock's duty cycles. Consequently, the JTAG interface is not intended to support extremely high data rates.[29]

SGPIO

[edit]

SGPIO is essentially another (incompatible) application stack for SPI designed for particular backplane management activities.[citation needed] SGPIO uses 3-bit messages.

Intel's Enhanced Serial Peripheral Interface

[edit]

Intel has developed a successor to its Low Pin Count (LPC) bus that it calls the Enhanced Serial Peripheral Interface (eSPI) bus. Intel aims to reduce the number of pins required on motherboards and increase throughput compared to LPC, reduce the working voltage to 1.8 volts to facilitate smaller chip manufacturing processes, allow eSPI peripherals to share SPI flash devices with the host (the LPC bus did not allow firmware hubs to be used by LPC peripherals), tunnel previous out-of-band pins through eSPI, and allow system designers to trade off cost and performance.[30][31]

An eSPI bus can either be shared with SPI devices to save pins or be separate from an SPI bus to allow more performance, especially when eSPI devices need to use SPI flash devices.[30]

This standard defines an Alert# signal that is used by an eSPI slave to request service from the master. In a performance-oriented design or a design with only one eSPI slave, each eSPI slave will have its Alert# pin connected to an Alert# pin on the eSPI master that is dedicated to each slave, allowing the eSPI master to grant low-latency service, because the eSPI master will know which eSPI slave needs service and will not need to poll all of the slaves to determine which device needs service. In a budget design with more than one eSPI slave, all of the Alert# pins of the slaves are connected to one Alert# pin on the eSPI master in a wired-OR connection, which requires the master to poll all the slaves to determine which ones need service when the Alert# signal is pulled low by one or more peripherals that need service. Only after all of the devices are serviced will the Alert# signal be pulled high due to none of the eSPI slaves needing service and therefore pulling the Alert# signal low.[30]

This standard allows designers to use 1-bit, 2-bit, or 4-bit communications at speeds from 20 to 66 MHz to further allow designers to trade off performance and cost.[30]

Communications that were out-of-band of LPC like general-purpose input/output (GPIO) and System Management Bus (SMBus) should be tunneled through eSPI via virtual wire cycles and out-of-band message cycles respectively in order to remove those pins from motherboard designs using eSPI.[30]

This standard supports standard memory cycles with lengths of 1 byte to 4 kilobytes of data, short memory cycles with lengths of 1, 2, or 4 bytes that have much less overhead compared to standard memory cycles, and I/O cycles with lengths of 1, 2, or 4 bytes of data which are low overhead as well. This significantly reduces overhead compared to the LPC bus, where all cycles except for the 128-byte firmware hub read cycle spends more than one-half of all of the bus's throughput and time in overhead. The standard memory cycle allows a length of anywhere from 1 byte to 4 kilobytes in order to allow its larger overhead to be amortised over a large transaction. eSPI slaves are allowed to initiate bus master versions of all of the memory cycles. Bus master I/O cycles, which were introduced by the LPC bus specification, and ISA-style DMA including the 32-bit variant introduced by the LPC bus specification, are not present in eSPI. Therefore, bus master memory cycles are the only allowed DMA in this standard.[30]

eSPI slaves are allowed to use the eSPI master as a proxy to perform flash operations on a standard SPI flash memory slave on behalf of the requesting eSPI slave.[30]

64-bit memory addressing is also added, but is only permitted when there is no equivalent 32-bit address.[30]

The Intel Z170 chipset can be configured to implement either this bus or a variant of the LPC bus that is missing its ISA-style DMA capability and is underclocked to 24 MHz instead of the standard 33 MHz.[32]

The eSPI bus is also adopted by AMD Ryzen chipsets.

Development tools

[edit]

Single-board computers

[edit]

Single-board computers may provide pin access to SPI hardware units. For instance, the Raspberry Pi's J8 header exposes at least two SPI units that can be used via Linux drivers or python.

USB to SPI adapters

[edit]

There are a number of USB adapters that allow a desktop PC or smartphone with USB to communicate with SPI chips (e.g. CH341A/B[33] based or FT221xs[34]). They are used for embedded systems, chips (FPGA, ASIC, and SoC) and peripheral testing, programming and debugging. Many of them also provide scripting or programming capabilities (e.g. Visual Basic, C/C++, VHDL) and can be used with open source programs like flashrom, IMSProg, SNANDer or avrdude for flash, EEPROM, bootloader and BIOS programming.

The key SPI parameters are: the maximum supported frequency for the serial interface, command-to-command latency, and the maximum length for SPI commands. It is possible to find SPI adapters on the market today that support up to 100 MHz serial interfaces, with virtually unlimited access length.

SPI protocol being a de facto standard, some SPI host adapters also have the ability of supporting other protocols beyond the traditional 4-wire SPI (for example, support of quad-SPI protocol or other custom serial protocol that derive from SPI[35]).

Protocol analyzers

[edit]

Logic analyzers are tools which collect, timestamp, analyze, decode, store, and view the high-speed waveforms, to help debug and develop. Most logic analyzers have the capability to decode SPI bus signals into high-level protocol data with human-readable labels.

Oscilloscopes

[edit]

SPI waveforms can be seen on analog channels (and/or via digital channels in mixed-signal oscilloscopes).[36] Most oscilloscope vendors offer optional support for SPI protocol analysis (both 2-, 3-, and 4-wire SPI) with triggering.

Alternative terminology

[edit]

Various alternative abbreviations for the four common SPI signals are used. (This section omits overbars indicating active-low.)

  • Serial clock
    • SCK, SCLK, CLK, SCL
  • Master Out Slave In (MOSI)
    • SIMO, MTSR, SPID - correspond to MOSI on both master and slave devices, connects to each other
    • SDI, DI, DIN, SI, SDA - on slave devices; various abbreviations for serial data in; connects to MOSI on master
    • SDO, DO, DOUT, SO - on master devices; various abbreviations for serial data out; connects to MOSI on slave
    • COPI, PICO for peripheral and controller,[37][38] or COTI for controller and target[39]
  • Master In Slave Out (MISO)
    • SOMI, MRST, SPIQ - correspond to MISO on both master and slave devices, connects to each other
    • SDO, DO, DOUT, SO - on slave devices; connects to MISO on master
    • SDI, DI, DIN, SI - on master devices; connects to MISO on slave
    • CIPO, POCI,[37][38] or CITO[39]
  • Slave Select (SS)
    • Chip select (CS)
    • CE (chip enable)
    • Historical: SSEL, NSS, /SS, SS#

Microchip uses host and client though keeps the abbreviation MOSI and MISO.[40]

See also

[edit]

Notes

[edit]

References

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
The Serial Peripheral Interface (SPI) is a protocol designed for full-duplex, high-speed data exchange between a master device and one or more slave peripherals over short distances, typically within a single . Developed by (now ) in the early 1980s, SPI has become a widely adopted in embedded systems for interfacing microcontrollers with sensors, devices, displays, and other peripherals. In SPI, communication operates in a master-slave architecture where the master device generates the serial clock signal (SCLK) to synchronize data transfer, enabling simultaneous bidirectional data flow without a formal protocol overhead. The interface uses four primary signals: SCLK for clocking, MOSI (Master Out Slave In) for data from master to slave, MISO (Master In Slave Out) for data from slave to master, and SS/CS (Slave Select/Chip Select) to designate the active slave among multiple devices. Data is transferred in frames of programmable length (commonly 8 or 16 bits), with the master controlling the clock polarity (CPOL) and phase (CPHA) to support four operational modes for compatibility with diverse devices. SPI's , lack of addressing scheme (relying instead on dedicated select lines), and support for transfer rates up to tens of megahertz make it ideal for applications requiring low latency and high throughput, such as in , industrial controls, and consumer devices. Unlike protocols like , SPI does not require pull-up resistors or multi-master , reducing hardware complexity while enabling daisy-chaining of slaves in some configurations. Its open specification has led to widespread implementation across vendors, ensuring without licensing fees.

Fundamentals

History and Origins

The Serial Peripheral Interface (SPI) was developed by in the mid-1980s as a straightforward protocol intended for short-distance data exchange between integrated circuits on the same circuit board. This interface emerged to meet the growing demand for efficient, full-duplex serial links in early embedded systems, where simplicity and speed were prioritized over long-range capabilities. Unlike more complex protocols, SPI was engineered for minimal overhead, using a master-slave architecture to synchronize data transfer via a dedicated clock line. A pivotal document in SPI's formalization was Motorola's Application Note AN991, originally published in 1987, which provided the first detailed description of the protocol. Titled "Using the Serial Peripheral Interface to Communicate Between Multiple Microcomputers," it outlined the original four-wire configuration: Serial Clock (SCK) for synchronization, Master Out Slave In (MOSI) for data from master to slave, Master In Slave Out () for data from slave to master, and Slave Select () to designate active devices. The note demonstrated SPI's in hardware on the MC68HC05C4 and in software on the MC68705R3, highlighting its versatility for inter-microcomputer communication without requiring additional protocol layers. SPI saw initial adoption within Motorola's product lineup, notably in the 68HC11 family of 8-bit microcontrollers introduced in 1984, where it served as a built-in peripheral for with sensors, memory, and other ICs. By the late 1980s, the protocol expanded to other vendors, fostering broader interoperability. Although never ratified as an official standard by bodies like IEEE or ISO, SPI evolved into a industry norm by the 1990s, driven by its integration into countless embedded applications and the absence of licensing restrictions. By 1990, it had achieved widespread use in microcomputer-based systems for tasks requiring reliable, high-speed local data transfer.

Basic Principles

The Serial Peripheral Interface (SPI) is a protocol designed for short-distance data exchange between a and peripheral devices, such as sensors or chips. It operates in full-duplex mode, enabling simultaneous transmission and reception of data over dedicated lines. At its core, SPI employs four primary signal lines: the Serial Clock (SCK), which is generated by the master device to synchronize data transfer; Master Out Slave In (MOSI), for data output from the master to the slave; Master In Slave Out (), for data input from the slave to the master; and Slave Select (SS) or (CS), which activates a specific slave device. These lines facilitate a straightforward, hardware-based interface without requiring complex protocol overhead. SPI follows a master-slave architecture, where a single master device—typically a microcontroller—controls the communication by providing the clock signal and initiating transfers, while one or more slave devices respond passively without generating their own clock. This setup ensures deterministic timing and simplifies implementation, as slaves only need to detect the clock and select signals to participate. The full-duplex nature allows the master and slave to exchange data bits concurrently during each clock cycle, doubling the effective throughput compared to half-duplex alternatives. The protocol is optimized for short-distance connections, commonly spanning within a single (PCB) or up to approximately 10 meters with appropriate buffering to mitigate signal degradation. Unlike protocols with built-in addressing schemes, SPI lacks formal device addressing; instead, the master selects slaves individually using dedicated SS lines or through software-based decoding on a shared line, enabling point-to-point or multi-slave bus configurations.

Operation

Data Transmission Protocol

The Serial Peripheral Interface (SPI) operates as a synchronous, full-duplex master-slave protocol for serial data exchange between integrated circuits, where the master device controls the timing and flow of communication using four primary signal lines: serial clock (SCK), master out slave in (MOSI), master in slave out (), and slave select (). The master initiates each transaction by asserting the line low for the specific slave device, signaling the start of data transfer and enabling the slave to prepare for reception. This selection mechanism ensures that only the targeted slave responds, while others remain inactive. Once initiated, the master generates the SCK signal to synchronize the bit stream, shifting data serially in frames that are typically 8 bits long, with transmission occurring most significant bit (MSB) first. On the MOSI line, the master outputs its data bits, which the slave samples on designated clock edges; concurrently, the slave outputs its response data on the line, which the master samples on the same or corresponding edges, facilitating simultaneous bidirectional transfer. This full-duplex capability allows efficient data exchange without waiting for unidirectional cycles, though the exact sampling edges depend on the configured mode without altering the overall protocol flow. In the idle state, the SS line remains high and the clock idles at the level defined by the clock polarity (CPOL), preventing any unintended data activity and maintaining a stable bus condition. A transaction concludes when the master deasserts the SS line high, which resets the slave's internal shift registers and counters, preparing it for the next selection. This deassertion marks the end of the frame and ensures proper synchronization for subsequent operations. SPI lacks built-in error detection or correction mechanisms, such as cyclic redundancy checks (CRC) or hardware acknowledgments, making it a lightweight protocol that depends on overlying software layers for verifying and handling transmission errors. This design prioritizes speed and simplicity over robustness, suitable for short-distance, low-error environments like on-chip or board-level communications.

Clock Polarity and Phase

The Serial Peripheral Interface (SPI) protocol incorporates two key configurable parameters for the serial clock (SCLK): clock polarity (CPOL) and clock phase (CPHA). These parameters define the clock's idle state and the timing of data sampling relative to clock edges, ensuring between the master and slave devices during transmission. Clock polarity, denoted as CPOL, determines the default of the SCLK line during the period, which occurs when the (CS) signal is deasserted (high). A CPOL value of 0 configures the clock to low (), while CPOL = 1 sets it to high (). This polarity affects the initial state from which clock transitions occur when CS is asserted, influencing the overall and compatibility with connected peripherals. Clock phase, denoted as CPHA, specifies when is captured (sampled) by the receiver relative to the clock edges. With CPHA = 0, is sampled on the first clock edge after CS assertion—the —while the transmitter shifts on the opposite (trailing) edge. For CPHA = 1, sampling occurs on the second clock edge—the trailing edge—with shifting on the . This distinction separates the setup phase (where is prepared) from the capture phase (where it is read), preventing timing conflicts in bidirectional communication. The combination of CPOL and CPHA yields four distinct operating configurations, conventionally labeled as SPI modes 0 through 3, each producing unique clock waveforms that dictate data validity windows. In mode 0 (CPOL=0, CPHA=0), the clock idles low; data is sampled on the rising edge and shifted on the falling edge, resulting in a waveform where the first rising edge captures the initial bit after CS assertion. Mode 1 (CPOL=0, CPHA=1) also idles low but samples on the falling edge and shifts on the rising edge, with data setup occurring before the first falling edge. For mode 2 (CPOL=1, CPHA=0), the clock idles high; sampling happens on the falling edge (first transition from high), with shifting on the rising edge. Finally, mode 3 (CPOL=1, CPHA=1) idles high, sampling on the rising edge and shifting on the falling edge, where the first rising edge follows an initial high-to-low transition. These waveforms ensure data stability during transfers, with the master initiating pulses to align bits across MOSI and MISO lines. To maintain reliable operation, data must adhere to minimum setup and hold times around the sampling edges, as specified in device datasheets. Setup time is the duration data must be stable before the sampling edge, typically around 10 ns, while hold time requires stability after the edge, often exceeding 15 ns in some implementations to account for delays. Clock cycle times must accommodate these, for example, supporting frequencies up to 10 MHz with periods of at least 100 ns in certain peripherals. Mismatches in these timings can lead to bit errors, necessitating careful configuration. Among the modes, mode 0 (CPOL=0, CPHA=0) serves as the most common default in many systems due to its alignment with natural clock behaviors in logic, promoting broad interoperability unless a peripheral specifies otherwise. Masters are often designed to support all four modes for flexibility, while slaves may be fixed to one or two.

Mode Numbers and Valid Sequences

The Serial Peripheral Interface (SPI) defines four standard operating modes based on the combination of clock polarity (CPOL) and clock phase (CPHA) settings, which determine the clock's state and the timing of data sampling and shifting. These modes ensure compatibility between master and slave devices by standardizing how data is captured relative to clock edges. In Mode 0, CPOL is 0 and CPHA is 0, resulting in a clock that idles low and samples data on the leading (rising) edge while shifting data on the trailing (falling) edge. Mode 1 sets CPOL to 0 and CPHA to 1, with the clock idling low but sampling data on the trailing (falling) edge and shifting on the leading (rising) edge. Mode 2 uses CPOL=1 and CPHA=0, where the clock idles high and samples data on the leading (falling) edge, shifting on the trailing (rising) edge. Finally, Mode 3 combines CPOL=1 and CPHA=1, with the clock idling high, sampling on the trailing (rising) edge, and shifting on the leading (falling) edge. The following table summarizes the four SPI modes:
ModeCPOLCPHAIdle Clock LevelData Sample EdgeData Shift Edge
000LowRising (leading)Falling (trailing)
101LowFalling (trailing)Rising (leading)
210HighFalling (leading)Rising (trailing)
311HighRising (trailing)Falling (leading)
For reliable communication, the master and slave devices must operate in the same mode, as mismatches in CPOL or CPHA lead to incorrect data sampling and potential corruption. All pairings where the master and slave modes differ are incompatible, while identical modes (e.g., both Mode 0 or both Mode 3) enable proper synchronization. The table below illustrates compatible and incompatible pairings:
Master ModeCompatible Slave ModesIncompatible Slave Modes
001, 2, 3
110, 2, 3
220, 1, 3
330, 1, 2
Many SPI peripherals support multiple modes, configurable through hardware registers to match the requirements of connected devices, with Mode 0 being the most commonly implemented due to its simplicity and widespread adoption in legacy systems.

Chip Select and Interrupts

The (CS), also known as Slave Select (SS), serves as an active-low control signal in the Serial Peripheral Interface (SPI) to designate and enable a specific slave device for data exchange with the master. The master asserts the CS line low to activate the targeted slave, initiating the transaction, while deasserting it high concludes the exchange and places the slave's output in a high-impedance state to prevent bus contention. This mechanism ensures synchronous, full-duplex communication occurs exclusively between the master and the selected slave during the assertion period. In multi-slave configurations, the master utilizes distinct CS lines, each connected to a (GPIO) pin, to individually address slaves without requiring additional hardware decoding. Software on the master manages these lines by asserting only the CS corresponding to the intended slave for each transaction, thereby supporting scalable bus architectures while maintaining isolation between devices. Interrupts in SPI primarily support event-driven operation within controller modules but extend to basic signaling for transaction coordination between master and slave. From the master to the slave, the falling edge of the CS signal can generate an interrupt in the slave if supported by the hardware, alerting it to prepare for incoming data or to begin transmission synchronization. This edge detection leverages the CS assertion to trigger hardware interrupts for receive or transmit buffer management in the slave. Slave-to-master signaling lacks a uniform protocol in core SPI specifications, relying instead on implementation-specific techniques such as toggling the Master In Slave Out (MISO) line with predefined patterns to indicate data availability or using a dedicated (IRQ) line. A prevalent method involves the slave asserting a separate GPIO or IRQ pin low when data is ready for transmission, which the master monitors via its own to prompt an SPI read operation. Overall, SPI's interrupt mechanisms for device coordination are not standardized beyond module-level flags for events like transfer completion or buffer status, resulting in vendor-dependent approaches that differ across microcontroller implementations from manufacturers like Texas Instruments and Microchip Technology. This flexibility accommodates diverse applications but requires careful design consideration for interoperability.

Software Implementation

The Serial Peripheral Interface (SPI) is commonly implemented in software through dedicated hardware controllers or bit-banging techniques, depending on the microcontroller's capabilities and application requirements. Hardware SPI controllers are integrated peripherals in many microcontrollers, providing efficient, high-speed communication without significant CPU overhead. For instance, the AVR family from Microchip includes an SPI module configurable via registers like SPCR for mode selection (e.g., , clock polarity/phase) and SPSR/SPCR for baud rate control, supporting clock rates derived from the system clock. Similarly, microcontrollers from feature SPI peripherals with registers such as SPI_CR1 for mode and baud rate settings, and SPI_CR2 for operational control, enabling full-duplex transfers. These controllers can achieve baud rates up to 100 Mbps in advanced implementations, though typical rates range from 1 to 50 MHz to ensure reliable across short distances. The rate in hardware controllers is calculated based on the clock and prescaler values; for example, fSCK=fclk2×prescalerf_{SCK} = \frac{f_{clk}}{2 \times prescaler}, where fclkf_{clk} is the peripheral clock frequency and the prescaler divides it to set the desired SPI clock speed. This configuration allows developers to match the clock to peripheral device specifications, with common prescalers yielding rates like 8 MHz from a 16 MHz clock using a prescaler of 1. In devices, the formula aligns similarly, using the APB bus clock divided by a programmable prescaler (powers of 2 from 2 to 256). When hardware controllers are unavailable or flexibility is needed (e.g., on pin-constrained devices), bit-banging emulates SPI using general-purpose I/O (GPIO) pins to toggle the clock (SCK), master-out-slave-in (MOSI), master-in-slave-out (MISO), and slave select (SS) lines manually in software. This approach is simple to implement but CPU-intensive, as it requires the processor to handle timing and data shifting for each bit, limiting throughput to a fraction of hardware capabilities—often below 1 MHz on low-end MCUs. Precise timing is critical in bit-banging to avoid protocol violations; developers typically insert delays between pin changes or use hardware timers for more accurate clock generation, as imprecise delays can cause data misalignment or missed edges. A basic pseudocode example for an 8-bit full-duplex transfer in master mode (assuming mode 0: CPOL=0, CPHA=0) illustrates the process:

void spi_transfer(uint8_t tx_data, uint8_t* rx_data) { *rx_data = 0; digital_write(SS, LOW); // Assert slave select for (int i = 7; i >= 0; i--) { digital_write(MOSI, (tx_data >> i) & 1); // Set MOSI bit delay_us(half_period); // Setup time (clock low duration) digital_write(SCK, HIGH); // Clock high (rising edge) *rx_data |= (digital_read(MISO) << i); // Sample MISO on rising edge delay_us(half_period); // Clock high duration digital_write(SCK, LOW); // Clock low (falling edge) } digital_write(SS, HIGH); // Deassert slave select }

void spi_transfer(uint8_t tx_data, uint8_t* rx_data) { *rx_data = 0; digital_write(SS, LOW); // Assert slave select for (int i = 7; i >= 0; i--) { digital_write(MOSI, (tx_data >> i) & 1); // Set MOSI bit delay_us(half_period); // Setup time (clock low duration) digital_write(SCK, HIGH); // Clock high (rising edge) *rx_data |= (digital_read(MISO) << i); // Sample MISO on rising edge delay_us(half_period); // Clock high duration digital_write(SCK, LOW); // Clock low (falling edge) } digital_write(SS, HIGH); // Deassert slave select }

This loop shifts out the transmit byte while shifting in the receive byte, with half_period tuned to half the desired clock period for a 50% duty cycle (e.g., via a timer interrupt for better precision). To simplify development, libraries abstract these low-level details. The Arduino SPI library (SPI.h) provides functions like SPI.beginTransaction() for configuring modes and rates on supported boards, handling register setup internally. On Linux systems, the Python spidev module interfaces with the kernel's SPI driver for user-space access, offering methods like xfer() for data exchange and max_speed_hz for baud rate setting. These tools enable rapid prototyping while leveraging underlying hardware or software emulation.

Bus Configurations

Single Master-Multiple Slave

The single master-multiple slave configuration represents the conventional topology in SPI, enabling one master device to interface with multiple slave peripherals via a shared communication bus. This setup is widely used in embedded systems where the master, often a , coordinates data exchange with several devices simultaneously connected but addressed individually. In terms of wiring, the serial clock (SCK), master-out slave-in (MOSI), and master-in slave-out (MISO) lines are common to all slaves, while the master provides a dedicated slave select (SS) line to each slave from its (GPIO) pins. This parallel connection allows full-duplex communication on the shared lines without requiring additional wiring beyond the individual SS signals. Slave selection occurs when the master drives the target SS line low (active low in most implementations), deasserting all other SS lines to high; this activates only the intended slave for the transaction, ensuring orderly access to the bus. To prevent bus contention on the shared line, non-selected slaves must tri-state their MISO outputs, isolating them from the bus during inactive periods. The maximum number of slaves is primarily constrained by the availability of GPIO pins on the master for distinct SS lines, commonly supporting 8 to 16 devices in typical setups, though capacitive loading from additional slaves may necessitate speed reductions to maintain . Capacitive loading on the bus increases with the number of connected slaves and trace lengths, potentially degrading signal rise/fall times and requiring an extended clock period or lower frequencies; to mitigate this, bus lengths are generally limited to under 30 cm, and pull-up resistors (typically 10 kΩ) are often added to the line for stability. A representative example involves a microcontroller master connected to four slaves: an EEPROM for non-volatile storage, an analog-to-digital converter (ADC) for signal acquisition, a temperature sensor for environmental monitoring, and an LCD display for output visualization, all sharing the bus lines with individual SS controls.

Daisy Chain and Expander Setups

In daisy chain configurations for the Serial Peripheral Interface (SPI), multiple slave devices are interconnected in a linear series, with the serial data output (often denoted as MISO or DOUT) of one slave connected to the serial data input (MOSI or DIN) of the subsequent slave, while all slaves share a single chip select (SS) line, clock signal (SCLK), and ground. This setup allows the master to transmit data that propagates sequentially through the chain, where each clock cycle shifts bits one position forward, requiring the master to send a data frame equal in length to the total number of bits across all slaves. Upon deassertion of the SS line, each slave latches the appropriate portion of the shifted data for execution, enabling synchronized operation without individual addressing. Common use cases for daisy chaining include LED drivers and s, such as the 74HC595 serial-in/parallel-out , which is frequently chained to expand output capabilities for driving multiple LEDs or displays with minimal master pins. In such setups, the total effective bit width equals the number of slaves multiplied by the bits per slave; for instance, chaining ten 74HC595 devices (each handling 8 bits) creates an 80-bit capable of controlling 80 outputs simultaneously. This contrasts briefly with shared bus configurations, where multiple slaves connect in parallel to the same lines but require separate SS signals for selection. Expander configurations utilize dedicated SPI I/O expander chips, such as the Microchip MCP23S17, to augment the master's (GPIO) pins by adding up to 16 bidirectional ports per device over the SPI bus. The MCP23S17 interfaces via standard SPI signals (CS, SCK, SI, SO) and supports up to eight devices on the same bus through three hardware address pins (A0-A2), allowing selection via a control byte in the SPI transaction without needing multiple dedicated SS lines, though additional expanders beyond eight may require or separate CS groups. Configuration occurs through internal registers like IODIRA/B for direction control and GPIOA/B for data, operating at speeds up to 10 MHz in SPI modes 0,0 or 1,1. These setups offer key advantages, including a significant reduction in required master pins—often limiting to just SCLK, a chained MOSI/MISO path, and one SS—thereby simplifying wiring and enabling scalability in pin-constrained embedded systems. However, disadvantages include increased latency for non-terminal slaves, as must propagate through preceding devices (scaling linearly with chain length), and potential error propagation, where a fault in one slave can corrupt for all downstream devices. Additionally, expanders like the MCP23S17 introduce minimal overhead with low standby current (1 µA maximum) but require compatible slaves supporting pass-through shifting for .

Multidrop and Shared Bus Variants

In multidrop configurations of the Serial Peripheral Interface (SPI), multiple slaves share the clock (SCLK), master-out slave-in (MOSI), and master-in slave-out () lines, while each slave typically receives a dedicated (SS) line from the master to enable individual selection and prevent bus contention on MISO. Slaves without dedicated SS lines require tri-state capability on their MISO outputs, placing them in a high-impedance state when inactive to allow only the selected slave to drive the line. This shared bus supports multiple slaves, typically limited to 8-16 in practice by the availability of chip select lines on the master, with capacitive loading and affecting achievable bus speed and length, but demands precise timing to avoid data corruption. Shared bus variants extend this by enabling bidirectional operation on the data lines, often in a 3-wire mode where MOSI and MISO are combined into a single bidirectional line (SDIO or SISO), alongside SCLK and . This half-duplex configuration reduces pin count for space-constrained applications but prohibits simultaneous transmit and receive, with the master controlling direction via assertion or protocol commands. Tri-state buffers or internal drivers ensure the inactive direction does not interfere, maintaining bus integrity across multiple slaves. To implement addressing in setups with a shared SS line, expander integrated circuits (ICs) facilitate selection without dedicated lines per slave. For instance, SPI-controlled multiplexers like the ADG728 CMOS analog matrix switch use serial commands to route signals to specific channels, effectively addressing slaves by switching connections dynamically and minimizing master GPIO requirements. Similarly, SPI-to-I²C bridges allow protocol conversion, enabling I²C-style addressing (e.g., 7-bit slave IDs) over an SPI backbone for multidrop extension. These ICs support up to 8 or more channels, with low on-resistance for analog signals in mixed setups. Such variants face challenges including the lack of inherent , as SPI relies on master-driven timing without , potentially leading to errors if slaves erroneously drive . Additionally, software decoding of addresses or switching introduces latency—typically 1-2 clock cycles for tri-state control plus decoding time—compared to hardware SS selection, impacting real-time performance in high-speed applications. A practical example appears in industrial sensor networks, where multiple remote s (e.g., or devices) connect via a shared SPI bus over extended distances, using an initial address byte on MOSI to select the target before data exchange; bridges like the DS28E18 extend this to multidrop topologies with addressing for multiple devices (up to 10 or more, depending on configuration).

Advantages and Limitations

Key Advantages

The Serial Peripheral Interface (SPI) offers high data transfer speeds, typically ranging from several megabits per second up to over 100 Mbps in full-duplex mode, making it significantly faster than alternatives like (limited to 100-400 kbps in standard and fast modes) or UART (often capped at 115 kbps in typical implementations). This capability stems from SPI's synchronous nature, where a dedicated enables efficient bit-stream transmission without the overhead of asynchronous or multi-device addressing protocols. SPI's simplicity arises from its minimal protocol overhead, lacking start/stop bits, parity checks, or built-in addressing mechanisms, which are handled instead by individual (CS) lines for each slave device. This design facilitates straightforward hardware implementation using just four wires (clock, master-out-slave-in, master-in-slave-out, and CS), reducing complexity in both master and slave controllers compared to the multi-byte addressing required in or the rate matching in UART. As a result, SPI is particularly efficient for point-to-point or short-bus communications where direct, low-latency exchanges are prioritized. The full-duplex and synchronous operation of SPI allows simultaneous bidirectional data flow synchronized by the master's clock, enhancing efficiency for real-time applications such as sensor data acquisition or audio streaming, where I²C's half-duplex nature introduces delays. Furthermore, SPI provides flexibility through support for variable data frame sizes (commonly 8 to 16 bits) and easy integration of multiple slaves without complex , as each is independently selected via dedicated CS pins. This adaptability contrasts with UART's fixed asynchronous framing or I²C's reliance on shared addressing. SPI's cost-effectiveness is evident in its requirement for few pins and no external clock sources for slaves, as they derive timing directly from the master's , minimizing additional components like crystals or oscillators needed in asynchronous protocols. This lean architecture lowers both implementation costs and power consumption in resource-constrained systems, while maintaining robust performance over short distances without the need for pull-up resistors as in .

Principal Disadvantages

The Serial Peripheral Interface (SPI) lacks built-in addressing mechanisms, requiring a dedicated (CS) line for each slave device in multi-slave configurations, which increases pin count and limits scalability in systems with many peripherals. This design also does not natively support multi-master operation, as the protocol assumes a single master to control the clock and initiate transfers, necessitating additional hardware for any multi-master setups. SPI is constrained to short distances, typically 1-2 meters without signal conditioning, due to its single-ended signaling which is susceptible to electromagnetic interference and signal degradation over longer cables. Beyond this range, noise pickup and propagation delays can cause data errors unless differential drivers or repeaters are employed. The protocol provides no inherent error detection or correction, such as parity bits or cyclic redundancy checks (CRC), making it vulnerable to transmission glitches that go undetected without external filtering or software checks. Additionally, SPI lacks acknowledgment mechanisms, so the master has no confirmation of successful data reception by the slave. In power-sensitive applications, SPI can consume more energy than alternatives like I²C, primarily due to its use of multiple signal lines (MOSI, MISO, SCLK, and CS) and support for higher clock speeds, which increase active pin toggling and overall current draw in embedded systems. Continuous clocking during transfers further contributes to higher power usage in battery-powered devices. SPI's implementation varies across vendors, as there is no formal standardization body or specification defining clock modes, timing, or electrical characteristics uniformly, leading to potential interoperability issues between devices from different manufacturers.

Common Applications

Embedded Systems and Microcontrollers

The Serial Peripheral Interface (SPI) is ubiquitous in modern microcontrollers, serving as a standard peripheral for interfacing with external devices in embedded systems. Major microcontroller families, including ARM Cortex-M series from vendors like STMicroelectronics and NXP, Microchip's PIC and AVR architectures, integrate dedicated SPI hardware modules to enable efficient communication with sensors and actuators. For instance, the Bosch BMP280 barometric pressure sensor commonly connects via SPI to these MCUs for precise environmental data acquisition in compact designs. In real-time control applications, SPI facilitates rapid data polling and synchronization essential for time-sensitive operations. Automotive electronic control units (ECUs) leverage SPI to interface with sensors and actuators for engine management and safety systems, ensuring low-latency responses in dynamic environments. Similarly, in (IoT) devices, SPI enables fast communication between microcontrollers and peripherals like accelerometers, supporting efficient data collection in battery-constrained networks. Practical examples highlight SPI's versatility in hobbyist and prototyping platforms. The utilizes its onboard SPI interface for GPIO expansion via chips like the Microchip MCP23S08, allowing additional pins for controlling LEDs, relays, or custom circuits without taxing the limited native GPIO resources. On boards, SPI connects to modules for data logging, enabling storage of sensor readings or program states in portable projects. To optimize energy efficiency in battery-powered embedded devices, many microcontrollers incorporate low-power SPI modes that align with sleep states, minimizing current draw during idle periods while allowing quick wake-up for peripheral interactions. For example, ' MSP430 series supports SPI operation in low-power modes, extending battery life in wearables and remote sensors.

Data Storage and Displays

Serial Peripheral Interface (SPI) plays a crucial role in applications, particularly with NOR and NAND flash memory chips, where it enables efficient command-based access for reading and writing code and data. NOR flash devices, such as the Winbond W25Q series, provide reliable, random-access storage suitable for executable code and configuration data, supporting standard SPI operations with opcodes for tasks like page reads, program, and sector erases. These chips typically operate at clock frequencies up to 104 MHz in single SPI mode, allowing for straightforward integration in embedded storage scenarios. SPI NAND flash, exemplified by Winbond's W25N series, extends storage capacity for denser data applications while maintaining compatibility with SPI protocols, including buffer reads and continuous read modes for . These devices use command structures similar to NOR flash but incorporate NAND-specific features like page-based operations and error correction, achieving read throughputs of up to 52 MB/s in practical implementations. SD and MMC cards also leverage SPI mode for low-speed access, supporting clock rates up to 25 MHz to enable simple, cost-effective data logging and transfer without dedicated high-speed controllers. In display applications, SPI facilitates the transfer of data to and panels, enabling compact, low-pin-count interfaces for graphical output. drivers like the SSD1306 support SPI for writing data to an internal 128x64 frame buffer, where each byte controls eight vertical in a column-addressed manner, often paired with DMA for burst transfers to minimize CPU overhead. Similarly, controllers such as the ILI9341 use SPI to stream RGB values to a 240x320 resolution display, supporting frame buffer updates for dynamic content rendering in portable devices. SPI flash memory is integral to bootloader implementations, storing initial firmware for system initialization and enabling over-the-air updates in networked devices. In routers, such as EdgeRouters, SPI NOR flash holds multi-stage bootloaders that load subsequent images, facilitating recovery and upgrades via serial access. Digital cameras, including models from , utilize SPI flash for persistent storage of and settings, allowing in-field updates while maintaining boot integrity. The full-duplex nature of SPI enhances efficiency in these bidirectional operations, such as verifying update integrity during writes.

Protocol Variations

Standard and Timing Extensions

The original specification for the Serial Peripheral Interface (SPI), as outlined in Motorola's Application Note AN991, defined fixed 8-bit frame transfers with data shifted most significant bit (MSB) first and no built-in flow control beyond the slave select () signal. The original specification supported configurable clock polarity (CPOL) and phase (CPHA), with mode 0 (CPOL=0, CPHA=0) being a common configuration where the clock idles low and data is sampled on the first rising edge. Subsequent extensions in microcontroller implementations have introduced variable transmission sizes, typically configurable from 4 to 32 bits through controller registers, allowing flexibility for different peripherals without fixed 8-bit limitations. Additionally, options for least significant bit (LSB)-first or MSB-first shifting have been added, controlled by bits in the SPI control registers to match specific device requirements. Timing variations include support for half-duplex operation, where only one data line (MOSI or ) is used for unidirectional transfers, effectively disabling the bidirectional full-duplex nature of standard SPI. In some variants, particularly for multidrop configurations with sensors, address-based selection replaces dedicated lines; the master sends an address byte over the data lines to target a specific slave, reducing pin count at the expense of added protocol overhead. Hardware extensions often involve standardized pinouts for interconnects, such as 2x2 headers arranging SCK, MOSI, , and for easy prototyping. To bridge voltage domains, level shifters are commonly used for interfacing 5V-tolerant masters with 3.3V slaves, preventing signal damage while maintaining compatibility.

Multi-Bit and High-Speed Modes

To enhance throughput beyond the standard single-data-line configuration of the Serial Peripheral Interface (SPI), multi-bit modes extend the protocol by utilizing additional bidirectional I/O lines for parallel data transfer during specific phases of communication. These modes maintain the core SPI signals—clock (SCK), (CS), and serial data—while repurposing extra pins to increase bandwidth, particularly in applications requiring faster access to devices like NOR flash. Dual and quad variants are the most prevalent, offering scalable performance improvements without necessitating a complete redesign of the interface. Dual SPI mode employs two bidirectional data lines, typically designated as IO0 and IO1, to transmit or receive two bits per clock cycle during the address and data phases. This configuration effectively doubles the bandwidth compared to standard SPI, enabling throughput rates around 20 Mbps in typical implementations. It is configured via specific commands, such as 0xBB for dual I/O fast read, and supports half-duplex operation while remaining compatible with existing SPI hardware. Quad SPI (QSPI) further advances this by leveraging four bidirectional data lines (IO0 through IO3), allowing up to four bits per clock cycle in the data phase and achieving approximately four times the throughput of single-line SPI. Commonly integrated in controllers, QSPI supports commands like 0xEB for quad input/output fast read, and at an 80 MHz clock frequency, it can deliver around 40 MB/s in single data rate (SDR) mode. Vendor-specific implementations, such as Spansion's (now Infineon) Quad Peripheral Interface (QPI), extend this by transmitting the instruction, , and data phases all in 4-bit parallel format (4-4-4 mode), requiring explicit enabling via configuration registers for seamless high-speed operation. High-speed enhancements like (DDR) mode complement multi-bit configurations by sampling data on both the rising and falling edges of the , effectively doubling the transfer rate without raising the clock frequency. When combined with quad modes, DDR can yield bandwidths up to 80 MB/s at 80 MHz clocks in 1.8 V devices, or higher in advanced implementations. These modes often operate in SDR by default but can switch to DDR via device-specific commands. A key advantage of multi-bit and high-speed modes is their with standard single-line SPI, using the same pinout for core signals and additional I/O lines only when needed. The command phase typically remains single-line to ensure , with the controller issuing a mode-entry command before shifting to dual or quad data transfer, allowing legacy devices to coexist on the bus. The Microwire protocol, developed by , is a three-wire that operates in full-duplex mode, utilizing a serial clock (SK), serial data output (SO), and serial data input (SI) without a dedicated line for individual slaves. This variant simplifies wiring compared to standard four-wire SPI while maintaining compatibility with master-slave communication for peripherals like EEPROMs in embedded systems. Microwire/Plus extends the original protocol by adding a line to indicate slave readiness and supporting variable word lengths up to 16 bits per transfer, enabling more efficient handling of asynchronous operations in applications. These enhancements reduce protocol overhead in scenarios requiring precise timing control, such as in National Semiconductor's COP8 family. Three-wire SPI variants omit either the master-out slave-in (MOSI) or master-in slave-out () line, resulting in a unidirectional, half-duplex configuration that combines data lines into a single bidirectional path alongside the clock and signals. This approach is commonly used in space-constrained devices like displays or sensors, where full-duplex capability is unnecessary, though it limits simultaneous bidirectional data flow. SafeSPI, an extension for automotive and IoT applications, incorporates AES-128 and mechanisms to secure data transmission against tampering and , achieving ASIL B compliance. The protocol standardizes 32-bit or 48-bit frame lengths with built-in cyclic redundancy checks (CRC) for error detection, making it suitable for safety-critical networks in vehicles. High-reliability enhancements to SPI often include CRC polynomials for data integrity verification and watchdog timers to detect and recover from communication timeouts, particularly in aerospace environments where bit errors from radiation or noise are prevalent. For instance, ESA-prototyped space-grade SPI protocols append 16-bit CRCs to frames and implement redundant clocking to ensure transmission reliability exceeding 99.999% in harsh conditions. These features mitigate single-event upsets without altering the core SPI timing. Intelligent SPI controllers in modern microcontrollers integrate direct memory access (DMA) engines and first-in first-out (FIFO) buffers to offload CPU involvement, allowing burst transfers up to several kilobytes without interrupt overhead. This is evident in devices like NXP's LPC series, where DMA reduces latency in high-throughput applications such as data logging, while FIFOs (typically 16-64 words deep) buffer data to handle clock domain mismatches. Other SPI-related protocols include Serial GPIO (SGPIO), a four-wire bus for low-speed status signaling in storage enclosures, such as LED drive and fault indication, standardized by SNIA for SAS/ backplanes. Intel's SPI (eSPI) serves as a low-pin-count replacement for the legacy LPC bus, multiplexing virtual channels over a two-wire serial link for access and sideband communications in PCs. JTAG (IEEE 1149.1) provides an alternative serial interface for boundary-scan testing and debugging, often used interchangeably with SPI in development flows but focused on in-system programmability rather than general data exchange.

Development and Debugging

Hardware Tools and Adapters

USB to SPI adapters provide a convenient bridge between personal computers and SPI-enabled devices, enabling prototyping and testing without dedicated hardware. The from offers a single-channel USB 2.0 Hi-Speed interface configurable for SPI master operation, supporting all four standard SPI clock modes (0-3) with data rates up to 30 MHz in synchronous FIFO mode. Similarly, the CH341 chipset, commonly used in low-cost adapters, supports SPI master operation, compatible with standard modes, with compatibility for USB 2.0 full-speed operation and voltage levels of 3.3V or 5V. These adapters typically include GPIO pins for (CS) and signals, facilitating direct connection to peripherals like sensors or EEPROMs. Single-board computers such as the and BeagleBone Black integrate SPI interfaces directly on their GPIO expansion headers, simplifying embedded development. The models (e.g., Pi 4 and 5) feature two SPI buses on the 40-pin header, with pins 19 (), 21 (MOSI), 23 (SCLK), and 24 (CE0) for the primary bus, operating at up to 125 MHz but typically clocked at 3.3V logic levels. The BeagleBone Black provides two SPI instances (SPI0 and SPI1) on its 92-pin P8 and P9 headers, such as P9.31 (SPI0 SCLK) and P9.29 (SPI0 D0), supporting up to 48 MHz and configurable via device tree overlays for 3.3V operation. These headers allow straightforward wiring to SPI slaves, often requiring only enabling the interface in the OS configuration. Breakout boards enhance SPI connectivity by addressing voltage mismatches and bus expansion needs. Logic level converters, such as the bi-directional TXB0108E module, enable safe interfacing between 3.3V microcontrollers and 5V peripherals by shifting signals on MOSI, , SCLK, and CS lines without direction control pins. For multi-device setups, SPI multiplexers like the CD74HC4067 16-channel analog/digital breakout board route signals to multiple slaves via addressable selection, operating at 3.3V to 5V and supporting SPI ADCs or sensors by data lines. These boards often include pull-up resistors and decoupling capacitors to ensure signal integrity. Connectors for SPI applications vary by device type, with IDC (Insulation Displacement Connector) headers being standard for prototyping on 2.54 mm pitch GPIO expansions, rated for 3.3V to 5V signals. For compact displays and modules, FPC (Flexible Printed Circuit) connectors, such as 18-pin 0.5 mm pitch variants, provide slim, high-density links for SPI TFT or screens, typically limited to 3.3V operation to avoid damaging thin-film traces. SPI wiring generally follows a master-slave with dedicated lines for each, as referenced in standard bus configurations. Hardware tools, including the Saleae Logic Pro 16 (released in 2014, with updates in 2022), offer advanced USB-based logic analysis for SPI debugging with 16 channels, 500 MS/s sampling, and built-in protocol decoders for modes 0-3, capturing up to 100 MHz signals at an accessible price point for professionals. This analyzer includes analog inputs shared with digital channels, aiding in mixed-signal SPI verification on prototypes. In 2025, Total Phase released high-speed and SPI analysis applications for the Promira Serial Platform, supporting advanced protocol decoding and monitoring.

Software Simulators and Analyzers

Software simulators for the Serial Peripheral Interface (SPI) enable engineers to model and verify protocol behavior without physical hardware. , a free SPICE-based tool from , supports analog timing simulations for SPI signals, allowing users to analyze , , and noise effects in circuit designs. For digital aspects, hardware description languages like and are commonly used to create SPI master and slave models, simulated with tools such as from EDA, which provides cycle-accurate verification of data transmission and mode configurations. Open-source options include Verilog for compiling and simulating Verilog-based SPI testbenches, facilitating rapid prototyping in FPGA development environments. Protocol analyzers decode captured SPI frames to aid debugging, focusing on signal alignment and transaction integrity. Saleae Logic software includes a built-in SPI analyzer that decodes clock (SCK), data (MOSI/), and slave select () lines, with triggers configurable on SS edges to isolate specific device communications. Mixed-signal oscilloscopes enhance this capability; for instance, models like the 5 Series MSO offer automated SPI decoding and triggering on events such as frame errors or specific byte values, combining analog waveform viewing with digital protocol overlays. Similarly, Keysight's Infiniium series with the N5391B option provides hardware-accelerated /SPI decoding, enabling time-correlated views of protocol violations across multiple channels. Open-source tools extend accessibility for SPI analysis. Sigrok's PulseView frontend, paired with libsigrokdecode, supports SPI protocol decoding from various logic analyzers, extracting MOSI/MISO bytes and identifying mode-dependent timing (e.g., CPOL/CPHA) in captured sessions. For higher-layer integration, captures from SPI analyzers can be exported to using plugins or utilities, allowing dissection of encapsulated protocols like IPMI over SPI in embedded systems. Best practices for SPI software debugging emphasize comprehensive capture and error detection to ensure reliable verification. Engineers should configure analyzers to record full transactions, including preamble SS assertions and mode-specific clock polarities/phases, to validate sequence integrity across SPI modes 0-3. Glitch detection is critical; tools like Saleae's software glitch filter mitigate false triggers from noise, while oscilloscope features in Keysight and Tektronix instruments highlight timing anomalies such as runt pulses or overshoots that could corrupt data. Prioritizing non-intrusive logging and iterative simulation helps isolate issues like bit misalignment before hardware integration.

Terminology and Standards

Alternative Names and Definitions

The Serial Peripheral Interface (SPI) is commonly referred to interchangeably as the "SPI bus" or "SPI interface" in technical documentation and datasheets, with "bus" emphasizing the shared communication pathway among multiple devices and "interface" highlighting the connection protocol between a controller and peripherals. This dual nomenclature arises from its role as a synchronous serial communication standard, originally developed by Motorola in the mid-1980s as a proprietary module for microcontrollers. Over time, as the technology became widely adopted beyond Motorola's ecosystem—now under NXP Semiconductors—the term has evolved from the full "Serial Peripheral Interface" to more generic descriptors like "SPI serial interface" or simply "serial interface" in modern hardware references, reflecting its de facto standardization without formal oversight. In some contexts, particularly older documentation, SPI is occasionally abbreviated or referred to as (SSI), though this can lead to confusion since SSI typically denotes a distinct protocol used in industrial sensors like rotary encoders, which employs differential signaling and operation rather than SPI's full-duplex, single-ended lines. Vendor-specific naming further complicates terminology; for instance, Motorola's original implementation was branded as the SPI module, while Freescale (now NXP) distinguished it from their Serial Communications Interface (SCI), which refers to asynchronous serial communication akin to UART rather than SPI's synchronous mode. A frequent point of confusion involves distinguishing standard SPI from Quad SPI (QSPI), an enhanced variant that uses four lines for parallel transfers instead of SPI's single bidirectional pair; while QSPI builds directly on SPI principles for higher throughput in applications like , it is not a separate protocol but an extension, leading some to mistakenly treat them as unrelated interfaces. Another common misconception is that SPI operates exclusively under master control with no slave agency, whereas although the master alone drives the clock and initiates transactions, slaves can effectively request communication by asserting dedicated lines to the master, prompting it to poll or read . Additionally, SPI is sometimes erroneously associated with communication, but it is strictly a wired, short-distance protocol limited to board-level or chip-to-chip connections without components.

Standardization Efforts

The Serial Peripheral Interface (SPI) has historically functioned as a , originally developed by in the mid-1980s without oversight from a centralized standards body, leading to widespread adoption through proprietary implementations in embedded systems and peripherals. Formal standardization efforts emerged primarily in the and accelerated into the , focusing on specific domains such as and platform interfaces rather than a comprehensive protocol definition. These initiatives address challenges by defining discoverable parameters, extended modes, and compliance mechanisms, though gaps persist in areas like high-speed variants for automotive and IoT applications. JEDEC has played a key role in partial formalization through memory-specific standards. The JESD216 standard, first published in 2011 and updated to revision B in 2016, establishes the Serial Flash Discoverable Parameters (SFDP) framework, enabling SPI-compatible NOR flash devices to self-describe their operational features, such as command sets, timing modes, and density, via a standardized database readable over the SPI bus. Later revisions, such as JESD216F (December 2021), incorporate support for xSPI profiles to enhance discoverability in high-speed modes. Building on this, JEDEC's JESD251C (published in May 2022) defines the eXpanded SPI (xSPI) specification for non-volatile memory devices, supporting higher data throughput up to several hundred MB/s through multi-bit modes while maintaining low pin counts. Intel's Enhanced SPI (eSPI) interface base specification, originally released in 2016 but integrated into client and server platforms post-2020 (e.g., 11th-generation Core processors and later), replaces legacy LPC buses with a multiplexed SPI-based architecture for peripherals like super I/O and ECs, emphasizing power efficiency and security features. In automotive contexts, standardization efforts have emphasized compliance. For instance, high-speed SPI NOR flash devices, supporting dual/quad modes with data rates exceeding 100 MB/s, have achieved ASIL-D certification as early as 2023, ensuring reliability in safety-critical systems like ADAS and , though broader protocol-level standards for (DDR) extensions remain vendor-specific. Compliance testing for mode interoperability—such as clock polarity/phase (CPOL/CPHA) variations and multi-device daisy-chaining—relies on specialized tools like Soliton Technologies' SPI Protocol Validation Suite, which uses PXI-based hardware to automate electrical and protocol checks against de facto baselines. Overall, while these efforts mitigate fragmentation, comprehensive IEEE or ISO for core SPI remains absent, leaving room for further unification in high-impact areas like automotive and .

References

Add your contribution
Related Hubs
User Avatar
No comments yet.