diff --git a/cores/arduino/Serial.cpp b/cores/arduino/Serial.cpp index e4f77b076d..62ba97f995 100644 --- a/cores/arduino/Serial.cpp +++ b/cores/arduino/Serial.cpp @@ -581,8 +581,20 @@ void Uart::flush(uint32_t timeout) } // Only manage timeout if any if ((timeout != 0) && ((HAL_GetTick() - tickstart) >= timeout)) { - // clear any transmit data - _serial.tx_head = _serial.tx_tail; + // Discard the pending transmit data, except the bytes of the HAL + // transfer in progress: it can't be cancelled, and its completion + // moves tail by tx_size. Doing it atomically as the TX complete IRQ + // may end this transfer and start the next one at any time. + // PRIMASK is restored (not unconditionally enabled) as flush() may be + // called with interrupts already disabled. + uint32_t primask = __get_PRIMASK(); + __disable_irq(); + if (serial_tx_active(&_serial)) { + _serial.tx_head = (_serial.tx_tail + _serial.tx_size) % SERIAL_TX_BUFFER_SIZE; + } else { + _serial.tx_head = _serial.tx_tail; + } + __set_PRIMASK(primask); break; } }