"while (!Serial);" USB Disconnect Issue

duff

Well-known member
This issue is if you externally power your Teensy and cut the trace for the usb power.

Compile (USB Serial) and upload the sketch below, open the Arduino Serial Monitor (leave it open) and disconnect the USB cable you will notice that the Teensy keeps blinking when it should stop because of the "while(!Serial);" part of the code. If you just open and close the Serial Monitor with a valid USB cable connected the blinking will stop as expected.

When disconnecting the USB cable the SLEEP status bit gets set for the USB isr to handle. I think this is the where CDC_SET_CONTROL_LINE_STATE needs to be reinitialized to its default values.

Code:
const int ledPin = 13;


void setup() {
  pinMode(ledPin, OUTPUT);
}


void loop() {
  while(!Serial);
  Serial.println("HI");
  digitalWrite(ledPin, HIGH);
  delay(100);
  digitalWrite(ledPin, LOW); 
  delay(100);
}
 
Paul, I think I have a solution for this in which you add this code to the USB ISR's SLEEP code:
Code:
[COLOR=#000000][FONT=Menlo][COLOR=#ba2da2]if[/COLOR] ((status & USB_ISTAT_SLEEP [COLOR=#008400]/* 10 */[/COLOR] )) {[/FONT][/COLOR]
[COLOR=#000000][FONT=Menlo]    USB0_ISTAT = USB_ISTAT_SLEEP;
[COLOR=#FF0000]    usb_cdc_line_rtsdtr = setup.wValue;[/COLOR][/FONT][/COLOR]
[COLOR=#000000][FONT=Menlo][COLOR=#ff0000]    usb_cdc_line_rtsdtr_millis = systick_millis_count;[/COLOR][/FONT][/COLOR]
[COLOR=#000000][FONT=Menlo]}[/FONT][/COLOR]
So when you unplug the USB from the Teensy the SLEEP status bit is set and the code above runs. Sometimes the ERROR bit gets set but the SLEEP bit always proceeds this so this is where I think the code should go.

This works perfect from my tests and I will send a PULL unless you think there is better solution. Even though this bug effects only small amount of people I know I have wanted to use the "while(!Serial)" in my loop code before to detect USB state while the Serial Connection is open. I hope you have time to look at this.
 
Huh, did I just wasted a night of hacking on this? This is a bug, if you try the code I posted and follow the steps i outlined but whatever.
 
I've made a first beta release of an ambitious redesign of the Arduino serial monitor and ports menu. It's meant to solve these long-standing issues.

https://forum.pjrc.com/threads/49831-Teensyduino-1-42-Beta-1

If you're still watching this thread and experiencing this problem, please give this latest beta a try. It's still a bit rough around the edges, as you can see from the known issues list. But it does already solve some of these problems, and my hope is to be able to fix every long-standing serial issue by the 1.42 release. Some of these problems only happen on certain computers or with specific setups, so I'm really depending on feedback.
 
Back
Top