/* HID Joystick Mouse Example by: Jim Lindblom date: 1/12/2012 license: MIT License - Feel free to use this code for any purpose. No restrictions. Just keep this license if you go on to use this code in your future endeavors! Reuse and share. This is very simplistic code that allows you to turn the SparkFun Thumb Joystick (http://www.sparkfun.com/products/9032) into an HID Keyboard. Send up/down/left/right arrow keystrokes using the joystick. The select button on the joystick is set up as the 'P' (pause) button. I wrote it to play free PacMan online! http://www.freepacman.org/ */ #define KEY_RIGHT 0x4F // Right arrow #define KEY_LEFT 0x50 // Left arrow #define KEY_DOWN 0x51 // Down arrow #define KEY_UP 0x52 // Up arrow int horzPin = A0; // Analog output of horizontal joystick pin int vertPin = A1; // Analog output of vertical joystick pin int selPin = 9; // select button pin of joystick int vertZero, horzZero; // Stores the initial value of each axis, usually around 512 int vertValue, horzValue; // Stores current analog output of each axis const int threshold = 200; // Higher sensitivity value = slower mouse void sendKey(byte key, byte modifiers = 0); void setup() { pinMode(horzPin, INPUT); // Set both analog pins as inputs pinMode(vertPin, INPUT); pinMode(selPin, INPUT); // set button select pin as input digitalWrite(selPin, HIGH); // Pull button select pin high delay(1000); // short delay to let outputs settle vertZero = analogRead(vertPin); // get the initial values horzZero = analogRead(horzPin); // Joystick should be in neutral position when reading these } void loop() { vertValue = analogRead(vertPin) - vertZero; // read vertical offset horzValue = analogRead(horzPin) - horzZero; // read horizontal offset if (vertValue > threshold) sendKey(KEY_DOWN); else if (vertValue < -threshold) sendKey(KEY_UP); if (horzValue > threshold) sendKey(KEY_RIGHT); else if (horzValue < -threshold) sendKey(KEY_LEFT); if (!digitalRead(selPin)) Keyboard.write('P'); } void sendKey(byte key, byte modifiers) { KeyReport report = {0}; // Create an empty KeyReport /* First send a report with the keys and modifiers pressed */ report.keys[0] = key; // set the KeyReport to key report.modifiers = modifiers; // set the KeyReport's modifiers report.reserved = 1; Keyboard.sendReport(&report); // send the KeyReport /* Now we've got to send a report with nothing pressed */ for (int i=0; i<6; i++) report.keys[i] = 0; // clear out the keys report.modifiers = 0x00; // clear out the modifires report.reserved = 0; Keyboard.sendReport(&report); // send the empty key report }