Connecting 2 STM32 boards via SPI

This tutorial shows how to connect two STM32 boards using the SPI interface and exchange data between them.

We will connect 2 STM32F4Discovery boards and use the STM32Cube HAL API to configure one board as an SPI master (generating the clock) and the other as an SPI slave (relying on the clock generated by the master). We will then use a logic analyzer to look into the SPI signals and show how to avoid a common synchronization error.

Before you begin, follow our basic STM32 SPI tutorial to get ensure that the SPI on your board works and your logic analyzer can capture and display the SPI signals.

  1. First we will create the project for the SPI master board. Start Visual Studio and open the VisualGDB Embedded Project Wizard:01-newprj1
  2. Proceed with the default project type:02-bin
  3. Select the ARM toolchain and choose your device. For the STM32F4Discovery board shown in this tutorial select STM32F407VG:03-device
  4. Proceed with the default “LEDBlink (HAL)” example:04-sample
  5. Select debug settings that match your configuration. For most STM32 devices we recommend using ST-Link via OpenOCD:05-debug
  6. Start another instance of Visual Studio and create another “LEDBlink” project for the board used as the SPI slave: 05-prj2Note that in order to debug both boards at the same time, you need to have 2 separate Visual Studio instances.
  7. Locate the pins corresponding to the SPI signals in your device datasheet (see the basic SPI tutorial for details) and connect them together (MOSI, MISO, SCK and NSS on the master board should be connected to MISO, MISO, SCK and NSS on the second board). Also connect the ground on the 2 boards:2boards
  8. Replace the main source file contents in the “Mastet” project with the following:

    This code configures the SPI in the master mode and then repeatedly sends and receives 32-bit words. Then it compares the received word with the word sent in the previous cycle (the slave board is expected to echo back the received words).

  9. Replace the main source file contents for the “Slave” project with this:

    This code configures the SPI in the slave mode and simply echoes back the received 32-bit words.

  10. Set a breakpoint on the “nop” line in the “Master” project and then build and start debugging it. As the slave project is not running yet, the breakpoint should immediately trigger: 06-start2
  11. Now build and start debugging the “Slave” project:07-mismatchFinally remove the breakpoint in the “Master” project and resume it as well. Both boards should now run in a loop.
  12. Now we will use a logic analyzer to look into the SPI signals. In this tutorial we will use Analyzer2Go that can turn many popular STM32 boards into full-featured logic analyzers. Connect your logic analyzer board to the SPI signals as it is shown in the basic SPI tutorial, enable data capture on them in Analyzer2Go and set labels like MISO, MOSI and SCK for your convenience: 08-siglist
  13. Go to the Protocol Analyzers tab and add the SPI protocol analyzer to automatically decode the SPI signals:08a-spi
  14. Set a breakpoint on the “nop” line in the Master project again. After several seconds to a few minutes it will get triggered:  09-mismatch2
  15. We will now record the SPI communication prior to the problem and analyze it. Switch back to Analyzer2Go and press “Record”, then resume the “Master” project and wait until the breakpoint triggers again:10-signals
  16. Zoom into the end of the recorded data until you see individual packets:11-sparse
  17. Double-click on packet before the last one to automatically zoom in:12-goodNote how SPI always sends data in both directions. While the MOSI (Master Output/Slave Input) line is used to send a packet from master to slave, the MISO (Master Input/Slave Output) line is already echoing back the data from the previous packet. Click on the right arrow in the “SCK” signal to automatically jump to the next packet.
  18. The data transferred back in the last packet will look wrong – it will look like 2 extra zero bytes were inserted before the normal reply:13-bad
  19. We will diagnose this by using 2 more pins to track the internal state of the HAL_SPI_TransmitReceive() function. First add the following code before the main loop in the “Slave” project:

    Then add this after the “output = input” line:

  20. Finally locate all references to the Instance->DR registers in the 8-bit mode branch of HAL_SPI_TransmitReceive() and add lines toggling PA0 after each write to the DR register (that corresponds to sending a byte) and toggling the PA1 after each read of the DR register (that corresponds to reading received data):14-markers
  21. Connect the PA0 and PA1 pins to the logic analyzer and do another long recording until the problem is reproduced. Note how after each byte sent by the master, the slave gets an RX event (PA1 is toggled) and soon after the last RX event the HAL_SPI_TransmitReceive() function returns (4 fast toggles of PA0):15-events
  22. The packet before the last one looks different: although 4 RX events take place, it looks like the HAL_SPI_TransmitReceive() function never returns:16-badevents
  23. This causes the observed behavior in the last packet: the function is stuck until the master sends the first byte (as the slave did not initiate another transfer, the previous value of 00 is repeated), then it returns (missing another byte from the master) and when it’s finally called again, it is 2 bytes too late:17-badevents2
  24. You can quickly pinpoint the part of the HAL_SPI_TransmitReceive() that gets stuck by toggling the PA0 or PA1 pins in different parts of it and counting the impulses in the logic analyzer. In this example the part responsible for the hang was the SPI_CheckFlag_BSY() call waiting for the BUSY flag to turn off. Normally this check is needed to avoid deactivating the NSS signal before the actual transfer is completed, but it is meaningless in the slave mode. Hence you can fix the problem by patching the HAL_SPI_TransmitReceive() function as follows:

    18-fixRestart the Slave project and resume the Master project. Confirm that the “nop” breakpoint does not trigger anymore.

  25. You can remove the HAL_Delay() call to transfer the data at a higher rate: I19-saveIf you want to programmatically check the consistency of the captured SPI data, use the “Show output as text” checkbox and “Save all to file” button in Analyzer2Go to export the SPI data to a file.
  26. The SPI communication code shown in this tutorial has one major drawback: if the slave device starts while the master device is already running, it will not be able to detect the start of the packet properly and may receive incorrectly aligned errors (e.g. instead of [01 00 00 00] [02 00 00 00] it could receive [00 00 00 02] [00 00 00 ..]). We can fix this by creating a modified version of HAL_SPI_TransmitReceive()  that will immediately stop receiving a packet if it detects that the PA4 (NSS) pin is high: