Arduino Dedect connection State of PC Com port

Hi,
i m search and try some solution but not.

if Arduino connected pc and serial comminication avaiable, i m catch this.

i try if(Serial) not work in "void loop".

I want to do exactly that ;

void loop() {
String DateTime;
DateTime=rtc.getTimeStr();

if (serial port connected)
    { 
     while (sdFile.available())  { Serial.println(sdFile.read() ; } // before if db file exists  send db file lines to pc
     Serial.println(DateTime);                                                // after send  actual DateTime data.
    }
     else // not connected
   {
    // sd card write data 
       sdFile.write(Datetime);
    }
}

Shortly if serial2pc connected, send data to pc else save data to sd. in main loop.
How to ?

Thanks for yours interest.

Have you done a search? It is not possible to tell if there is anything on the other end of the serial port without the cooperation of the program on the other end of the connection.

i try cooperation of the pc software like this but not healthy.

   boolean PingSerial()
    {
      String Ping;
      Ping="";
      Serial.println("<P>");
      delay(40);
      if (Serial.available())   // ping reply
      {
          Ping=Serial.readString();
           if (Ping=="<P>") {
            Ping="OK" ;    
           }
      }
      if (Ping=="OK") { return true;} else { return false;}; 
    }

and use PingSerial() in main loop. so it did not work.

Can you give a sample solution ?
Thanks.

i try cooperation of the pc software like this but not healthy.

What application is listening to the serial port on the PC? Does that software KNOW that it is supposed to send "

" when it gets "

"?

      if (Ping=="OK") { return true;} else { return false;};

or

   return (Ping == "OK");

İ write test pc software.
Listening pc side and if pc receive

, send pc to arfuino

.

İf arduino receive

ping function return true.

İts looks like work, but slowly cominication and sometimes not work good.

Your PC might be doing other things so it might take a while before it responds.

More importantly, there is no guarantee that the reply from the PC contains all three bytes; it might well send two bytes followed by one (and readString might time out in between).

It might be better to use a character array instead of String. See the thread Serial Input Basics for ideas. You can implement your own timeout.

@sterretje
thanks for your information. i solved this issue for your guidance.