Serial Communications Trigger

I have created a routine that outputs serial data to a terminal for troubleshooting (see attached picture). I have it color coded and formatted using ascii codes which is very readable and works fine. Since this requires sending serial data I would like to be able to control the routine so that it is only active when I have the USB cable plugged into a terminal. Is there a way to auto detect whether the USB cable is plugged into the Arduino?

My initial thought is to send a short prompt like below and use the corresponding character to control the serial display routine. This would give me a way to toggle it on and off. I would initially set it to "off" during setup.

Serial Communications egin or [Q]uit
Serial_Display.jpg

I do not know of a way you can "read" if the USB is connected or not, whether there is an appropiate program on the pc.

The screen shot shows PuTTY. Theres is a "enquiry" string you can send to PuTTY (and most other terminal emulators), and PuTTY will reply with some terminal info. If you do that in the Arduino in setup() you can then disable your serial debug/diagnstic routine.

Thanks for your response! I think this will work for me. I can send the ^E enquiry character and if I get a response I will send the serial data, if no response I will skip that routine. Just need to make sure the time sending the ^E enquiry character and waiting for a response is less than the actual time to just send the serial data to begin with.

Scott

Just a quick update. I wrote a simple routine that sends out a ctl-E and if there is a response I continue with sending the serial data.

The serial data in my program takes 70ms to execute.
The routine that checks for a terminal response takes about 1ms to execute (serial port at 115,000)

So, it looks like I can save 69ms each program cycle by using a routine that checks for a terminal response. Below is a copy of the code in the event it is useful to someone else.

unsigned long start, finished;      // Timer variables
void setup()
{
Serial.begin(115200);
}

void loop() 
{
 start=millis();                    // Start timer
  Serial.write(5);                  // ^E enquiry character
  //delay (50);                     // No delay was necessary, but initially had it in the code to test it out
  if (Serial.available() > 0)       // Check for serial data response
  {  
   finished=millis();               // Stop timer
    Serial.print(finished-start);   // Print program execution time to terminal window
    Serial.println(" ms ");
  }
}

Thank you very much for the feedback. Good for the Forum, and really nice to know the suggestion made was usefull.