Serial Peripheral Interface Bus (SPI) 是一种简单的全双工串行通讯总线,SPI 共需要4根线。
Pin | Direction | Function | Note |
---|---|---|---|
CLK | Master->Slave | Clock | 时钟 |
/SS (/CS) | Master->Slave | Slave Select (Chip Select) | 片选,低电平有效 |
MOSI | Master->Slave | Master output slave input | 主设备数据输出 |
MISO | Slave->Master | Master input slave output | 主设备数据输入 |
说明:
- 提供时钟的设备称为"Master" (主设备),与主设备通信的对端设备称为"Slave" (从设备)
- 一个 Master 可以连接多个 Slave,这种情况下所有 Slave 共用 CLK / MOSI / MISO,但每个 Slave 有自己独立的 SS。
- Linux 内核的 SPI 驱动好像只支持将本机作为 Master 模式。
- CLK 只有在有数据传输时才有信号(方波),空闲时固定低电平或高电平(视 SPI 模式而定)。
- SPI 协议里没有任何 "acknowledgement" 信号。
- 如果 Master 只需要发送而不需要接收数据,MISO 可以不用。
- SS 片选很多 SOC 里有专门的引脚,也可以使用 GPIO 引脚。如果 SPI 总线上只有一个 Slave,可以不用 SS。
- 理论上 SPI 协议每次可以传输任意 bits 数据(不需要是 8 bits 整数倍),但 Linux 的 SPI 驱动好像只支持以 byte 为单位传输数据。
- SPI 协议是全双工的。
- SPI 协议不规定传输字节序/比特序,一般 MSB (高位bit)先传输。
SPI Mode
SPI 默认模式 (SPI MODE 0)
CPOL = 0, CPHA = 0
- CLK 空闲时为 0 (低电平)
- 每个时钟周期,数据在时钟上升沿(rising edge)被接收方采样,下降沿(falling edge)由发送方输出。
- Output 输出的第一个 bit 必须在时钟最开始的初始上升沿之前就准备好。对于 Slave 设备,这即意味着当 Slave 检测到 SS 变低时立即输出第一个 bit 到 MISO。
说明
SPI Mode: 0-3 (2 bits)
bit1 | bit0 |
---|---|
CPOL | CPHA |
CPOL (Clock polarity)
CPOL determines the polarity of the clock. The polarities can be converted with a simple inverter.
CPOL=0 is a clock which idles at 0, and each cycle consists of a pulse of 1. That is, the leading edge is a rising edge, and the trailing edge is a falling edge.
CPOL=1 is a clock which idles at 1, and each cycle consists of a pulse of 0. That is, the leading edge is a falling edge, and the trailing edge is a rising edge.
CPHA (Clock phase)
CPHA determines the timing of the data bits relative to the clock pulses. It is not trivial to convert between the two forms.
For CPHA=0, the "out" side changes the data on the trailing edge of the preceding clock cycle, while the "in" side captures the data on (or shortly after) the leading edge of the clock cycle. The out side holds the data valid until the trailing edge of the current clock cycle. For the first cycle, the first bit must be on the MOSI line before the leading clock edge.
An alternative way of considering it is to say that a CPHA=0 cycle consists of a half cycle with the clock idle, followed by a half cycle with the clock asserted.
For CPHA=1, the "out" side changes the data on the leading edge of the current clock cycle, while the "in" side captures the data on (or shortly after) the trailing edge of the clock cycle. The out side holds the data valid until the leading edge of the following clock cycle. For the last cycle, the slave holds the MISO line valid until slave select is deasserted.
An alternative way of considering it is to say that a CPHA=1 cycle consists of a half cycle with the clock asserted, followed by a half cycle with the clock idle.
Timing
SPI Mode 0 Timing