skip navigational linksPJRC
Shopping Cart Checkout Shipping Cost Download Website
Home MP3 Player 8051 Tools All Projects PJRC Store Site Map
You are here: Teensy Teensyduino USB Mouse Search PJRC

PJRC Store
Teensy, $18
Teensy Pins, $21
Teensy++, $24
Teensy++ Pins, $27
USB Cable, $4
Teensy
Main Page
Getting Started
How-To Tips
Code Library
Projects
Teensyduino
Reference

Using USB Mouse

When you select "USB Keyboard/Mouse" from the Tools->Boards menu, the Teensy becomes a USB keyboard and mouse while running your program.

Mouse interaction is obviously limited because the Teensy can not view the screen. Nonetheless, you can send mouse actions, which might be useful for some types of projects.

Moving The Mouse

To move the mouse, use Mouse.move(X, Y), where X and Y range from -127 to +127. Positive X moves to the right. Positive Y moves downwards. For natural looking motion, many small moves performed slowly are needed.

Here is a simple example that moves the mouse in a triangle.

void setup() { } // no setup needed
void loop() {
  int i;
  for (i=0; i<40; i++) {
    Mouse.move(2, -1);
    delay(25);
  }
  for (i=0; i<40; i++) {
    Mouse.move(2, 2);
    delay(25);
  }
  for (i=0; i<40; i++) {
    Mouse.move(-4, -1);
    delay(25);
  }
}
TODO: video demonstration

Clicking

For a simple mouse click, just use Mouse.click(). Use with caution!
  Mouse.click();

For more control over the 3 mouse buttons, you can use Mouse.set_buttons(LEFT, MIDDLE, RIGHT). For each input, 1 means the button is pressed, 0 means not pressed.

  Mouse.set_buttons(0, 0, 1);
  Mouse.set_buttons(0, 0, 0);

Click and Drag

You can combine Mouse.move() with Mouse.set_buttons() to perform drag and drop operations.

  Mouse.set_buttons(1, 0, 0);  // hold left button
  Mouse.move(-30, 10);         // move the mouse while holding
  delay(500);
  Mouse.set_buttons(0, 0, 0);  // release button after move

Of course, how to position the mouse and where to move are tricky. You may also need to add substantial delay before the Mouse.set_buttons() call, because many GUI-based programs feature delayed respose, anticipating human-like timing.

Scroll Wheel

You can also control the scroll wheel. Positive numbers scroll upward; negative numbers scroll downward.

  Mouse.scroll(-3);