Here is what the code would look like:
#include <Arduino.h>
#include <USBAPI.h>
#define KEY_1 5 // Key 1 pin definition
#define KEY_2 6 // Key 2 pin definition
#define KEY_3 7 // Key 3 pin definition
// USB keyboard key mapping for arrow keys
#define KEY_RIGHT 79
#define KEY_LEFT 80
#define KEY_DOWN 81
#define KEY_UP 82
#define KEY_ENTER 40
#define LED_PIN 13
Up to this point, we have just declared a few constants. KEY_i (i=1,2,3) defines the digital inputs to read the push-buttons. Where as the KEY_x (x=RIGHT, LEFT, ...), define the USB keys for up, down, left and right.
void setup()
{
// Initialise hardware
pinMode ( LED_PIN, OUTPUT );
pinMode ( KEY_1, INPUT );
pinMode ( KEY_2, INPUT );
pinMode ( KEY_3, INPUT );
}
Here you just define your pushbuttons as digital inputs.
void loop()
{
KeyReport keys = {0}; // KeyReport
bool keyPressed = false;
static ledState = 0;
digitalWrite ( LED_PIN, ledState );
ledState ^= 1;
if ( digitalRead ( KEY_1 ) )
{
keys.keys[0] = KEY_UP;
keyPressed = true;
}
if ( digitalRead ( KEY_2 ) )
{
keys.keys[0] = KEY_DOWN;
keyPressed = true;
}
if ( digitalRead ( KEY_3 ) )
{
keys.keys[0] = KEY_ENTER;
keyPressed = true;
}
if ( keyPressed )
{
Keyboard.sendReport(&keys);
}
delay ( 100 );
}
What this code does, is to read the state of the input, here we have assumed that you have a pull-down (when the button is not pressed you will be reading LOW and when the button is pressed you will read a HIGH) resistor on your push-button (schematic attached).
The main loop, blinks the LED, and then goes through each digital input to see what its state is. If the state is HIGH, it will set the variable "keys" to the mapped USB arrow key. The program will then send "Keyboard.sendReport (&key);" the USB key (as if it were your keyboard) to the computer.
That is all to it. You can see it is very easy what you are trying to do with an AVR like the ATMega32U4 and the Arduino IDE or even some libraries out there.
WARNING - 1 - the program is over simplistic here, it will only send 1 key event at the time, so if you have more than one button pressed it will only send one of them (bottom up order in the code). You will have to add some logic to debounce the key press. In the code here I have added a 100ms delay but there are other ways to do it.
WARNING - 2 - the Keyboard.sendReport, is not public in the Keyboard class (variable), so you will have to go into the distribution and move the sendReport method from where it says private, to public, in the USBAPI.h file. I may write an HID extension over the weekend.