SPI Slave with DMA: How to receive packets of unknown length?
- 5 replies
- 7881 views
Ok guys. I think I'm slowly turining insane. Someone please help me. I already wasted so many hours on this...
I'm currently fighting with getting SPI to work in slave mode with DMA. So let me explain what I'm trying to do.
The STM32(F303RE) is connected to a RaspberryPi. The Raspi sends messages over SPI to the STM32 and excpects a response message. SPI Freuqentcy is only 500 kHz.
The message format is:
MB1(1 byte)|MB2(1 byte)|messeageId(1 byte)|payloadLength(1 byte)|payload(payloadLength bytes)|CRC(4 bytes)
MB1(0x22) and MB2(0x33) are magic bytes I use to detect the start of a message.
The the RPi sends messages with arbitrary length to the STM32, waits a couple of ms and then starts a second spi transfer for the response (only transmitting 0x00 bytes, while the STM32 can write the response). Length of the response is known by the Raspi and the STM32. Length of the inital message is only known by the Raspi in advance... After some more ms the next message is send to the STM32.
There are two problems with my current implementation:
1) Data in the recieve buffer is sometimes prefixed by 1 to 4 0x00 bytes.
2) Sometimes the recieve buffer only contains seemingly random data (only in the first few bytes of the buffer. The remainding buffer is 0x00).
3) If 1 or 2 occurs the STM32 my code blocks for many ms and I can't figure out where it blocks.
I created a small example project with just the SPI code: https://github.com/Geend/Stm32DmaSpiSlaveTest/blob/master/Src/main.c
It's generated with Stm32CubeMX. The Stm32CubeMX project file is also in the repository.
I think the interesstings parts are the following functions in main.c:
void loop();
HAL_StatusTypeDef restartDma(uint16_t size, bool clearWB);
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin);
I also attached a DSView logic anylyzer log file and a few screenshots here.
The documentation of the HAL SPI API is a bit sparse. I'm 100% sure I'm not using it correctly. Especially the usage of HAL_SPI_Transmit_DMA, HAL_SPI_Receive_DMA, HAL_SPI_DMAStop, HAL_SPI_Abort and the handling of SPI NSS. Maybe my entire approch to this is wrong and there is a better solution...
So here is my question: How recieve SPI messages with unknown length on an STM32 using DMA?
