stm32spistm32f4discoveryslavenvidia-jetson

stm32 spi full-duplex slave mode


I'm working on spi communicate between stm32f0308-discovery and jetson tx2. Jetson is master and stm32 should be slave. (idk how but if it is possible stm32 may be master too.) My problem is I'm new for stm32 and I don't know how an I make stm32 to slave. Can someone show me a way for stm32 spi slave ? Thanks in advance.


Solution

  • Yes, you can use the STM32 as SPI slave.

    If you are new with STM32, I recommend to use STM32CubeIDE and its code generation from .ioc file. It will make the low level initialization for SPI. All you have to use is this two function:

    HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)
    HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)
    

    If your code has no blocking function in the main while cycle (e.g.:HAL_Delay()), then you can use the SPI of the slave STM32 without interrupt or DMA.

    Important: If your slave device has to answer for the master (not just read from it), you have to set the size of the protocol the same as the size of the command bytes (.ioc -> Basic parameters ->Data size). In this way, your HAL_SPI_Receive() function will return with the command bytes, and you can process it before calling HAL_SPI_Transmit().

    SPI Echo example ( 1 byte command, 1 byte data / I set the slave select pin manually / If you need to separate reading and writing data, and need to implement setpoint readback, you can improve this code with FromMaster/ToMaster arrays) :

    void SPI_Slave_Process(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, SPI_HandleTypeDef *hspi, uint8_t* FromMaster, uint8_t* ToMaster) {
        static uint8_t RxData;
        static uint8_t TxData;
        while(!(HAL_GPIO_ReadPin(GPIOx, GPIO_Pin))) {
            HAL_SPI_Receive(hspi, &RxData, 1, 2);
            TxData = RxData;
            HAL_SPI_Transmit(hspi, &TxData, 1, 2);
        }
    }