Necessary to wait for serial?

Hi. I recently got my hands on a Leonardo, and I am making a sketch where I use the USB serial for debugging.

I was having some problems that my sketch would not start running if I powered on the Leonardo with an external power supply. Only if the computer was connected to the USB port it would start when I connected with a serial terminal.

I found out that this behaviour was caused by the while(Serial) in the beginning of the sketch, which came from some example sketch. After removing this line the sketch would start on an external power supply without problems.

My question is now what is the reason for having the while(Serial); in the beggining? Is it just to make sure that the sketch does not start until the computer has been connected, or is it to avoid potentially problems if you start printing to the USB port before it has been initialized?

It's there to ensure that the USB connection to the PC from the Leo has been set before any data is sent to the PC.


Ok, so it is only to make sure that the PC does not "miss" any data?

In my case I'm just using it for debugging, so I want the sketch to able to start no matter if the PC is connected or not.

I guess what I am asking is if it will cause any problems to use the Serial.print function if I do not wait for Serial to become true first, because something will then be uninitialized or something.

Is it ok to not to wait for Serial, and then just start printing?

Just take that line out when you know that it will be on an external supply.

Here's a better way of making any Arduino wait for USB serial...

void setup() {
  // put your setup code here, to run once:

  SerialUSB.begin(9600); //doesn't matter what baud rate you pick, but you must pick one
  while(!SerialUSB && millis()<4000) {
    //wait for serial to connect, for up to 4 seconds (4000 milliseconds)
  SerialUSB.println("Test code started!");
void loop() {
  // put your main code here, to run repeatedly:


This uses the fact that millis() is always set to zero at reset. By putting the check at the end of setup(), it means you don't have to wait any longer than absolutely necessary.

I use the Arduino-defined SerialUSB because on some chips, like the Teensy or Due, Serial is not the USB serial. If you are likely to run this on other Arduinos which have no USB serial, then a better choice might be SERIAL_PORT_MONITOR.