Location>code7788 >text

STM32F103 SPI Detailed Explanation and Sample Code

Popularity:734 ℃/2024-07-28 16:35:34

1 SPI Protocol Explained

SPI is Serial Peripheral Interface (Serial Peripheral Interface) abbreviation, is the United States Motorola (Motorola) first introduced a synchronous serial transmission specification, but also a single chip peripheral chip serial expansion interface, is a high-speed, full-duplex, synchronous communication bus, so you can send and receive data at the same time. SPI has no defined speed limit, usually can reach or even exceed 10M/bps. SPI has two modes, master and slave, usually consists of a master module and one or more slave modules (SPI does not support multiple hosts), the master module selects a slave module for synchronous communication, so as to complete the exchange of data. The device that provides the clock is the master device (Master), and the device that receives the clock is the slave device (Slave). The read and write operations of the SPI interface are initiated by the master device, and when there are more than one slave device, they are managed through their respective chip select signals.

The SPI communication principle is very simple and requires at least 4 wires, 3 wires for unidirectional transmission, which are MISO (Master Device Data Input), MOSI (Master Device Data Output), SCLK (Clock) and CS/SS (Chip Select):

MISO(Master Input Slave Output): Master device data input, slave device data output;

MOSI(Master Output Slave Input): Master device data output, slave device data input;

SCLK(Serial Clock): Clock signal, generated by the master device;

CS/SS(Chip Select/Slave Select): Slave device enable signal, controlled by the master device, a master multi-slave, CS/SS is the control signal from the chip is selected by the master chip, only the chip selection signal for the pre-specified enable signal (high or low potential), the master chip operation of this slave chip is effective.

 

Figure 1 Multi-master and multi-slave

1.1 Principles of communication

Both the SPI master and slave devices have a serial shift register, and the master initiates a transfer by writing a byte to its SPI serial register.

 

Figure 2 Data Shift Exchange

The flow of SPI data communication can be divided into the following steps:

1. The master device initiates a signal to pull CS/SS low and initiate communication.

2, the master device by sending a clock signal to tell the slave device to write data or read data operation (the timing of the acquisition may be the rising edge of the clock signal (from low to high) or falling edge (from high to low), because the SPI has four modes, which will be discussed later), it will immediately read the signal on the data line, so that we get a bit of data (1bit).

3, the host (Master) will send the data written to the send data cache (Memory), the cache area through the shift register (cache length is not necessarily, depending on the configuration of the microcontroller), the serial shift register through the MOSI signal line will be shifted byte by byte out of the transmission to the slave, while the MISO interface to receive the data through the shift register one by one shifted to the receive cache area. The data received by the MISO interface is moved one by one to the receive buffer through the shift register.

4. The Slave also returns the contents of its own serial shift register (cache length is not certain, depending on the microcontroller configuration) to the host via the MISO signal line. At the same time, it receives the data sent by the host through the MOSI signal line, so that the contents of the two shift registers are exchanged.

indeedSPI has only master and slave modes, there is no such thing as read and writeThe write and read operations of the peripheral are done synchronously. If only a write operation is performed, the host simply ignores the received byte (virtual data/dummy data); conversely, if the host wants to read a byte from the slave, it must send a null byte to trigger a transmission from the slave. In other words, if you send a piece of data, you must receive a piece of data; if you want to receive a piece of data, you must also send a piece of data first.

1.2 Communication characteristics

1.2.1 Equipment selection

SPI is a single master (Single Master) communication protocol, only one master device can initiate communication, when the SPI master device wants to read/write the slave device, it first pulls down the corresponding SS line of the slave device (SS is active low). Then it starts to send work pulses to the clock line, at the corresponding pulse time, the master device sends the signal to MOSI to realize "write", and at the same time, it can realize "read" by sampling MISO. As shown in the figure below:

Figure 3 Logic analyzer data capture example

Low level selection is just the standard mode, or you can select high level validity, i.e., CLK is low at IDLE, and the Master pulls the CLK signal high when it wants to select Slave. It should be noted that either way, Master and Slave need to be configured the same for the selection mode.

1.2.2 Device Clock

SPI clock characteristics include three main aspects: clock rate, clock polarity and clock phase.

clock rate

The master device on the SPI bus must be configured and generated with the appropriate clock signal at the start of communication. Theoretically, the clock rate can be any rate you want as long as it is practicable, but of course this rate is limited by how much system clock frequency each system can provide, and the maximum SPI transfer rate.

