Code

The libraries are located at our github repository https://github.com/adafruit/Adafruit-Trinket-USB/ . You can also just click the button below to download the ZIP file which contains both the Keyboard and Mouse libraries. Install these as ordinary Arduino libraries (see http://arduino.cc/en/Guide/Libraries or our tutorial on Arduino libraries). Keep in mind that this library is designed specifically for Trinket. (although they can be modified to work with other platforms)

The example code is really straightforward. The button pins are initialized as inputs with internal pull-up resistors enabled. The USB functionality starts with TrinketKeyboard.begin();, and then the loop will poll the buttons. If the button on pin #0 is pressed, the keyboard will type out 'A' until the button is released. If the button on pin #2 is pressed, the keyboard will type out "Hello World!" until the button is released.
/*
TrinketKeyboard example
For Trinket by Adafruit Industries
*/

#include <TrinketKeyboard.h>

#define PIN_BUTTON_CAPITAL_A 0
#define PIN_BUTTON_STRING    2

void setup()
{
  // button pins as inputs
  pinMode(PIN_BUTTON_CAPITAL_A, INPUT);
  pinMode(PIN_BUTTON_STRING, INPUT);

  // setting input pins to high means turning on internal pull-up resistors
  digitalWrite(PIN_BUTTON_CAPITAL_A, HIGH);
  digitalWrite(PIN_BUTTON_STRING, HIGH);
  // remember, the buttons are active-low, they read LOW when they are not pressed

  // start USB stuff
  TrinketKeyboard.begin();
}

void loop()
{
  // the poll function must be called at least once every 10 ms
  // or cause a keystroke
  // if it is not, then the computer may think that the device
  // has stopped working, and give errors
  TrinketKeyboard.poll();

  if (digitalRead(PIN_BUTTON_CAPITAL_A) == LOW)
  {
    // this should type a capital A
    TrinketKeyboard.pressKey(KEYCODE_MOD_LEFT_SHIFT, KEYCODE_A);
    // this releases the key (otherwise it is held down!)
    TrinketKeyboard.pressKey(0, 0);
  }

  if (digitalRead(PIN_BUTTON_STRING) == LOW)
  {
    // type out a string using the Print class
    TrinketKeyboard.print("Hello World!");
  }
}
If you need some more debouncing, add a delay(3); line after the TrinketKeyboard.poll(); line
Last updated on 2015-05-04 at 04.27.10 PM Published on 2013-09-27 at 11.22.33 AM