Skip to content

Commit

Permalink
Merge pull request #2124 from fpistm/Serial_flush_timeout
Browse files Browse the repository at this point in the history
feat(serial): add timeout support to flush()
  • Loading branch information
fpistm authored Sep 11, 2023
2 parents 0ffbf3e + 96cba70 commit 6f39b41
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 11 deletions.
25 changes: 15 additions & 10 deletions cores/arduino/HardwareSerial.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ void HardwareSerial::begin(unsigned long baud, byte config)
void HardwareSerial::end()
{
// wait for transmission of outgoing data
flush();
flush(TX_TIMEOUT);

uart_deinit(&_serial);

Expand Down Expand Up @@ -487,20 +487,25 @@ int HardwareSerial::availableForWrite(void)
return tail - head - 1;
}

void HardwareSerial::flush()
void HardwareSerial::flush(uint32_t timeout)
{
// If we have never written a byte, no need to flush. This special
// case is needed since there is no way to force the TXC (transmit
// complete) bit to 1 during initialization
if (!_written) {
return;
}

while ((_serial.tx_head != _serial.tx_tail)) {
// nop, the interrupt handler will free up space for us
if (_written) {
uint32_t tickstart = HAL_GetTick();
while ((_serial.tx_head != _serial.tx_tail)) {
// the interrupt handler will free up space for us
// Only manage timeout if any
if ((timeout != 0) && ((HAL_GetTick() - tickstart) >= timeout)) {
// clear any transmit data
_serial.tx_head = _serial.tx_tail;
break;
}
}
// If we get here, nothing is queued anymore (DRIE is disabled) and
// the hardware finished transmission (TXC is set).
}
// If we get here, nothing is queued anymore (DRIE is disabled) and
// the hardware finished transmission (TXC is set).
}

size_t HardwareSerial::write(const uint8_t *buffer, size_t size)
Expand Down
2 changes: 1 addition & 1 deletion cores/arduino/HardwareSerial.h
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ class HardwareSerial : public Stream {
virtual int peek(void);
virtual int read(void);
int availableForWrite(void);
virtual void flush(void);
virtual void flush(uint32_t timeout = 0);
virtual size_t write(uint8_t);
inline size_t write(unsigned long n)
{
Expand Down
2 changes: 2 additions & 0 deletions cores/arduino/stm32/uart.h
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ struct serial_s {
};

/* Exported constants --------------------------------------------------------*/
#ifndef TX_TIMEOUT
#define TX_TIMEOUT 1000
#endif

#if !defined(RCC_USART1CLKSOURCE_HSI)
/* Some series like C0 have 2 derivated clock from HSI: HSIKER (for peripherals)
Expand Down

0 comments on commit 6f39b41

Please sign in to comment.