This was fixed by replacing UART::flush() with the following:
void UART::flush() {
#if defined(SERIAL_CDC)
if (is_usb) {
while(!_SerialUSB.writeable());
} else {
while(!_serial->obj->writeable());
}
#else
while(!_serial->obj->writeable());
#endif
}
In the file 'cores/arduino/Serial.cpp'.