Frequent calls to Serial.flush() can gum things up

blackketter

Well-known member
I spent a little too long tracking down an issue with Serial.flush() on a Teensy 3.6 today.

The following sketch doesn't generate any serial output. If I comment out the Serial.flush() it works fine:

Code:
void setup() {
  Serial.begin(9600);
  delay(1000);
}

int time = 0;

void loop() {
  
  int now = millis()/1000;

  if (now != time) {
    Serial.println(now);
    time = now;
  }
  Serial.flush();
}

The workaround is to not call flush too often, though I'm not sure exactly how often that is.

In my larger project, too frequent calls to Serial.flush() also stopped the Keyboard and Mouse libraries from generating events to the host. Interestingly, in that project connecting a monitor to the virtual serial port somehow slowed things down enough to make the keyboard and mouse work again.

This is with Teensyduino 1.51.
 
Out of curiosity, I tried your program out on a Teensy 4.0 and it behaved as it should: printing the count once a second.

In further of curiosity, what happens if you include the Serial.flush() call in the if block rather than putting it afterwards? That way it's only getting called after you've actually printed something.
 
Out of curiosity, I tried your program out on a Teensy 4.0 and it behaved as it should: printing the count once a second.

In further of curiosity, what happens if you include the Serial.flush() call in the if block rather than putting it afterwards? That way it's only getting called after you've actually printed something.

Good point, I also didn't see this on Teensy 4.0. And if I call flush less frequently (like after every print), it works fine. I suspect that there's some USB timing issue that's at play here.

It's easy enough to work around: don't abuse flush(). I thought I'd just share it in case somebody else was having a similar problem.
 
Back
Top