Page 1 of 1

How use SPI1 and SPI2 same time

Posted: Tue Jun 21, 2022 6:50 am
by ynsucn
Hello everyone

F401 Blackpill board`s SPI2 and SPI1 ports how using at same time
I have a problem ;
I have SD library and SPI Sd card module data logger
and ı have CAN BUS module
conflicts occur when i run these two from the same port
How using different SPI on STM32duino

Thanks

Re: How use SPI1 and SPI2 same time

Posted: Tue Jun 21, 2022 8:54 am
by GonzoG
If libraries for those modules allow you to choose SPI interface, then define SPI2 interface and use it as SPI for set module.
https://github.com/stm32duino/wiki/wiki/API#spi

If libraries do not allow for choosing SPI, then you have 2 options:
1. modify library to use different SPI interface
2. find library that allow you to choose SPI interface.

Re: How use SPI1 and SPI2 same time

Posted: Mon Jun 27, 2022 3:34 pm
by Vassilis
As @GonzoG already said, you can modify the default SD library and change the SPI port. This is the easy way, but you need to remember this modification in case you want to restore the original settings and connect the SD card to the SPI 1 port.

Supposing that the official SD library is stored in the following folder

Code: Select all

D:\Electronics\arduino-1.8.10\libraries\SD\src\utility

Edit the Sd2Card.cpp file and add these 7 lines:

Code: Select all

#define USE_SPI_LIB
#include <Arduino.h>
#include "Sd2Card.h"
#include <SPI.h> // <---- [1]
//------------------------------------------------------------------------------
#ifndef SOFTWARE_SPI
#ifdef USE_SPI_LIB
  
  #ifndef SDCARD_SPI
    #define MOSI2 PB15 // <---- [2]
    #define MISO2 PB14 // <---- [3]
    #define SCLK2 PB13 // <---- [4]
    #define SS2   PB12 // <---- [5]
    SPIClass SPI_2 = SPIClass(MOSI2, MISO2, SCLK2, SS2); // <---- [6]
    
    #define SDCARD_SPI SPI_2  // <---- [7]
  #endif

  #include <SPI.h>
  static SPISettings settings;
#endif
Upload your sketch. The SD card is now configured to use the SPI 2 port

Of course there are better and safer ways to do this, but this is one of the easiest ways.

Re: How use SPI1 and SPI2 same time

Posted: Tue Jun 28, 2022 2:36 pm
by ynsucn
Thanks all repyly

Re: How use SPI1 and SPI2 same time

Posted: Tue Jun 28, 2022 11:54 pm
by dannyf
How use SPI1 and SPI2 same time
the answer is "yes" and "no", depending on what you mean.

obivously on a single core CPU, it cannot do two things at the same time. However, with DMA, buffers + interrupts and low enough of a transmission speed, you can run multiple peripherals (spi or otherwise) for seamless transmission, giving the perception that you are using both at the same time.

whether it is doable depends on lots of factors.