Automate Key Presses With Arduino

From Squirrel's Lair
Jump to navigation Jump to search

  • Cargo:

  • Categories:
  • Default form

There are libraries for Arduino that will let you use any 32u4 or SAMD-based Arduino (Leonardo, Pro Micro, etc) as a keyboard and/or mouse device, and it's simple to use.

Say you're need to wiggle and left-click your mouse every five minutes for some reason. This would do the trick:


void loop(){
    Mouse.move(-20, 5, 0);    // Move the mouse -20 on the X-axis, +5 on the Y-axis, and 0 on the mouse wheel
    delay(50);    // Delay 50ms
    Mouse.move(20, -5, 0);    // Move the mouse +20 on the X-axis, -5 on the Y-axis, and 0 on the mouse wheel;    // Left-click (press and release) the left mouse button
    delay(300000);    // Delay 300 seconds (5 minutes)

If you wanted to hit the escape key once every minute, you could use this:


void loop(){;    // Press and hold the ESC key
    delay(50);    // Wait 50ms
    Keyboard.releaseAll();    // Release any keys that are "pressed"
    delay(60000);    // Wait 60 seconds

You can even use both libraries at the same time to simulate almost any combination of keyboard and mouse movement, but be careful of how much RAM your program uses.

This is a simple, quick way to simplify one-way communication between an Arduino and a computer with USB ports. We've used it successfully in several projects that sent keystrokes to a host computer based on the state of several inputs (like Hall sensors, buttons, and IR transmitters). It is not appropriate for projects where sensitive information is sent, since the Arduino will happily talk to any computer it's plugged into. No passwords!

Note that this will not work with any Arduino boards that are not built around the 32u4 or SAMD chips (like the ATMega2560 or 328p).

You can find more information about this at the Arduino Keyboard library and Mouse library pages.