clock polarity

Depending on the hardware manufacturer's naming convention, clock polarity is usually written as CKP or CPOL. clock polarity and phase together determine how data is read, such as whether data is read on the rising edge of a signal or on the falling edge of a signal.

CKP can be configured as 1 or 0, which means that the default state of the clock (IDLE) can be set as high or low as desired. Polarity reversal can be achieved with a simple logic inverter. The device's datasheet must be referred to in order to set CKP and CKE correctly.

CKP = 0: clock idle IDLE is low 0;

CKP = 1: clock idle IDLE is high 1.

phase of the clock

Depending on the hardware manufacturer, the clock phase is usually written as CKE or CPHA. as the name implies, the clock phase/edge, which means that the data is acquired at a specific phase or edge of the clock signal;

CKE = 0: Sampling at the first jump edge of the clock signal SCK;

CKE = 1: Sampled at the second jump edge of the clock signal SCK.

1.2.3 Four models

There are four different SPI communication operation modes that can be set according to the SPI clock polarity and clock phase characteristics. The difference between them is that they define which edge of the clock pulse converts (toggles) the output signals, which edge samples the input signals, and the stabilized level value (that is, whether it is high or low when the clock signal is invalidated) of the clock pulse, as shown in the details below:

Mode0CKP=0CKE=0: When idle state, SCK is at low level, data sampling is at the 1st edge, that is, SCK jumps from low level to high level, so data sampling is at the rising edge (prepare data), (send data) data sending is at the falling edge.

Mode1CKP=0CKE=1: When idle state, SCK is at low level, data sending is at the 2nd edge, that is, SCK jumps from low level to high level, so data sampling is at the falling edge and data sending is at the rising edge.

Mode2CKP=1CKE=0: When in idle state, SCK is at high level, data acquisition is at the 1st edge, that is, SCK jumps from high to low level, so data acquisition is at the falling edge and data sending is at the rising edge.

Mode3:CKP=1,CKE=1: When idle state, SCK is at high level, data sending is at the 2nd edge, that is, SCK jumps from high level to low level, so data acquisition is at the rising edge and data sending is at the falling edge.

Figure 4 Four models

The black line in the figure shows the moment of sampling data, and the blue line is the SCK clock signal.

As an example, the following figure shows the SPI Mode0 read/write timing, you can see that the SCK idle state is low, the host output data is sampled by the slave at the first jump edge, and the host input data is the same.

Figure 5 Example of Mode0 data sampling

Figure 5 shows the SPI Mode3 read/write timing, SCK idle state is high, host output data is sampled by the slave at the second jump edge (corresponding to the green arrow in the figure), and the same for host input data.

1.2.4 Advantages and disadvantages

vantage

There are no start and stop bits, so data bits can be transmitted continuously without interruption;

There is no complex slave device addressing system like I2C;

The data transfer rate is higher than I2C (almost twice as fast);

Separate MISO and MOSI signal lines so that data can be sent and received simultaneously;

Extremely flexible data transfer, not limited to 8 bits, it can be any size word;

Very simple hardware architecture. Slaves do not need a unique address (unlike I2C). Slaves use host clock, no precision clock oscillator/crystal needed (unlike UART). No transceiver required (unlike CAN).

drawbacks

Four signal wires are used (two signal wires are used for I2C and UART);

It is not possible to confirm whether the data has been successfully received (I2C has this function);

There is no error checking of any kind, such as the parity bit in the UART;

Only one master device is allowed;

There is no hardware slave answer signal (the host may send it nowhere without knowing it);

No hardware level error checking protocol is defined;

Only very short distances can be supported compared to RS-232 and CAN bus.

2 STM32 related content

This blog is based on STM32F103ZET6 control board for all operations, other STM32F1 model control boards can be referred.

2.1 SPI Peripheral Introduction and Architecture Analysis

The STM32's SPI peripheral can be used as both a master and a slave for communication, and supports a maximum SCK clock frequency of fpclk/2 (STM32F103 model chip default fpclk1is 36 MHz, fpclk2(72MHz), fully supports 4 modes of SPI protocol, the data frame length can be set to 8-bit or 16-bit, and the data can be set to MSB-first or LSB-first. It also supports two-wire full-duplex, two-wire unidirectional and single-wire modes. The two-wire unidirectional mode can use both MOSI and MISO data lines to transmit data in one direction, which can double the transmission speed. The single-wire mode reduces the number of hardware wires, but of course the speed will be affected. We will only explain the two-wire full-duplex mode.

