@@ -441,7 +441,7 @@ void HardwareSerial::begin(unsigned long baud, byte config)
441441void HardwareSerial::end ()
442442{
443443 // wait for transmission of outgoing data
444- flush ();
444+ flush (TX_TIMEOUT );
445445
446446 uart_deinit (&_serial);
447447
@@ -487,20 +487,25 @@ int HardwareSerial::availableForWrite(void)
487487 return tail - head - 1 ;
488488}
489489
490- void HardwareSerial::flush ()
490+ void HardwareSerial::flush (uint32_t timeout )
491491{
492492 // If we have never written a byte, no need to flush. This special
493493 // case is needed since there is no way to force the TXC (transmit
494494 // complete) bit to 1 during initialization
495- if (!_written) {
496- return ;
497- }
498-
499- while ((_serial.tx_head != _serial.tx_tail )) {
500- // nop, the interrupt handler will free up space for us
495+ if (_written) {
496+ uint32_t tickstart = HAL_GetTick ();
497+ while ((_serial.tx_head != _serial.tx_tail )) {
498+ // the interrupt handler will free up space for us
499+ // Only manage timeout if any
500+ if ((timeout != 0 ) && ((HAL_GetTick () - tickstart) >= timeout)) {
501+ // clear any transmit data
502+ _serial.tx_head = _serial.tx_tail ;
503+ break ;
504+ }
505+ }
506+ // If we get here, nothing is queued anymore (DRIE is disabled) and
507+ // the hardware finished transmission (TXC is set).
501508 }
502- // If we get here, nothing is queued anymore (DRIE is disabled) and
503- // the hardware finished transmission (TXC is set).
504509}
505510
506511size_t HardwareSerial::write (const uint8_t *buffer, size_t size)
0 commit comments