How does this code line detect if a serial interface is connected? I am working with some code for remote temperature sensor nodes. They turn the debug interface on and off depending on if anything is conneced to the serial port or not.

The code is on Github here. Line 111 is the line of interest:

if (Serial) debug = 1; else debug=0; //if serial UART to USB is connected show debug O/P.


So, a simple question: On a hardware and software level, how does this work? I can't see anything in HardwareSerial or Stream that would return true/false if anything was connected or not.

Note that I am not confident that it actually works. This simple test indicates it doesn't work as the LED flashes regardless of the presence of a serial adapter or connection:

boolean debug;

const int toggle = 6;

void setup()
{
  if (Serial) debug = 1; else debug = 0;

  pinMode(toggle, OUTPUT);
  digitalWrite(toggle, LOW);

  if (debug)
  {
    Serial.begin(9600);
    Serial.println("Setup");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
  }
}

void loop()
{
  if (debug)
  {
    Serial.println("Loop");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
    delay(1000);
  }
}
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.