Serial Peripheral Interface: Difference between revisions

Content deleted Content added
fixed broken link
 
(42 intermediate revisions by 26 users not shown)
Line 1:
{{Short description|Synchronous serial communication interface}}
{{Cleanup rewrite|[[WP:NOTTEXTBOOK|it reads like a guide or textbook]]|article|date=March 2021}}
{{recentism|date=December 2023}}
{{Infobox connector <!-- NOTE: Not a perfect template match, but good enough for now -->
| name = Serial Peripheral Interface (SPI)
Line 8 ⟶ 7:
| data_style = [[Full-duplex]] [[serial communication|serial]]
| daisy_chain = [[#Daisy chain configuration|Depends]] on devices
| manufacturer = variousVarious
| data_devices = [[#Multidrop configuration|Multidrop]] limited by chipslave selects. [[#Daisy chain configuration|Daisy chaining]] unlimited.
| data_bit_width = 1 bit (bidirectional)
| high_freq = yes
| pin_custom1_name = MOSI
| pin_name_custom1 = MasterOutMaster Out Slave In
| pin_name_custom2 = Master In Slave Out
| pin_custom2_name = MISO
| pin_custom3_name = SCLK
| pin_custom4_name = {{Overline|CSSS}}
| pin_name_custom3 = Serial Clock
| pin_name_custom4 = [[ChipSlave Select]] (one or more)
| pinout_notes = (pins may have [[#Alternative terminology|alternative names]])
| maximum_voltage = Unspecified
| maximum_current = Unspecified
| physical_connector = Unspecified
| design_date = Around early 1980s{{NoteTag|The earliest definitive mention of a "Serial Peripheral Interface" in bitsavers archives of Motorola manuals is from 1983 (see {{slink||Original definition}}). While some sources on the web allege that Motorola introduced SPI when 68000 was introduced in 1979, however many of those appear to be [[citogenesis]] or speculation, and Motorola's 1983 68000 manual has no mention of "Serial Peripheral Interface", so the alleged 1979 date doesn'tdoes not seem to be reliable information. Please only add a specific design_date if you have a definitive source from Motorola around then.}}
}}
 
'''Serial Peripheral Interface''' ('''SPI''') is a [[de<!--DO factoNOT standard|''ITALICIZE; CONSIDERED ANGLICIZED-->[[de facto'' standard]] (with many [[#Variations|variants]]) for [[Comparison of synchronous and asynchronous signalling|synchronous]] [[serial communication]], used primarily in [[embedded systems]] for short-distance [[wired communication]] between [[integrated circuits]].
 
SPI usesfollows a [[master–slave (technology)|master–slave architecture]], described here with the terms "main" and "sub",{{NoteTag|The {{slink||Alternative terminology}} section gives more details on proposed alternative terminology. See [[Talk:Serial Peripheral Interface#Terminology|the talk page]] for an ongoing discussion.}} <ref name=":0">{{Cite web |last=DhakerStoicescu |first=PiyuAlin |date=2018 |title=IntroductionGetting toStarted SPIwith InterfaceSPI |url=https://wwwww1.analogmicrochip.com/downloads/en/analog-dialogueAppnotes/articles/introductionTB3215-toGetting-spiStarted-interface.html |urlwith-status=live |archiveSPI-url=https://web90003215A.archive.org/web/20230525152752/https://www.analog.com/en/analog-dialogue/articles/introduction-to-spi-interface.html |archive-date=2023-05-25 |access-date=2023-07-21pdf |website=[[Analog DialogueMicrochip]]}}</ref> where one{{NoteTag|For any given transaction, only one device is the main. However, some devices support changing main and sub roles on the fly. Most microcontrollers can easily reconfigure their SPI's role, and some Atmel and Silabs devices can change roles depending on an external pin.}}a mainmaster device [[Signaling (telecommunications)|orchestrates communication]] with someone numberor ofmore peripheral (sub)slave devices by driving the [[clock signal|clock]] and [[chip select]] signal(s)signals. Some devices support changing master and slave roles on the fly.
 
[[Motorola]]'s original specification (from the early 1980s) uses four [[Wire|wireslogic signal]]s, aka lines or wires, to performsupport [[full duplex]] communication. It is sometimes called a ''four-wire'' [[serial bus]] to contrast with [[Serial Peripheral Interface#Three-wire|three-wire]] variants which are [[half duplex]], and with the ''two-wire'' [[I²C]] and [[1-Wire]] serial buses.
 
Typical [[#Applications|applications]] include interfacing [[microcontrollers]] with peripheral chips for [[Secure Digital]] cards, [[liquid crystal display]]s, [[analog-to-digital]] and [[digital-to-analog converters]], [[Flash memory#Serial flash|flash]] and [[EEPROM#Serial bus devices|EEPROM]] memory, and various communication chips.
 
Although SPI may be accurately described asis a synchronous serial interface,<ref>{{cite web |url= https://digital.ni.com/public.nsf/allkb/862567530005F09C862566BE004E469D |title= What is Serial Synchronous Interface (SSI)? |access-date= 2015-01-28 }}</ref> but it is different from the [[Synchronous Serial Interface]] (SSI) protocol.{{NoteTag|While [[Synchronous Serial Interface]] (SSI) is also a four-wire synchronous serial communication protocol, the SSI protocol employs [[differential signaling]] and provides only a single [[simplex communication]] channel.}}
 
==Operation==
[[File:SPI_single_slave.svg|thumb|368x368px|Single master to single slave: basic SPI wiring]]
''<small>(Note: [[#Variations|Variations]] section describes operation of non-standard variants.)</small>''
 
Commonly, SPI has four logic signals. [[#Variations|Variations]] may use different [[#Alternative terminology|names]] or have different signals.
[[File:SPI basic operation, single Main & Sub.svg|thumb|368x368px|Figure 1: Basic SPI configuration using a single main and a single sub. Each device internally uses a [[shift register]] for serial communication, which together forms an inter-chip [[circular buffer]].]]
 
SPI has four [[Logic signal|logic signals]] (which may have [[#Alternative terminology|alternative names]]):
:{| class="wikitable"
! Short<br/>Name Abbr.!! Long<br/>Name !! Description<br/>(historical terms in parens)
|-
| {{center|{{Overline|CSSS}}}} || {{center|ChipSlave Select}} || [[Logic level#Active state|Active-low]] [[Chip select|chip select signal]] fromsignal mainfrom (master) to<br />enable communication with a specific sub (slave) device.
|-
| {{center|SCLK}} || {{center|Serial Clock}} || [[Clock signal]] from main (master) transitions for each serial data bit.
|-
| {{center|MOSI}} || {{center|MainMaster Out, SubSlave In<br/>(master out, slave in)}} || [[Serial communication|Serial data]] output from main (master), highest bit first.
|-
| {{center|MISO}} || {{center|MainMaster In, SubSlave Out<br/>(master in, slave out)}} || [[Serial communication|Serial data]] output from sub (slave), highest bit first.
|}
 
MOSI on a mainmaster outputs to MOSI on a subslave. MISO on a subslave outputs to MISO on a mainmaster.
 
[[File:SPI basic operation, single Main & Sub.svg|thumb|368x368px|Figure 1: Basic SPI configuration using a single main and a single sub. Each device internally uses a [[shift register]] for serial communication, which together forms an inter-chip [[circular buffer]].]]
SPI operates with a single device acting as main and with one or more sub devices.
 
SubSlave devices should use [[tri-state output]]s so their MISO signal becomes [[high impedance]] (''electrically disconnected'') when the device is not selected. SubsSlaves without tri-state outputs cannot share a MISO wireline with other subsslaves without using an external tri-state buffer.
 
===Data transmission===
[[File:SPI 8-bit circular transfer.svg|upright=1.8|thumb|A typical hardware setup using two [[shift register]]s to form an inter-chip [[circular buffer]] ]]
To begin communication, the SPI mainmaster first selects a subslave device by pulling its {{Overline|CSSS}} low. (Note: theThe bar above {{Overline|CSSS}} 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 mainmaster must wait for at least that period of time before issuing clock cycles.{{NoteTag|Some subsslaves require a falling edge of the {{Overline|ChipSlave Select}} signal to initiate an action. An example is the Maxim MAX1242 ADC, which starts conversion on a high→low transition.}}
 
During each SPI clock cycle, full-duplex transmission of a single bit occurs. The mainmaster sends a bit on the MOSI line while the subslave 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 sub (Figure 1)slave involves one shift register in the mainmaster and one shift register in the subslave, both of some given word size (e.g. 8 bits),{{NoteTag|Transmissions. The transmissions often consist of eight-bit words., However,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.}} connected in a virtual [[ring topology]]. Data is usually shifted out with the [[most-significant bit]] (MSB) first.{{NoteTag|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 main and sub 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 main and sub 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 main stops toggling the clock signal, and typically deselects the sub.
 
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 sub device is used, its {{Overline|CS}} pin ''may'' be fixed to [[logic level|logic low]] if the sub permits it. With multiple sub devices, a [[#Multidrop configuration|multidrop configuration]] requires an independent {{Overline|CS}} signal from the main for each sub device, while a [[#Daisy chain configuration|daisy-chain configuration]] only requires one {{Overline|CS}} signal.
 
If a single subslave device is used, its {{Overline|CSSS}} pin ''may'' be fixed to [[logic level|logic low]] if the subslave permits it. With multiple subslave devices, a [[#Multidrop configuration|multidrop configuration]] requires an independent {{Overline|CSSS}} signal from the mainmaster for each subslave device, while a [[#Daisy chain configuration|daisy-chain configuration]] only requires one {{Overline|CSSS}} signal.
Every sub on the bus that has not been selected should disregard the input clock and MOSI signals. And to prevent [[Bus contention|contention]] on MISO, non-selected subs must use [[Three-state logic|tristate]] output. Subs that aren't already tristate will need external tristate buffers to ensure this.<ref name="Better SPI Bus Design in 3 Steps" />
 
Every subslave on the bus that has not been selected should disregard the input clock and MOSI signals. And to prevent [[Bus contention|contention]] on MISO, non-selected subsslaves must use [[Three-state logic|tristate]] output. SubsSlaves that aren'tare not already tristate will need external tristate buffers to ensure this.<ref name="Better SPI Bus Design in 3 Steps" />
 
===Clock polarity and phase===
In addition to setting the clock frequency, the mainmaster must also configure the clock polarity and phase with respect to the data. Motorola<ref>[https://web.archive.org/web/20150413003534/http://www.ee.nmt.edu/~teare/ee308l/datasheets/S12SPIV3.pdf SPI Block Guide v3.06; Motorola/Freescale/NXP; 2003.]</ref><ref name=":4" /> named these two options as CPOL and CPHA (for '''c'''lock '''pol'''arity and '''c'''lock '''pha'''se) respectively, a convention most vendors have also adopted.
 
[[File:SPI timing diagram CS.svg|thumb|338x338px|SPI [[Digital timing diagram|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]].]]
Line 85 ⟶ 86:
* CPHA represents the [[Phase (waves)|phase]] of each data bit's transmission cycle relative to SCLK.
** For CPHA=0:
*** The first data bit is outputtedoutput ''immediately'' when {{Overline|CSSS}} activates.
*** Subsequent bits are outputtedoutput 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 outputtedoutput on SCLK's first clock edge ''after'' {{Overline|CSSS}} activates.
*** Subsequent bits are outputtedoutput 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.
** Note: 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 mainmaster and subslave devices may sample data at different points in that half cycle, for flexibility, despite the original specification.
 
===Mode numbers ===
Line 100 ⟶ 101:
|-
! SPI mode
! Clock polarity<br />(CPOL)
! Clock phase<br />(CPHA)
!Data is shifted out on
! Data is sampled on
|-
| 0 || 0 || 0
|falling SCLK, and when {{Overline|CSSS}} activates || rising SCLK
|-
| 1 || 0 || 1
Line 112 ⟶ 113:
|-
| 2 || 1 || 0
| rising SCLK, and when {{Overline|CSSS}} activates || falling SCLK
|-
| 3 || 1 || 1
Line 121 ⟶ 122:
 
* 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 mainmaster 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 ===
Some subslave 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===
Interrupts are outside the scope of SPI; their usage is neither forbidden nor specified, and so may optionally be implemented optionally.
 
==== From mainmaster to subslave ====
Microcontrollers configured as subslave devices may have hardware support for generating interrupt signals to themselves when data words are received or overflow occurs in a receive [[FIFO (computing and electronics)|FIFO]] buffer,<ref>{{Cite web |date=2002 |title=TMS320x281x Serial Peripheral Interface Reference Guide |url=https://www.ti.com/lit/pdf/spru059 |website=[[Texas Instruments]] |pages=16–17}}</ref> and may also set up an interrupt routine when their chipslave select input line is pulled low or high.
 
==== From subslave to mainmaster ====
SPI subsslaves sometimes use an [[out-of-band signal]] (another wire) to send an interrupt signal to a mainmaster. Examples include pen-down interrupts from [[touchscreen]] sensors, thermal limit alerts from [[List of temperature sensors|temperature sensors]], alarms issued by [[real-time clock]] chips, [[Secure Digital#SDIO|SDIO]]{{NoteTag|Not to be confused with the SDIO (Serial Data I/O) line of the half-duplex implementation of SPI sometimes also called "3-wire" SPI. Here e.g. MOSI (via a resistor) and MISO (no resistor) of a mainmaster is connected to the SDIO line of a subslave.|name=3wireSDI}} and [[audio jack]] insertions for an [[audio codec]]. Interrupts to mainmaster may also be faked by using [[Polling (computer science)|polling]] (similarly to [[USB 1.1]] and [[USB 2.0|2.0]]).
 
===Software design===
Line 140 ⟶ 141:
 
===Bit-banging the protocol===
The [[pseudocode]] below outlines a software- implementation ("[[bit-banging]]") of SPI's protocol as a mainmaster with simultaneous output and input. This pseudocode is for CPHA=0 and CPOL=0, thus SCLK is pulled low before {{Overline|CSSS}} 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 {{Overline|CSSS}} as high
* Pull {{Overline|CSSS}} low to select the subslave
* Loop for however many number of bytes to transfer:{{NoteTag|Peripherals may allow or require a particular number (or any number) of transfer bytes while selected, as specified in their datasheet.}}
** Initialize{{Code|byte_out|C}}with the next output byte to transmit
** Loop 8 times:
*** [[Left-shift operator|Left-Shift]]{{NoteTag|Left-shifts are used because SPI normally transmits the most-significant bit first. Right-shifts could instead be used to transfer least-significant bit first.}} the next output bit from{{Code|byte_out|C}}to MOSI
*** [[NOP (code)|NOP]] for the subslave's [[setup time]]
*** Pull SCLK high
*** Left-Shift the next input bit from MISO into{{Code|byte_in|C}}
*** NOP for the subslave's hold time
*** Pull SCLK low
** {{Code|byte_in|C}}now contains that recently-received byte and can be used as desired
* Pull {{Overline|CSSS}} high to unselect the subslave
Bit-banging a subslave's protocol is similar but different from above. An implementation might involve [[busy waiting]] for {{Overline|CSSS}} to fall or triggering an [[Interrupt handler|interrupt routine]] when {{Overline|CSSS}} falls, and then shifting in and out bits when the received SCLK changes appropriately for however long the transfer size is.
 
== Bus topologies ==
Though the previous operation section focused on a basic interface with a single subslave, SPI can instead communicate with multiple subsslaves using multidrop, daisy chain, or expander configurations.
 
===Multidrop configuration===
[[File:SPI main sub multidropSPI_three_slaves.svg|thumb|216x216px|Multidrop SPI bus]]
In the [[multidrop bus]] configuration, each subslave has its own {{Overline|CSSS}}, and the mainmaster 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 subsslaves 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 subslave is not selected. SubSlave devices not supporting tri-state may be used in multidrop configuration by adding a tri-state buffer chip controlled by its {{Overline|CSSS}} signal.<ref name="Better SPI Bus Design in 3 Steps">[https://www.pjrc.com/better-spi-bus-design-in-3-steps/ Better SPI Bus Design in 3 Steps]</ref> (Since only a single signal line needs to be tristated per subslave, one typical standard logic chip that contains four tristate buffers with independent gate inputs can be used to interface up to four subslave devices to an SPI bus)<blockquote>Caveat: All {{Overline|CSSS}} signals should start high (to indicate no chipsslaves are selected) before sending initialization messages to any subslave, so other uninitialized subsslaves ignore messages not addressed to them. This is a concern if the mainmaster uses [[General-purpose input/output|general-purpose input/output (GPIO) pins]] (which may default to an undefined state) for {{Overline|CSSS}} and if the mainmaster uses separate software libraries to initialize each device. One solution is to configure all GPIOs used for {{Overline|CSSS}} to output a high voltage for ''all'' subsslaves ''before'' running initialization code from any of those software libraries. Another solution is to add a [[pull-up resistor]] on each {{Overline|CSSS}}, to ensure that all {{Overline|CSSS}} signals are initially high.<ref name="Better SPI Bus Design in 3 Steps" /></blockquote>
 
===Daisy chain configuration===
[[File:SPI main sub daisychainSPI_three_slaves_daisy_chained.svg|thumb|229x229px|Daisy-chained SPI]]
Some products that implement SPI may be connected in a [[Daisy chain (electrical engineering)|daisy chain]] configuration, where the first subslave's output is connected to the second subslave's input, and so on with subsequent subsslaves, until the final subslave, whose output is connected back to the mainmaster's input. This effectively merges the individual communication shift registers of each subslave to form a single larger combined [[shift register]] that shifts data through the chain. This configuration only requires a single {{Overline|CSSS}} line from the mainmaster, rather than a separate {{Overline|CSSS}} line for each subslave.<ref>[https://www.maximintegrated.com/en/app-notes/index.mvp/id/3947 Maxim-IC application note 3947: "Daisy-Chaining SPI Devices"]</ref>
 
In addition to using SPI-specific subsslaves, daisy-chained SPI can include [[Discrete component|discrete]] shift registers for [[Shift register#More I/O pins|more pins]] of inputs (e.g. using the [[Shift register#Parallel-in serial-out (PISO)|parallel-in serial-out]] [[List of 7400-series integrated circuits|74]]<nowiki/>xx165)<ref name=":3">{{Cite web |last=Gammon |first=Nick |date=2013-03-23 |title=Gammon Forum : Electronics : Microprocessors : Using a 74HC165 input shift register |url=https://www.gammon.com.au/forum/?id=11979 |url-status=live |archive-url=https://web.archive.org/web/20230729042912/http://www.gammon.com.au/forum/?id=11979 |archive-date=2023-07-29 |access-date=2023-08-03 |website=Gammon Forum}}</ref> or outputs (e.g. using the [[Shift register#Serial-in parallel-out (SIPO)|serial-in parallel-out]] [[List of 7400-series integrated circuits|74]]<nowiki/>xx595)<ref name=":2">{{Cite web |last=Gammon |first=Nick |date=2012-01-31 |title=Gammon Forum : Electronics : Microprocessors : Using a 74HC595 output shift register as a port-expander |url=https://www.gammon.com.au/forum/?id=11518 |url-status=live |archive-url=https://web.archive.org/web/20230714101259/http://www.gammon.com.au/forum/?id=11518 |archive-date=2023-07-14 |access-date=2023-08-03 |website=Gammon Forum}}</ref> chained indefinitely. Other applications that can potentially interoperate with daisy-chained SPI include [[SGPIO]], [[JTAG]],<ref>{{citation |title= Interfaces |year = 1977|url= https://books.google.com/books?id=8od7phxJHGkC |pages= 80, 84}}</ref> and [[I2C|I<sup>2</sup>C]].
 
===Expander configurations===
Expander configurations use SPI-controlled addressing units (e.g. [[Binary decoder|binary decoders]], [[Demultiplexer|demultiplexers]], or shift registers) to add chip selects.
 
For example, one {{Overline|CSSS}} can be used for transmitting to a SPI-controlled demultiplexer an index number controlling its select signals, while another {{Overline|CSSS}} is routed through that demultiplexer according to that index to select the desired subslave.<ref>{{cite web |date=2001-07-01 |title=Serial-Control Multiplexer Expands SPI Chip Selects |url=http://www.farnell.com/datasheets/312519.pdf |archive-url=https://web.archive.org/web/20190819062018/http://www.farnell.com/datasheets/312519.pdf |archive-date=2019-08-19 |access-date= |website=[[Premier Farnell]]}}</ref>
 
==Pros and cons==
Line 190 ⟶ 191:
** Arbitrary choice of message size, content, and purpose
* Simple hardware and interfacing
** Hardware implementation for subsslaves only requires a selectable shift register
*** SubsSlaves use the mainmaster's clock and hence do not need precision oscillators
*** SubsSlaves do not need a unique [[address space|address]]{{snd}} unlike [[I²C]] or [[GPIB]] or [[SCSI]]
*** MainsMasters only additionally require generation of clock and {{Overline|CSSS}} 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 communication|parallel interfaces]]
*** At most one unique signal per device ({{Overline|CSSS}}); all others are shared
**** Note: theThe daisy-chain configuration doesn'tdoes not need more than one shared {{Overline|CSSS}}
** Typically lower power requirements than [[I²C]] or SMBus due to less circuitry (including pull up resistors)
** Single mainmaster 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]]
Line 206 ⟶ 207:
* Requires more pins on IC packages than [[I²C]], even in [[Serial Peripheral Interface#Three-wire|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 subsslaves using different SPI Modes are required
** Access is slowed down when mainmaster 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 (data)|flow control]] by the subslave (but the mainmaster can delay the next clock edge to slow the transfer rate)
** No hardware subslave acknowledgment (the mainmaster could be transmitting to nowhere and not know it)
** No error-checking protocol
** No [[hot swapping]] (dynamically adding nodes)
Line 233 ⟶ 234:
* Control devices: [[audio codec]]s, [[digital potentiometers]], [[digital-to-analog converter|DACs]]
* Camera lenses: [[Canon EF lens mount]]
* Communications: [[Ethernet]], [[USB]], [[USART]], [[CAN bus|CAN]], [[IEEE 802.15.4]], [[IEEE 802.11]]
* Memory: [[flash memory#Serial flash|flash]] and [[EEPROM#Serial bus devices|EEPROMs]]
* [[Real-time clock|Real-time clocks]]
* [[LCD|LCDs]], sometimes even for managing image data
* Any [[MultiMediaCard|MMC]] or [[Secure Digital|SD]] card (including [[Secure Digital#SDIO|SDIO]] variant{{NoteTag|Not to be confused with the SDIO (Serial Data I/O) line of the half-duplex implementation of SPI sometimes also called "3-wire" SPI. Here e.g. MOSI (via a resistor) and MISO (no resistor) of a mainmaster is connected to the SDIO line of a subslave.|name=3wireSDI}})
* [[Shift registers]] for additional I/O<ref name=":3" /><ref name=":2" />
[[Printed circuit board|Board]] real estate and wiring savings compared to a [[Parallel communication|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 architecture|ARM]], [[MIPS architecture|MIPS]], or [[PowerPC]] and with lower-end microcontrollers such as the [[Atmel AVR|AVR]], [[PIC microcontroller|PIC]], and [[MSP430]]. These chips usually include SPI controllers capable of running in either mainmaster or subslave mode. [[In-system programming|In-system programmable]] AVR controllers (including blank ones) can be programmed using SPI.<ref>{{cite web |url=http://www.atmel.com/dyn/resources/prod_documents/DOC0943.PDF |title=AVR910 - In-system programming |archive-url=https://web.archive.org/web/20110302123348/http://www.atmel.com/dyn/resources/prod_documents/DOC0943.PDF |archive-date=2011-03-02}}</ref>
 
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, [[FPGA]]s sometimes use SPI to interface as a subslave to a host, as a mainmaster 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 mainmaster/single subslave 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 [[channel (communications)|telecommunications channels]], but most off-the-shelf chips stick to half-duplex request/response protocols.
 
==Variations==
SPI<!-- isregardless a [[de facto standard|''de facto'' standard]]. However, theof lack of astandards formal standard is-->SPI reflectedimplementations inhave a wide variety of protocol optionsvariations. Some devices are transmit-only; others are receive-only. ChipSlave 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 ===
Line 255:
 
===Timing variations===
Some devices have timing variations from Motorola's CPOL/CPHA modes. Sending data from subslave to mainmaster may use the opposite clock edge as mainmaster to subslave. 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 chipslave select line.
 
=== Transmission size ===
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 chipslave select ===
Some devices don'tdo not use chipslave select, and instead manage protocol state machine entry/exit using other methods.
 
=== Connectors ===
Line 269:
 
=== Flow control ===
Some devices require an additional [[Flow control (data)|flow control]] signal from subslave to mainmaster, 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 subslave 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 mainsmasters do not support that signal directly, and instead rely on fixed delays.)
 
=== SafeSPI ===
SafeSPI<ref>[http://SafeSPI.org SafeSPI.org]</ref> is an high industry standard for SPI in automotive applications. Its main focus is the transmission of sensor data between different devices.
 
=== High reliability modifications ===
Line 280:
A '''Queued Serial Peripheral Interface''' ('''QSPI'''; different to but has same abbreviation as ''Quad SPI'' described in {{Slink|2=Quad SPI|nopage=y}}) is a type of SPI controller that uses a [[queue (data structure)|data queue]] to transfer data across an SPI bus.<ref>{{Cite web |date=1996 |orig-date=1991 |title=Freescale Semiconductor, Inc. - QSM - Queued Serial Module - Reference Manual |url=https://www.nxp.com/docs/en/reference-manual/QSMRM.pdf |url-status=dead |archive-url=https://web.archive.org/web/20190824080750/https://www.nxp.com/docs/en/reference-manual/QSMRM.pdf |archive-date=2019-08-24 |website=[[NXP]]}}</ref> It has a [[circular buffer|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 [[virtual memory|memory-mapped]] parallel devices. This feature is useful in applications such as control of an [[analog-to-digital converter|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''').{{NoteTag|Such as with the MultiChannel Serial Port Interface, or McSPI, used in Texas Instruments OMAP chips. (https://www.ti.com/product/OMAP3530)}} Most SPI mainmaster controllers integrate support for up to four chipslave selects,{{NoteTag|Such as the SPI controller on Atmel AT91 chips fanatec like the at91sam9G20, which is much simpler than TI's McSPI.}} although some require chipslave 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!<ref>{{Cite web |date=2023-01-11 |title=Quad-SPI Brings Fast Parallel Data Transmission |url=https://resources.pcb.cadence.com/blog/quad-spi-brings-fast-parallel-data-transmission |url-status=live |archive-url=https://web.archive.org/web/20230601194620/https://resources.pcb.cadence.com/blog/quad-spi-brings-fast-parallel-data-transmission |archive-date=2023-06-01 |access-date=2023-06-30 |website=[[Cadence Design Systems]] |language=en-US}}</ref>
Line 291:
 
=== Three-wire ===
Three-wire variants of SPI restricted to a [[half-duplex]] mode use a single bidirectional data line called SISO (subslave out/subslave in) or MOMI (mainmaster out/mainmaster 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 [[Serial Peripheral Interface#Microwire|Microwire]]. Few SPI controllers support this mode, although it can be easily [[Bit-banging|bit-banged]] in software.
 
=== Dual SPI ===
Line 298:
This is particularly popular among SPI ROMs, which have to send a large amount of data, and comes in two variants:<ref name="W25Q16JV">{{cite web |title=W25Q16JV 3V 16M-bit serial flash memory with Dual/Quad SPI |date=12 August 2016 |version=Revision D |publisher=[[Winbond]] |type=data sheet |url=https://www.winbond.com/resource-files/w25q16jv%20spi%20revd%2008122016.pdf |access-date=2017-02-10}}</ref><ref name="D25LQ64">{{cite web |title=D25LQ64 1.8V Uniform Sector Dual and Quad SPI Flash |type=data sheet |date=11 February 2011 |version=version 0.1 |publisher=GigaDevice |url=https://www.sst-ic.com/File/DataSheet/KC909742-1112151725544ed0c4ce-8225-4c46-8d18-b81422086247.pdf |archive-url=https://web.archive.org/web/20170212090900/http://www.sst-ic.com/File/DataSheet/KC909742-1112151725544ed0c4ce-8225-4c46-8d18-b81422086247.pdf |url-status=dead |archive-date=12 February 2017 |access-date=2017-02-10}}</ref>
 
* Dual read commands sends the sendcommand and address from the mainmaster in single mode, and returnreturns the data in dual mode.
* Dual I/O commands sendsends the command in single mode, then sendsends the address and return data in dual mode.
 
=== Quad SPI ===
Line 328:
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.<ref name="eSPI" />
 
This standard defines an Alert# signal that is used by an eSPI subslave to request service from the mainmaster. In a performance-oriented design or a design with only one eSPI subslave, each eSPI subslave will have its Alert# pin connected to an Alert# pin on the eSPI mainmaster that is dedicated to each subslave, allowing the eSPI mainmaster to grant low-latency service, because the eSPI mainmaster will know which eSPI subslave needs service and will not need to poll all of the subsslaves to determine which device needs service. In a budget design with more than one eSPI subslave, all of the Alert# pins of the subsslaves are connected to one Alert# pin on the eSPI mainmaster in a [[wired-OR]] connection, which requires the mainmaster to poll all the subsslaves 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 subsslaves needing service and therefore pulling the Alert# signal low.<ref name="eSPI" />
 
This standard allows designers to use 1-bit, 2-bit, or 4-bit communications at speeds from 20 to 66&nbsp;MHz to further allow designers to trade off performance and cost.<ref name="eSPI" />
 
All communicationsCommunications that were out-of-band of LPC like [[general-purpose input/output]] (GPIO) and [[System Management Bus]] (SMBus) areshould 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.<ref name="eSPI" />
 
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 subsslaves 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.<ref name="eSPI" />
 
eSPI subsslaves are allowed to use the eSPI mainmaster as a proxy to perform flash operations on a standard SPI flash memory subslave on behalf of the requesting eSPI subslave.<ref name="eSPI" />
 
64-bit memory addressing is also added, but is only permitted when there is no equivalent 32-bit address.<ref name="eSPI" />
 
The Intel [[Z170|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&nbsp;MHz instead of the standard 33&nbsp;MHz.<ref>{{Cite web | url = https://www.intel.com/content/dam/www/public/us/en/documents/datasheets/100-series-chipset-datasheet-vol-1.pdf | title = Intel® 100 Series Chipset Family PCH Datasheet, Vol. 1 | access-date = April 15, 2015}}</ref>
 
The eSPI bus is also adopted by [[AMD Ryzen]] chipsets.
 
==Development tools==
Line 348 ⟶ 350:
 
=== USB to SPI adapters ===
There are a number of [[USB]] adapters that allow a desktop [[Personal computer|PC]] or [[smartphone]] with [[USB]] to communicate with SPI chips (e.g. CH341A/B<ref>{{cite web |title=USB Bridge Controller CH341 with UART, SPI and I2C | url=https://wch-ic.com/products/CH341.html |access-date=27 February 2025 |website=WCH}}</ref> based or [[FTDI|FT]]221xs<ref>{{cite web |title=USB to SPI converter |url=https://ftdichip.com/products/ft221xs/ |access-date=14 February 2021 |website=FTDI|date=2 August 2020 }}</ref>). They are used for embedded systems, chips ([[FPGA]], [[Application-specific integrated circuit|ASIC]], and [[System on a chip|SoC]]) and peripheral testing, programming and debugging. Many of them also provide scripting or programming capabilities (e.g. [[Visual Basic]], [[C (programming language)|C]]/[[C++]], [[VHDL]]) and can be used with open source programs like [[Flashrom_(utility)|flashrom]], IMSProg, SNANDer or avrdude for [[Flash_memory|flash]], [[EEPROM]], [[Bootloader|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&nbsp;MHz serial interfaces, with virtually unlimited access length.
Line 362 ⟶ 364:
 
==Alternative terminology==
Various alternative abbreviations for the four common SPI signals are used. (This section omits overbars indicating active-low.)
The term "master" is commonly used to identify the main device and "slave" for peripheral (sub) devices. These terms reflect how the main device is responsible for driving the serial clock and initiating communication: peripheral devices are only able to communicate when the main device is driving the clock.
 
* Serial clock
Various more contemporary alternative names for each of the four signals have been proposed:
* SCK : Serial Clock. Alternatives:
** SCK, SCLK, CLK, SCL
* MOSI : "Master" Out → "Slave" In. Now can be read as "Main" Out "Sub" In, or can use these alternatives:(MOSI)
** SIMO, MTSR, SPID - correspond to MOSI on both mainmaster and subslave devices, connects to each other
** SDI, DI, DIN, SI, SDA - on sub-onlyslave devices; Variousvarious abbreviations for "Serial"''serial "Data"data "In".in''; Connectsconnects to MOSI (or alternative names) on mainmaster
** SDO, DO, DOUT, SO - on main-onlymaster devices; Variousvarious abbreviations for "Serial"''serial "Data"data "Out".out''; connects to MOSI (or alternative names) on subslave
** COPI, PICO for "''peripheral'' and ''controller"'',<ref name="OSHWA">[https://www.oshwa.org/a-resolution-to-redefine-spi-signal-names/ SPI; OSHWA.]</ref><ref name=":5">{{Cite web| title=Product Overview - Translate Voltages for SPI | url=https://www.ti.com/lit/an/scea091a/scea091a.pdf | archive-url=https://web.archive.org/web/20220317120519/https://www.ti.com/lit/an/scea091a/scea091a.pdf | archive-date=2022-03-17}}</ref> or COTI for "''controller"'' and "''target"''<ref name=":1">{{Cite web |title=Serial Peripheral Interface (SPI) Devices |url=https://www.nxp.com/products/interfaces/ic-spi-i3c-interface-devices/www.nxp.com/pages/:SPI |url-status=live |archive-url=https://web.archive.org/web/20230601020101/https://www.nxp.com/products/interfaces/ic-spi-i3c-interface-devices/spi-interface-devices:SPI |archive-date=2023-06-01 |access-date=2023-07-22 |website=[[NXP]]}}</ref>
* MISO : "Master" In ← "Slave" Out. Now can be read as "Main" In "Sub" Out, or can use these alternatives:(MISO)
** SOMI, MRST, SPIQ - correspond to MISO on both mainmaster and subslave devices, connects to each other
** SDO, DO, DOUT, SO - on sub-onlyslave devices; connects to MISO (or alternative names) on mainmaster
** SDI, DI, DIN, SI - on main-onlymaster devices; connects to MISO (or alternative names) on subslave
** CIPO, POCI,<ref name="OSHWA" /><ref name=":5" /> or CITO<ref name=":1" />
* Slave Select (SS)
* {{Overline|SS}} : "Slave" Select (same functionality as [[chip select|{{Overline|Chip Select}}]]). Alternatives:
** Chip select (CS)
** SS, {{Overline|SS}}, SSEL, NSS, /SS, SS# (sub select)
** CS, {{Overline|CS}} (chip select)
** CE (chip enable)
** SS, {{Overline|SS}},Historical: SSEL, NSS, /SS, SS# (sub select)
[[Microchip Technology|Microchip]] uses "Host" and "Client" though keeps the abbreviation MOSI and MISO.<ref>{{Cite web |last=Stoicescu |first=Alin |title=Getting Started with Serial Peripheral Interface (SPI) |url=https://onlinedocs.microchip.com/pr/GUID-EF58F3A9-B49B-4C31-A7EC-B71EBB831870-en-US-5/index.html |url-status=live |archive-url=https://web.archive.org/web/20231221205244/https://onlinedocs.microchip.com/pr/GUID-EF58F3A9-B49B-4C31-A7EC-B71EBB831870-en-US-5/index.html |archive-date=2023-12-21 |access-date=2023-12-21 |website=[[Microchip Technology]]}}</ref>
 
[[Microchip Technology|Microchip]] uses "Host"''host'' and "Client"''client'' though keeps the abbreviation MOSI and MISO.<ref>{{Cite web |last=Stoicescu |first=Alin |title=Getting Started with Serial Peripheral Interface (SPI) |url=https://onlinedocs.microchip.com/pr/GUID-EF58F3A9-B49B-4C31-A7EC-B71EBB831870-en-US-5/index.html |url-status=live |archive-url=https://web.archive.org/web/20231221205244/https://onlinedocs.microchip.com/pr/GUID-EF58F3A9-B49B-4C31-A7EC-B71EBB831870-en-US-5/index.html |archive-date=2023-12-21 |access-date=2023-12-21 |website=[[Microchip Technology]]}}</ref>
 
==See also==