How to tell my Arduino when the serial monitor closes

Hi all,

I am working on a data logging project using the Adafruit Feather 32u4 Adalogger to log data to the SD card. The SD card then dumps data over the serial port.

I want the data to dump/print over the serial port only when it is plugged into the computer and the serial monitor is open. This is easy, BUT, once my Arduino know the serial port is open it thinks it is open even when I remove the Arduino from the computer and run it on battery power.

Here is a super simplified example of my code:

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

void loop() {
  CheckPluggedIn();
}

void CheckPluggedIn()
{
    if (Serial)
    {
      digitalWrite(13, HIGH);
    }

    else
    {
      digitalWrite(13, LOW);
    }
}

When I open the serial monitor the LED turns on, but when I close the monitor or unplug the Arduino the LED stays on...

Any help is much appreciated.

You can not detect a lost connection AFAIK.

Why bother with checking?

Dump the data, but only mark it successully transferred if you get a positve acknowledge from the target. (Your program should act like this anyway, don't you think so?)

A "Do you want the dump?" message to target followed by an "Shure, go ahead." answer would work, or the other way around a "Give me the data, slave!" message could trigger the transfer.

You need to write software to do this on the PC. Do you know Python or any of the Microsoft Visual languages? You could write simple software to replace the Serial Monitor with any of those.