Skip to content

Commit 96cba70

Browse files
committed
feat(serial): add timeout support to flush()
when called by end(). Default, no timeout (0). When called by end(), default timeout is TX_TIMEOUT which can be redefined if needed. Fixes stm32duino#2122 Signed-off-by: Frederic Pillon <[email protected]>
1 parent e6ad4b1 commit 96cba70

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

Diff for: cores/arduino/HardwareSerial.cpp

+15-10
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ void HardwareSerial::begin(unsigned long baud, byte config)
441441
void 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

506511
size_t HardwareSerial::write(const uint8_t *buffer, size_t size)

Diff for: cores/arduino/HardwareSerial.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ class HardwareSerial : public Stream {
125125
virtual int peek(void);
126126
virtual int read(void);
127127
int availableForWrite(void);
128-
virtual void flush(void);
128+
virtual void flush(uint32_t timeout = 0);
129129
virtual size_t write(uint8_t);
130130
inline size_t write(unsigned long n)
131131
{

0 commit comments

Comments
 (0)