cancel
Showing results for 
Search instead for 
Did you mean: 

HAL_SPI_Transmit() Size, is it defined as a byte or a word?

Spectramax
Associate II

Hello,

I have a very simple code. A two byte array that I need to send over SPI.

uint8_t my_array[2];
my_array[0] = 0x10;
my_array[1] = 0x01;
 
HAL_SPI_Transmit(&hspi1, my_array, 2, SPI_TIME_OUT);
// or 
HAL_SPI_Transmit(&hspi1, my_array, 1, SPI_TIME_OUT);
 

The HAL reference guide does not specify in what format is the "Size" expected? Is it in bytes? or in a 16-bit word?

3 REPLIES 3

Look at the library source code, it is provided.

Pretty sure it is a unit count. If you configured the SPI in 16-bit mode it will be words, and bytes in 8-bit mode.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
MBorg.14.276
Associate

Disclaimer: Not an expert.

tl;dr : 16-bit words 

Looking at the source code in stm32f4xx_hal_spi.c, the argument in question (1 or 2) is received as parameter uint16_t Size.

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

uint16_t Size is assigned to both hspi->TxXferSize and hspi->TxXferCount.

  /* Set the transaction information */
  hspi->State       = HAL_SPI_STATE_BUSY_TX;
  hspi->ErrorCode   = HAL_SPI_ERROR_NONE;
  hspi->pTxBuffPtr  = (uint8_t *)pData;
  hspi->TxXferSize  = Size;
  hspi->TxXferCount = Size;

The routine loops through hspi->TxXferCount and decrements down to zero. I believe the answer to your question is found herein. DR is loaded with a 16-bit word along with decrement of TxXferCount; the load and decrement are 1-to-1. If Size was 8-bit char, we might assume it would be 2-to-1. This suggests the argument Size is 16-bit words.

/* Transmit data in 16 Bit mode */
  while (hspi->TxXferCount > 0U)
  {
   /* Wait until TXE flag is set to send data */
   if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE))
   {
     hspi->Instance->DR = *((uint16_t *)pData);
     pData += sizeof(uint16_t);
     hspi->TxXferCount--;
   }
   else
   {
    /* Timeout management */
    if((Timeout == 0U) || ((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick()-tickstart) >= Timeout)))
    {
     errorcode = HAL_TIMEOUT;
     goto error;
    }
   }
  }

uint16_t Size in this context means between 0 and 65535 units, and is unrelated to the width of the transfer over the bus.

SpiHandle.Init.DataSize         = SPI_DATASIZE_8BIT; // << THIS IS CONTROLLING

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..