Skip to content

Commit

Permalink
Improve STM32 SPI asynchronous API stability
Browse files Browse the repository at this point in the history
`HAL_SPI_Receive_IT` HAL function causes dummy reads in 3-wire mode,
that causes data corruption in RX FIFO/register. It isn't possible
to fix it without signification refactoring, but we may prevent data
corruption with the following fixes:

- RX buffer/register cleanup after asynchronous transfer in 3-wire mode
- Explicit RX buffer/register cleanup after SPI initialization
  (for cases if we re-create SPI object).
  • Loading branch information
vznncv committed Aug 27, 2021
1 parent 0947214 commit 8eeee1b
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions targets/TARGET_STM/stm_spi_api.c
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ void init_spi(spi_t *obj)
if (HAL_SPI_Init(handle) != HAL_OK) {
error("Cannot initialize SPI");
}
/* In some cases after SPI object re-creation SPI overrun flag may not
* be cleared, so clear RX data explicitly to prevent any transmissions errors */
spi_flush_rx(obj);
/* In case of standard 4 wires SPI,PI can be kept enabled all time
* and SCK will only be generated during the write operations. But in case
* of 3 wires, it should be only enabled during rd/wr unitary operations,
Expand Down Expand Up @@ -1329,11 +1332,12 @@ void spi_master_transfer(spi_t *obj, const void *tx, size_t tx_length, void *rx,
inline uint32_t spi_irq_handler_asynch(spi_t *obj)
{
int event = 0;
SPI_HandleTypeDef *handle = &(SPI_S(obj)->handle);

// call the CubeF4 handler, this will update the handle
HAL_SPI_IRQHandler(&obj->spi.handle);
HAL_SPI_IRQHandler(handle);

if (obj->spi.handle.State == HAL_SPI_STATE_READY) {
if (handle->State == HAL_SPI_STATE_READY) {
// When HAL SPI is back to READY state, check if there was an error
int error = obj->spi.handle.ErrorCode;
if (error != HAL_SPI_ERROR_NONE) {
Expand All @@ -1351,9 +1355,19 @@ inline uint32_t spi_irq_handler_asynch(spi_t *obj)
// disable the interrupt
NVIC_DisableIRQ(obj->spi.spiIRQ);
NVIC_ClearPendingIRQ(obj->spi.spiIRQ);
#ifndef TARGET_STM32H7
if (handle->Init.Direction == SPI_DIRECTION_1LINE && obj->rx_buff.buffer != NULL) {
/**
* In case of 3-wire SPI data receiving we usually get dummy reads.
* So we need to cleanup FIFO/input register before next transmission.
* Probably it's better to set SPI_EVENT_RX_OVERFLOW event flag,
* but let's left it as is for backward compatibility.
*/
spi_flush_rx(obj);
}
#endif
}


return (event & (obj->spi.event | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE));
}

Expand Down

0 comments on commit 8eeee1b

Please sign in to comment.