Skip to content

Commit 8eeee1b

Browse files
committed
Improve STM32 SPI asynchronous API stability
`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).
1 parent 0947214 commit 8eeee1b

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

targets/TARGET_STM/stm_spi_api.c

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,9 @@ void init_spi(spi_t *obj)
149149
if (HAL_SPI_Init(handle) != HAL_OK) {
150150
error("Cannot initialize SPI");
151151
}
152+
/* In some cases after SPI object re-creation SPI overrun flag may not
153+
* be cleared, so clear RX data explicitly to prevent any transmissions errors */
154+
spi_flush_rx(obj);
152155
/* In case of standard 4 wires SPI,PI can be kept enabled all time
153156
* and SCK will only be generated during the write operations. But in case
154157
* of 3 wires, it should be only enabled during rd/wr unitary operations,
@@ -1329,11 +1332,12 @@ void spi_master_transfer(spi_t *obj, const void *tx, size_t tx_length, void *rx,
13291332
inline uint32_t spi_irq_handler_asynch(spi_t *obj)
13301333
{
13311334
int event = 0;
1335+
SPI_HandleTypeDef *handle = &(SPI_S(obj)->handle);
13321336

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

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

1356-
13571371
return (event & (obj->spi.event | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE));
13581372
}
13591373

0 commit comments

Comments
 (0)