USB keyboard and mouse fails unless a serial connection is made

Status
Not open for further replies.

blackketter

Well-known member
I have a previously reliable app that does USB keyboard and mouse and serial.

I just discovered that the mouse and keyboard events disappear unless I connect to the serial USB device. Connect to the serial port via a terminal, works great. Disconnect, the mouse and keyboard events disappear.

Weird. I can't imagine what changed and I can't start adding debugging messages to the serial port because connecting to it makes it work! Seems to be the case on both Linux and Mac.

Any suggestions on what might be going on?
 
Good question. Not much has changed in that code for quite a long time.

If you post a test program and tell me which Teensy and which operating system, I could give it a try here.
 
Hm, I got lucky and found it quickly. Seems that frequent calls to Serial.flush() can mess up HID devices. Try this:

Code:
#include <Arduino.h>

void setup() { } // no setup needed
void loop() {
  static int i = 100;
  i--;
  if (i<1) {
    Mouse.move(-20, -10);
    Mouse.move(20, 10);
    Serial.write('.');
    i=100;
  }
  Serial.flush();
}

If you don't connect to the serial, the mouse doesn't move. When you do, it jiggles as expected.

Take out the flush(), it works fine.

Note that in my real application, there's not nearly that much mouse, keyboard, or serial activity. But the flush() call every iteration through loop() somehow sets it off. And it just started happening suddenly, not sure why.

I'm building an interactive console using Serial, so I do want to flush periodically, but I can probably dial it back.
 
I've put this on my list of issues to investigate.

My gut feeling is this may be a case of both competing for USB packet buffers. But they they're supposed to wait, so maybe that's not it? It'll take me a while to get to this, but it's on my list so I won't forget.
 
Thanks, Paul.

I noticed that usb_serial.h has this note, which might be relevant:

virtual void flush() { usb_serial_flush_output(); } // TODO: actually wait for data to leave USB...

Taking out the calls to flush() has the side effect of showing some old buffered data written to Serial when I open the terminal. It's not the most recent data either, which is weird.
 
Status
Not open for further replies.
Back
Top