cancel
Showing results for 
Search instead for 
Did you mean: 

How to use HAL SPI Library

Konami
Senior
Posted on November 08, 2017 at 16:02

Is it possible to use the HAL slave SPI library to receive an unknown number bytes from the master? I'm convinced I'm missing something since the packet size is rarely known in the projects I work on but for some reason I can't seem to find how to do this with the HAL.

#stm32l4-hal
5 REPLIES 5
S.Ma
Principal
Posted on November 08, 2017 at 17:54

In spi slave, you need to send a buffer and receive one. Usually the number of byte has a maximum which define the buffer size. Use dmas in circular buffer. Use nss signal as interrupt exti on rising edge to process what has been transmitted and reinit the dmas. You can see where the dma ended in memory and if a rollover occured. You can use the first 16 bit received as message length byte info. No interrupt on dma...

Posted on November 08, 2017 at 18:28

So if I'm understanding you correctly, I would use something like HAL_SPI_Receive_DMA() and the size would be the maximum expected data size?

How about determining when to call HAL_SPI_Receive_DMA? Should I be calling it after every read to prepare for whenever the master decides to send the next message or trigger the read from the NSS?

Posted on November 09, 2017 at 07:30

It's up to your decided way of handling. At NSS falling edge, you can also get EXTI interrupt and reset the DMA to the buffer or another one, then at NSS rising edge EXTI interrupt you digest or flag what you got before the NSS goes low again. Keep the interrupt simple and short in time, process your data in the main loop.

Otherwise, if you can memorise the DMA pointer at NSS falling and rising edge and the DMA is circular, you can also relatively diff and find the location of the block of received data (modulo the size of the buffer, as it may wrap around). Circular mode is preffered for zero or oversize packets.

Konami
Senior
Posted on November 13, 2017 at 17:44

Thanks for the details- it's starting to make more sense. The thing I'm not clear on still is how to continue to read to the DMA after receiving one message.

For example if I have a buffer that is 10 bytes and do a HAL_SPI_Receive_DMA() with length of 10, but my master only sends 5 bytes. I trigger on the NSS and see the 5 bytes but if I repeat the call to HAL_SPI_Receive_DMA() I get a busy error.

Should I do a HAL_SPI_DMAStop first? Also how do I keep track of the DMA read/write pointers to continue reading data where the last read left off if using a circular DMA?

Posted on November 14, 2017 at 19:00

Define your slave behaviour, shall it wait for enough data bytes to process the incoming message, or shall it process it when the NSS is released high? In I2C mode, the STOP bit will trigger action, so in SPI mode, most people would do the same. For the DMA behaviour it depends on the chosen device's.