Skip to content

Commit f9f1d3a

Browse files
committed
Serial.flush() waits for last character to be transmitted (michele.mazzucchi)
http://code.google.com/p/arduino/issues/detail?id=871
1 parent b7fc69a commit f9f1d3a

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

hardware/arduino/cores/arduino/HardwareSerial.cpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,8 @@ void HardwareSerial::begin(unsigned long baud)
327327
*_ubrrh = baud_setting >> 8;
328328
*_ubrrl = baud_setting;
329329

330+
transmitting = false;
331+
330332
sbi(*_ucsrb, _rxen);
331333
sbi(*_ucsrb, _txen);
332334
sbi(*_ucsrb, _rxcie);
@@ -376,8 +378,9 @@ int HardwareSerial::read(void)
376378

377379
void HardwareSerial::flush()
378380
{
379-
while (_tx_buffer->head != _tx_buffer->tail)
380-
;
381+
// UDR is kept full while the buffer is not empty, so TXC triggers when EMPTY && SENT
382+
while (transmitting && ! (*_ucsra & _BV(TXC0)));
383+
transmitting = false;
381384
}
382385

383386
size_t HardwareSerial::write(uint8_t c)
@@ -394,6 +397,9 @@ size_t HardwareSerial::write(uint8_t c)
394397
_tx_buffer->head = i;
395398

396399
sbi(*_ucsrb, _udrie);
400+
// clear the TXC bit -- "can be cleared by writing a one to its bit location"
401+
transmitting = true;
402+
sbi(*_ucsra, TXC0);
397403

398404
return 1;
399405
}

hardware/arduino/cores/arduino/HardwareSerial.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ class HardwareSerial : public Stream
4343
uint8_t _rxcie;
4444
uint8_t _udrie;
4545
uint8_t _u2x;
46+
bool transmitting;
4647
public:
4748
HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
4849
volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,

0 commit comments

Comments
 (0)