Hello @RongShengWang
I updated my code. Could you check with this please.
void SPI_Transmit_Receive(const uint8_t *data_tx, uint8_t *data_rx, uint8_t size)
{
uint8_t rx_size= size;
uint8_t tx_size = size;
/* Set the Rx Fifo threshold */
if (size > 1U)
{
/* Set fiforxthreshold according the reception data length: 16bit */
CLEAR_BIT(SPI1->CR2, SPI_RXFIFO_THRESHOLD);
}
else
{
/* Set fiforxthreshold according the reception data length: 8bit */
SET_BIT(SPI1->CR2, SPI_RXFIFO_THRESHOLD);
}
/* Enable SPI */
SPI1->CR1 |= SPI_CR1_SPE;
while (size > 0)
{
/* Wait until TXE (Transmit buffer empty) flag is set */
while (!__HAL_SPI_GET_FLAG(&hspi1, SPI_FLAG_TXE));
/* Transmit data */
if (tx_size > 1U)
{
SPI1->DR = *((uint16_t *)data_tx);
data_tx += sizeof(uint16_t);
tx_size -= 2U;
}
else
{
*(__IO uint8_t *)&SPI1->DR = (*data_tx);
data_tx ++;
tx_size --;
}
/* Wait until RXNE (Receive buffer not empty) flag is set */
while (!__HAL_SPI_GET_FLAG(&hspi1, SPI_FLAG_RXNE));
if (rx_size > 1U)
{
*((uint16_t *)data_rx) = (uint16_t)SPI1->DR;
data_rx += sizeof(uint16_t);
rx_size -= 2U;
if (rx_size <= 1U)
{
/* Set RX Fifo threshold before to switch on 8 bit data size */
SET_BIT(SPI1->CR2, SPI_RXFIFO_THRESHOLD);
}
}
else
{
(*(uint8_t *)data_rx) = *(__IO uint8_t *)&SPI1->DR;
data_rx++;
rx_size --;
}
}
/* Wait until the SPI is not busy */
while (__HAL_SPI_GET_FLAG(&hspi1, SPI_FLAG_BSY));
/* Disable SPI */
SPI1->CR1 &= ~SPI_CR1_SPE;
}
In order to give better visibility on the answered topics, please click on 'Best answer' on the reply which solved your issue or answered your question. Saket_Om