From d8dfd14dfc7c12ba476a8d9be5e18fe52e29a063 Mon Sep 17 00:00:00 2001 From: Michael Keller Date: Sun, 23 Aug 2020 15:57:12 +1200 Subject: [PATCH] Merge pull request #10118 from SJChannel/serialRxBytesWaiting-fix Fix bug that causes uartTotalRxBytesWaiting() to return incorrect value when DMA is used --- src/main/drivers/serial_uart.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/drivers/serial_uart.c b/src/main/drivers/serial_uart.c index e516262c0c..2ac46f13e1 100644 --- a/src/main/drivers/serial_uart.c +++ b/src/main/drivers/serial_uart.c @@ -156,10 +156,12 @@ static uint32_t uartTotalRxBytesWaiting(const serialPort_t *instance) uint32_t rxDMAHead = xDMA_GetCurrDataCounter(s->rxDMAResource); #endif - if (rxDMAHead >= s->rxDMAPos) { - return rxDMAHead - s->rxDMAPos; + // s->rxDMAPos and rxDMAHead represent distances from the end + // of the buffer. They count DOWN as they advance. + if (s->rxDMAPos >= rxDMAHead) { + return s->rxDMAPos - rxDMAHead; } else { - return s->port.rxBufferSize + rxDMAHead - s->rxDMAPos; + return s->port.rxBufferSize + s->rxDMAPos - rxDMAHead; } } #endif