Figure 6 SPI Architecture

2.1.1 Communication pins

All the hardware architecture of SPI unfolds from the MOSI, MISO, SCK, and NSS lines on the left side of the SPI architecture diagram in Figure 6.The STM32 chip has several SPI peripherals, and their SPI communication signals are pinned out to different GPIO pins, and they must be configured to these specified pins when in use, as shown in Table SPI Pins of STM32F10x. For the multiplexing function of the GPIO pins, consult the STM32F10x datasheet and use it as a reference.

Figure 7 SPI Pins

SPI1 is the device on APB2, the maximum communication rate of 36Mbtis/s, SPI2, SPI3 is the device on APB1, the maximum communication rate of 18Mbits/s. In addition to the communication rate, there is no difference in other functions. SPI3 used to download the interface pins, the default function of these pins is to download, the second function is the IO port, if you want to use the SPI3 interface, then the program must first disable the download function of these IO ports. Generally in the case of resources are not very tight, these IO ports are used exclusively for downloading and debugging programs, will not be reused for SPI3.

2.1.2 Clock control logic

The clock signal of the SCK line is controlled by the baud rate generator according to the BR[0:2] bits in the "Control Register CR1", which is the control of the fpclkThe crossover factor of the clock, for fpclkThe result of the frequency division of the SCK pin is the output clock frequency of the SCK pin, which is calculated as shown in the table BR bit to fpclkThe crossover frequency.

Figure 8 Crossover Configuration

where fpclkThe frequency is the frequency of the APB bus where the SPI is located, and APB1 is fpclk1, APB2 is fpckl2

By configuring the "CPOL bit" and "CPHA bit" of the "Control Register CR", the SPI can be set to the four SPI modes analyzed earlier.

2.1.3 Data control logic

SPI MOSI and MISO are connected to the data shift register, the data source and target of the data shift register receive, send buffer and MISO, MOSI line. When sending data to the outside, the data shift register takes the "transmit buffer" as the data source and sends the data one by one through the data line; when receiving data from the outside, the data shift register stores the data sampled by the data line one by one into the "receive buffer". When receiving data from outside, the data shift register stores the data sampled by the data line one by one into the "receive buffer". The data is filled into the transmit buffer by writing the "Data Register DR" of SPI, and the contents of the receive buffer can be obtained by reading the "Data Register DR". The data frame length can be configured to 8-bit or 16-bit mode by "DFF bit" of "Control Register CR1"; "LSBFIRST bit" can be configured to select between Configuring the "LSBFIRST bit" can select whether the MSB or LSB is first.

2.1.4 Overall control logic

The overall control logic is responsible for coordinating the whole SPI peripheral, and the working mode of the control logic is changed according to the parameters of the "Control Register (CR1/CR2)" configured by us, and the basic control parameters include the SPI mode, baud rate, LSB first, master-slave mode, unidirectional and bidirectional modes and so on, as mentioned before. When the peripheral is working, the control logic will modify the "Status Register (SR)" according to the working status of the peripheral, and we only need to read the relevant register bits of the Status Register to understand the working status of the SPI. In addition, the control logic is also responsible for generating SPI interrupt signals, DMA requests, and controlling the NSS signal lines as required.
In practice, instead of using the standard NSS signal line of the STM32 SPI peripheral, we generally use more simply an ordinary GPIO, with software controlling its level output to generate communication start and stop signals.

2.2 Communication process

When STM32 uses SPI peripheral communication, it will write parameters to different data bits of "Status Register SR" at different stages of communication, and we can read these register flags to understand the communication status. Figure 9: Master Transmitter Communication Process The process in this figure is the "Master Mode" process, i.e., the process of sending and receiving data when the STM32 is the host side of SPI communication.

Figure 9 Main mode send/receive flow

The main mode send/receive process and events are described below:

