Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

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

  1. #1
    Senior Member blackketter's Avatar
    Join Date
    May 2015
    Location
    San Francisco
    Posts
    257

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

    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.

  2. #2
    Member
    Join Date
    Oct 2019
    Location
    Calgary
    Posts
    41
    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.

  3. #3
    Senior Member blackketter's Avatar
    Join Date
    May 2015
    Location
    San Francisco
    Posts
    257
    Quote Originally Posted by Silverlock View Post
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •