SPI configuration change and DMA Transmit
I’m currently developing a custom board based on an STM32U585.
On the board, I have three SPI devices connected to the MCU, each managed by its own chip-select line:
* MAX9939 → requires LSB first and can be controlled in transmit-only SPI mode.
* LSM6DSL (IMU) → requires MSB first and full-duplex mode.
* CAT25256 (EEPROM) → also requires MSB first and full-duplex mode.
To handle these differences, I switch the SPI configuration dynamically at runtime. The function I use for reconfiguration is:
int SPI_SetConfig(SPI_HandleTypeDef *hspi, struct _myspi_config_t *config)
{
printf(">>>>>>>>>>>>QUI\r\n");
// Skip re-initialization if configuration already matches
if (hspi->Init.CLKPolarity == config->CPOL &&
hspi->Init.CLKPhase == config->CPHA &&
hspi->Init.FirstBit == config->order &&
hspi->Init.Direction == config->direction &&
hspi->Init.DataSize == config->datasize &&
hspi->Init.BaudRatePrescaler == config->prescaler) {
return 0;
}
// Abort any ongoing transfer
if (HAL_SPI_GetState(hspi) != HAL_SPI_STATE_READY) {
HAL_SPI_Abort(hspi);
}
__HAL_SPI_DISABLE(hspi);
hspi->Init.CLKPolarity = config->CPOL;
hspi->Init.CLKPhase = config->CPHA;
hspi->Init.FirstBit = config->order;
hspi->Init.DataSize = config->datasize;
hspi->Init.Direction = config->direction;
hspi->Init.BaudRatePrescaler = config->prescaler;
if (HAL_SPI_Init(hspi) != HAL_OK) {
printf("SPI_SetConfig()::error while changing polarity\r\n");
return -1;
}
__HAL_SPI_ENABLE(hspi);
return 0;
}
## The issue
When I switch configurations repeatedly between devices, I encounter the following problem:
Calling HAL_SPI_Transmit_DMA() starts normally (no error returned).
However, HAL_SPI_TxCpltCallback() is never called.
If I check the state with HAL_SPI_GetState(), the SPI remains stuck in HAL_SPI_STATE_BUSY_TX.
If I wait in a loop for transmission completion, the loop never exits.
I checked both the SPI and DMA registers, and they appear to be fine. Despite that, the DMA transfer never completes.
If I skip one particular call to SPI_SetConfig(), the issue does not occur. But I don’t understand why this happens, and I’m not confident it won’t show up again under other conditions.
## Question
What could cause HAL_SPI_Transmit_DMA() to get stuck in BUSY_TX after reconfiguring the SPI peripheral multiple times?
How can I ensure safe switching between different SPI configurations without breaking DMA transfers?
Thanks in advance!
Edited to apply source code formatting - please see How to insert source code for future reference.
