Is there a way for a sketch to detect is USB cable is connected?
I often use
Serial.begin();
while (!Serial){}
to wait for the serial line to be active.
But if I want to use same sketch when my project is powered separately and no USB connected I have to replace while(!Serial){} with a simple delay(300) or similar, recompile and reload.
If I use the delay option all the time, the first few lines of serial output may be skipped (missing) entirely.
How about detecting when the external supply is not connected ?
The voltage will be present on the VIN pin of the board only when external power is connected. It should be possible to determine whether that pin has voltage on it or not by using an analogue input and a voltage divider between GND and VIN
There is quite possible a snag to doing this so please don't take my idea as gospel
Note too that the
while (!Serial) {}
test is meaningless on many Arduinos such as the Uno and Mega
Your PC detects something was connected to or removed from the USB by occasionally polling the USB ports. Notice how long it takes for your PC to discover you have removed a device.
One solution (for boards that don't have native USB) can be to send something from "the other side" (serial monitor or another application) and let the Arduino check for that.