The bad news is that I have managed to simulate your behaviour.
I externally powered the Leonardo with a 9V source on the barrel and started it with your sketch loaded. This allowed me to use the USB at will. I used realterm as the terminal, not serial monitor.
Behaviour below
led tx led
power up fast off
connect fast off
disconnect fast off
.
.
.
connect fast off
realterm on fast on
realterm stop fast on
.
.
.
disconnect slow on
connect fast off
realterm on fast on
realterm stop fast on
disconnect slow on
The good news is that you can use Serial.availableForWrite() as demonstrated below. If there are more than 32 bytes in the transmit buffer, it will stop sending; the TX led will stay on though.
boolean ledState = false;
void setup()
{
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(13, ledState);
ledState = !ledState;
if (Serial.availableForWrite() > 32)
{
Serial.println(".");
}
delay(50);
}
You will need to check how big the transmit buffer is and adjust the number; for an Uno it's 64 and I just picked half of that. I will try to find it as well.
Gussoh:
Do you know if the if(Serial) works better on your boards? For me it only works until the first connection is established, then it always returns true, regardless.
Works the same; needs to have seen a connection once. But see the above test results. If I reconnect after a disconnect, the TX led is off and it will wait.
You probably can combine in some way the availableForWrite and the if(Serial); and maybe you have to get it all reliable and not miss data, not sure. If the buffer content reaches 32 bytes, you can set a flag and use if(Serial) when that flag is set to determine if a terminal was opened again.