(1) Control the NSS signal line to generate the start signal (not shown in the figure);
(2) Write the data to be sent to the "data register DR", and the data will be stored in the send buffer;
(3) When communication starts, the SCK clock starts running, MOSI transmits the data in the transmit buffer one by one, and MISO stores the data into the receive buffer one by one;
(4) When a frame of data is transmitted, the "TXE flag bit" in the "Status Register SR" is set to 1, indicating that a frame has been transmitted and the transmit buffer is empty; similarly, when a frame of data is received, the "RXNE flag bit" is set to 1, indicating that a frame has been transmitted and the receive buffer is not empty. Similarly, when a frame of data is received, the "RXNE flag bit" is set to 1 to indicate that a frame has been transmitted and the receive buffer is not empty;
(5) Wait until the "TXE flag bit" is 1, and if you want to continue to send data, write data to the "data register DR" again; wait until the "RXNE flag bit" is 1, and then read the "data register DR" to get the contents of the receive buffer. When the "RXNE flag bit" is 1, the contents of the receive buffer can be obtained by reading the "data register DR".
If we enable TXE or RXNE interrupt, when TXE or RXNE is set to 1, it will generate SPI interrupt signal, and enter the same interrupt service function, and then when we get to the SPI interrupt service program, we can check the register bits to know which event it is, and then deal with it separately. DMA can also be used to send and receive data in the "data register DR".

2.3 SPI Initialization Structure Details

Like other peripherals, the STM32 standard library provides SPI initialization structures and initialization functions to configure SPI peripherals. The initialization structures and functions are defined in the library files "stm32f10x_spi.h" and "stm32f10x_spi.c", which can be used in conjunction with the comments in these two files or by referring to the library help file. After understanding the initialization structure, we can use the SPI peripheral freely, see code list: SPI-1.

 1 typedef struct
 2 {
 3     uint16_t SPI_Direction;           /*Setting the Uni-Bi-Directional Mode of SPI*/
 4     uint16_t SPI_Mode;                /*Setting the Master/Slave Side Mode of SPI*/
 5     uint16_t SPI_DataSize;            /*Set SPI data frame length, selectable 8/16 bits*/
 6     uint16_t SPI_CPOL;                /*Set clock polarity CPOL, selectable high/low level*/
 7     uint16_t SPI_CPHA;                /*Set clock phase, selectable odd/even edge sampling*/
 8     uint16_t SPI_NSS;                 /*Set whether the NSS pin is controlled by the SPI hardware or by software*/
 9     uint16_t SPI_BaudRatePrescaler;   /*Set clock division factor, fpclk/division number = fSCK*/
10     uint16_t SPI_FirstBit;            /*Setting the MSB/LSB first*/
11     uint16_t SPI_CRCPolynomial;       /*Setting the CRC checksum expression*/
12 } SPI_InitTypeDef;

The members of these structures are described below, where the text in parentheses is the macro defined in the STM32 standard library for the corresponding parameter:

  1. SPI_Direction

This member sets the communication direction of SPI, which can be set to two-lines full duplex (SPI_Direction_2Lines_FullDuplex), two-lines receive-only (SPI_Direction_2Lines_RxOnly), single-lines receive-only (SPI_Direction_1Line_Rx), and single-lines transmit-only mode ( SPI_Direction_1Line_Tx).

  1. SPI_Mode

This member sets the SPI to operate in Master mode (SPI_Mode_Master) or Slave mode (SPI_Mode_Slave ). The major difference between these two modes is the timing of the SCK signal line of the SPI, which is generated by the host in communication. If configured for slave mode, the STM32's SPI peripheral will accept external SCK signals.

  1. SPI_DataSize

This member can select whether the data frame size for SPI communication is 8 bits (SPI_DataSize_8b) or 16 bits (SPI_DataSize_16b).

  1. SPI_CPOL and SPI_CPHA

These two members configure the SPI clock polarity, CPOL, and clock phase, CPHA, which affect the communication mode of the SPI. For the description of CPOL and CPHA, refer to the previous section "Communication Mode".

Clock polarity CPOL member that can be set high (SPI_CPOL_High) or low (SPI_CPOL_Low ).

The clock phase CPHA can be set to SPI_CPHA_1Edge (to capture data on odd edges of SCK) or SPI_CPHA_2Edge (to capture data on even edges of SCK).

  1. SPI_NSS

This member configures the usage mode of the NSS pin, which can be selected as hardware mode (SPI_NSS_Hard ) and software mode (SPI_NSS_Soft ). The SPI chip select signal in the hardware mode is automatically generated by the SPI hardware, whereas in the software mode we need to pull up or set down the corresponding GPIO ports in order to generate the non-chip and chip select signals in person. In practice, the software mode is used more often.

  1. SPI_BaudRatePrescaler

This member sets the baud rate dividing factor, and the clock after dividing is the clock frequency of the SCK signal line of SPI. This member parameter can be set to 2, 4, 6, 8, 16, 32, 64, 128, 256 divisions of fpclk.

  1. SPI_FirstBit

