How does this code line detect if a serial interface is connected?

You're right -- it doesn't work in most cases, and will almost always return true. The one board where it's actually functional is the Leonardo. According to the official documentation:

On the Leonardo, if (Serial) indicates wether or not the USB CDC serial connection is open. For all other instances, including if (Serial1) on the Leonardo, this will always returns true.

Basic serial connections (used by most Arduinos) usually don't care if anything is actually listening. It's not uncommon for embedded devices to send debug info by serial even when nothing is receiving it. This has the advantage that the code's timing and behaviour won't change when debugging, which could cause all sorts of problems if you're trying to diagnose a problem reported in the field.


While it may not be possible to detect whether a device is connected to the Arduino serial connection or not, it is possible to enable the debug messages over the serial connection based on the presence of a device on the serial connection.

Considering that you will be using the debug interface of your sketch only when connected to a computer capable of serial communication, it is possible to incorporate a simple test into the sketch based on which debug mode is enabled or not.

When the sketch starts, you can check to see if any data is available on the Serial connection or not. If there is, then a device is present and debugging can be enabled. On the computer side, everytime you want to start the debugging mode on the Arduino, simply send a byte over the serial connection during the setup phase and sit back.

Here is a sample sketch showing the same:

int debug = 0;

void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);

  //Wait for four seconds or till data is available on serial, 
  //whichever occurs first.
  while(Serial.available()==0 && millis()<4000);

  //On timeout or availability of data, we come here.
  if(Serial.available()>0)
  {
    //If data is available, we enter here.
    int test = Serial.read(); //We then clear the input buffer

    Serial.println("DEBUG"); //Give feedback indicating mode

    debug = 1; //Enable debug
  }
}

void loop()
{
  if(debug==1) Serial.println("ON");
  digitalWrite(13,HIGH);
  delay(1000);
  if(debug==0) Serial.println("OFF");
  //Turn off if serial is not available
  digitalWrite(13,LOW);
  delay(1000); 
}

Tags:

Serial

Library