How to detect USB connected

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.

Suggestions? TIA

When the project is powered externally what voltage do you use and how is the power input connected to the Arduino ?

Which Arduino board are you using ?

I have a variety of boards, UNO R2, R4, Megas etc so usually 12v sometimes 24V connected through the power jack.

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

I could resort to an analog input as you suggest, but I'm still hoping for a method in software.

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.

const uint8_t ledPin = LED_BUILTIN;

void setup()
{
  Serial.begin(115200);
  digitalWrite(ledPin, LOW);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  if (Serial.available())
  {
    char ch = Serial.read();
    digitalWrite(ledPin, HIGH);
  }
}

The onboard LED will indicate if data was received indicating a connection.

You can add a timeout so this is e.g. only valid for 5 seconds after which the code expects a character again.

For boards with native USB you can use if(Serial) in loop() to pick up of a communication channel is established.

const uint8_t ledPin = LED_BUILTIN;

void setup()
{
  Serial.begin(115200);
  digitalWrite(ledPin, LOW);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  if (Serial)
  {
    digitalWrite(ledPin, HIGH);
  }
  else
  {
    digitalWrite(ledPin, LOW);

  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.