All serial communication protocols have the question of MSB first (high data first) or LSB first (low data first), and the SPI module of the STM32 can be programmed to control this feature through this structure member.

  1. SPI_CRCPolynomial

This is the polynomial in SPI's CRC checksum, and if we use the CRC checksum, we use the parameter (polynomial) of this member to compute the CRC value.

After configuring these structure members, we have to call SPI_Init function to write these parameters into the registers to realize the initialization of SPI, and then call SPI_Cmd to enable the SPI peripheral.

Quoted above:/mcu/stm32/f103badao/std/zh/latest/book/

2.4 NSS Slice Selection Details

2.4.1 Output modes

For each SPI the NSS can be input or output. The so-called input is the level signal of the NSS to itself, the so-called output is the level signal of the NSS is sent out to the slave. the NSS can only be used as a host when it is configured as an output, and we can configure the SSOE bit of the SPI_CR2 register to be 1. When the SSOE is 1 to enable the SPI, the NSS outputs a low level, which means it pulls down, so when other SPI devices with the NSS pin is connected to it, it must receive a low level, then the chip selection is successful, and all become slave devices. The corresponding registers are defined as follows

Figure 10 SSOE

However, a combination of practice and online claims suggest that there are bugs in this model, ie:

Host NSS without pull-up resistor case
After enabling the SPI peripheral, the host's NSS is continuously pulled low and does not go high, even if the SPI peripheral is turned off, it has no effect.
Host NSS plus pull-up resistor case
The host's NSS is pulled low when the SPI peripheral is enabled and pulled high when the SPI peripheral is disabled.

2.4.2 Input modes

NSS inputs are subdivided into two modes: hardware inputs and software-controlled inputs.

software model

1 For SPI hosts
The SPI_CR1 register needs to be set to 1 for SSM and 1 for the SSI bit. SSM is 1 to enable software slave management. the NSS has both internal and external pins, at this point, the external pin is left in place (it can be used as a chip-select signal for the GPIO to drive the slave device). The internal NSS pin level is driven by the SSI bit in the SPI_CR1 register, and a 1 in the SSI bit enables the NSS internal level to go high. the STM32 manual says to keep the MSTR and SPE bits 1, that is to say, to keep the host mode, these two bits can be kept set to 1 only if the NSS receives a high signal. that is to say, for the SPI of the STM32, to maintain the That is to say, for STM32 SPI, in order to maintain the host state, the internal input NSS level must be high. Of course, this is also true in hardware mode.

Figure 11 Related Pin Relationship Diagram

#define SPI_Mode_Master                 ((uint16_t)0x0104)
Host mode sets MSTR and SSI to 1. SSM is also 1 in software mode, and the external pins are fully released for other uses.

2 For SPI slaves

If the slave selects one of the STM32's SPIs, e.g. SPI1 for the host and SPI2 for the slave, the NSS pin must be connected to a low signal before the byte transfer is completed, according to the manual. In software mode, you need to set the SSM of the SPI_CR1 register to 1 (Software Slave Management Enable) and the SSI bit to 0, i.e., the SPI2 chip select is low, then the chip select is successful.
If the slave for a different SPI chip, then, we can have two ways: one way, is to connect the chip's CS to GND, the other way is to use a GPIO port to output a low level to control the success of the CS chip selection. This GPIO can be any GPIO port, of course, we mentioned above when the SPI host is configured for software mode, the external NSS pin is reserved for other uses, it is a GPIO, we can also use it. At this time, we can set its push-pull output to low, and then use the line to connect to the slave's CS, then you can chip select the slave chip.

hardware mode

For the host, our NSS can be directly connected to high level, for the slave, NSS connected to low is fine. Of course we mentioned above that when a host's SSOE is 1, the host is working in output mode and the NSS is pulled low, and we want the slave to chip select, just connect CS to the host's NSS, and CS is automatically pulled low.

3 Presentation of examples

3.1 Slaves

Here to use Taobao to buy the USB to SPI tool for testing, in order to avoid advertising suspicion such as the need for the tool please search on Taobao.

Slave Code

3.2 Master-slave intercommunications

Here SPI1 is selected as the master and SPI2 as the slave.

 

In addition, when testing on my side, it is more stable to set the configuration of the NSS Pin pin in the slave section to push-pull output, not sure of the principle at the moment.

 master-slave code

3.3 flash read/write

There are more examples of this example on the web, so I won't upload them separately!