Detecting USB connected

Status
Not open for further replies.

Fluxanode

Well-known member
Using a self powered teensy 3.x, is there a way for the teensy to detect when a USB connection to a PC has been made and then branch to code to handle that event?

Thanks.
 
This is what I use on 3.2

Code:
void loop()  {
    Serial.println("USB Status: ");
    while(1)  {
        if(USB_Status()==0)  {  Serial.println("  NONE"); }
        if(USB_Status()==1)  {  Serial.println("  USB"); }
        if(USB_Status()==2)  {  Serial.println("  USB + SERIAL"); }
        delay(500);
   }
}

byte USB_Status() {   
  // Checks for USB or USB Serial connection
  // Returns :
  //     0 = No USB data connection 
  //     1 = USB cable detected
  //     2 = USB cable detected + USB Serial detected (for example, Serial Monitor was opened on assigned COM port)
  // Note: Only identifies initial USB connection. Will NOT detect if USB is later disconnected. 
  //          Will continue to return TRUE if USB cable is later unplugged
    if(!usb_configuration)  { return 0; }       //usb_configured();
    if(!Serial) { return 1; }
    return 2;
}
 
@ ratnin, thanks.

I do need to know also when it has been disconnected...

Can the usb_status be reran to check if cable removed?
 
Status
Not open for further replies.
Back
Top