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

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

  1. #1

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

    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

  2. #2
    Senior Member+ MichaelMeissner's Avatar
    Join Date
    Nov 2012
    Location
    Ayer Massachussetts
    Posts
    3,259
    Quote Originally Posted by ausserirdischesindgesund View Post
    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.

Posting Permissions

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