Arduino: Incoming USB serial data when USB is disabled hoses the connection

811 Views Asked by At

I'm writing a sketch for an Arduino Leonardo that occasionally needs to communicate bidirectionally via USB serial, and also needs to be power efficient. To save power I'd like to disable the USB when it's not needed. I can successfully use power_usb_disable() and power_usb_enable() to do this, BUT only if no data is sent to the Arduino when USB is disabled.

Here's how to reproduce the problem: I run the following sketch on the Leonardo while it's connected to a serial comms program on my computer (I've tried the Arduino serial monitor and Minicom in Linux and PuTTY in Windows). It works as expected, printing out the messages, until I type something right after the "Disabling USB..." message. Once I do that, I will receive no further data from the Leo. The funny thing is, the TX and RX LEDs continue to blink as if everything is fine. The only way to get the connection working again is to reset the board.

Now, I don't really care about dropping the incoming data when USB is disabled, that's to be expected...but I would like the serial connection to continue to work correctly once USB is enabled again.

I don't know enough about how USB serial works to know how to troubleshoot this.

#include <avr/power.h>

void setup() {
  Serial.begin(9600);
  delay(3000);
}

void loop() {
  Serial.println("USB is enabled!");
  delay(1000);

  // If I send characters here, everything is fine.

  Serial.println("Disabling USB...");
  delay(25);
  power_usb_disable();
  delay(1000);

  // If I send characters here, it hoses the USB connection somehow.

  power_usb_enable();
  delay(25);
}
1

There are 1 best solutions below

0
On

I guess for now the best answer to this problem is "don't do that." I can arrange not to disable the USB if the connection is open, using the "if (Serial)" thing. So if somebody has a serial monitor open and looks as if they're about to type something, I leave USB enabled. Seems to work OK, although it doesn't address the underlying general question of how to robustly disable and re-enable USB from any state it might be in. I would still love to hear expert advice on that.