Skip to content

Commit d7e8143

Browse files
Fix lockup when writing to HardwareSerial with interrupts disabled
When interrupts are disabled, writing to HardwareSerial could cause a lockup. When the tx buffer is full, a busy-wait loop is used to wait for the interrupt handler to free up a byte in the buffer. However, when interrupts are disabled, this will of course never happen and the Arduino will lock up. This often caused lockups when doing (big) debug printing from an interrupt handler. Additionally, calling flush() with interrupts disabled while transmission was in progress would also cause a lockup. When interrupts are disabled, the code now actively checks the UDRE (UART Data Register Empty) and calls the interrupt handler to free up room if the bit is set. This can lead to delays in interrupt handlers when the serial buffer is full, but a delay is of course always preferred to a lockup. Closes: arduino#672 References: arduino#1147
1 parent bf41c7f commit d7e8143

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

hardware/arduino/cores/arduino/HardwareSerial.cpp

+21-5
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,14 @@ void HardwareSerial::flush()
395395
if (!_written)
396396
return;
397397

398-
while (bit_is_set(*_ucsrb, UDRIE0) || bit_is_clear(*_ucsra, TXC0));
398+
while (bit_is_set(*_ucsrb, UDRIE0) || bit_is_clear(*_ucsra, TXC0)) {
399+
if (bit_is_clear(SREG, SREG_I) && bit_is_set(*_ucsrb, UDRIE0))
400+
// Interrupts are globally disabled, but the DR empty
401+
// interrupt should be enabled, so poll the DR empty flag to
402+
// prevent deadlock
403+
if (bit_is_set(*_ucsra, UDRE0))
404+
_tx_udr_empty_irq();
405+
}
399406
// If we get here, nothing is queued anymore (DRIE is disabled) and
400407
// the hardware finished tranmission (TXC is set).
401408
}
@@ -406,10 +413,19 @@ size_t HardwareSerial::write(uint8_t c)
406413

407414
// If the output buffer is full, there's nothing for it other than to
408415
// wait for the interrupt handler to empty it a bit
409-
// ???: return 0 here instead?
410-
while (i == _tx_buffer_tail)
411-
;
412-
416+
while (i == _tx_buffer_tail) {
417+
if (bit_is_clear(SREG, SREG_I)) {
418+
// Interrupts are disabled, so we'll have to poll the data
419+
// register empty flag ourselves. If it is set, pretend an
420+
// interrupt has happened and call the handler to free up
421+
// space for us.
422+
if(bit_is_set(*_ucsra, UDRE0))
423+
_tx_udr_empty_irq();
424+
} else {
425+
// nop, the interrupt handler will free up space for us
426+
}
427+
}
428+
413429
_tx_buffer[_tx_buffer_head] = c;
414430
_tx_buffer_head = i;
415431

0 commit comments

Comments
 (0)