Making a sketch with Serial.print() work if something is connected to USB or not

Status
Not open for further replies.
I am currently working on a Teensy 2.0 Arduino project where I want to either connect the Teensy USB to the computer, or in other scenarios just to a phone Charger (no computer listening to the serial port). Without chaning the sketch in between.

I am now opening Serial like:

Code:
void setup() {
  Serial.begin(38400);
  while (!Serial)
  ;
}

... 

void loop() {
 Serial.print("foo");
 // do other stuff
}

If I comment out all the serial stuff my sketch runs just fine with "nothing" (a charger actually) connected to USB. If not it seems to hang in setup().

Is there a "right" or suggested way to solve this problem or should this just work and is my problem somewhere else (a side effect)?

Thanks in advance,
Ralph
 
I am currently working on a Teensy 2.0 Arduino project where I want to either connect the Teensy USB to the computer, or in other scenarios just to a phone Charger (no computer listening to the serial port). Without chaning the sketch in between.

I am now opening Serial like:

Code:
void setup() {
  Serial.begin(38400);
  while (!Serial)
  ;
}

... 

void loop() {
 Serial.print("foo");
 // do other stuff
}

If I comment out all the serial stuff my sketch runs just fine with "nothing" (a charger actually) connected to USB. If not it seems to hang in setup().

Is there a "right" or suggested way to solve this problem or should this just work and is my problem somewhere else (a side effect)?

Thanks in advance,
Ralph

In general, you want to avoid loops like:
Code:
    while (!Serial)
        ;

which will hang until you attach a USB serial connection. Instead you want a timeout, so it tries to get a serial connection, but stops asking whether it is connected after a timeout:
Code:
    // Wait for up to 3 seconds for a USB connection
    while (!Serial && millis () < 3000UL)
       ;

Now on a Teensy 3.x/LC/4.0, other Serial.print's would just not print anything if there is no serial device. I don't know if the Teensy 2.x does the same thing.
 
Status
Not open for further replies.
Back
Top