Jul 3, 2015

Program waits forever if monitor doesn't open on Teensy 3

Symptom: Program doesn't run (actually runs but hangs waiting for serial response) if the monitor window isn't opened.

The while loop added to wait for the serial port to exist also waits for a response from the host on the usb line; hence if the monitor isn't opened and the usb isn't connected to a computer with a response, it simply waits forever. If the program is only printing diagnostic messages for example, and you're done diagnosing, you don't open and the program seems to stop working. (Another good reason to blink and LED at the beginning of a program so that you know it has started.)

If the program is not required to communicate over the port, then no reason to block its operation. A solution is to add a timer so that after a while (a few seconds), the loop exits and the program proceeds.


void setup() {
  int timeout_duration = 3000;

  while (!Serial && (millis() - t0) < timeout_duration) { // timeout added
    ; // wait for serial port to connect. Needed for Leonardo or Teensy.
      // Port gets re-instantiated on start
  } 
  Serial.begin(115200);  // USB serial port
  Pln("Serial port is working.");

}

Here's a more complete explanation of the condition and Teensy designer's response.
https://forums.adafruit.com/viewtopic.php?f=25&t=67480&start=15
Another example uses same approach of a timer to stop waiting, making it non-blocking
http://www.xappsoftware.com/wordpress/2013/10/13/a-simple-serial-non-blocking-read-for-arduino/