|
| 1 | +/* HID Joystick Mouse Example |
| 2 | + by: Jim Lindblom |
| 3 | + date: 1/12/2012 |
| 4 | + license: MIT License - Feel free to use this code for any purpose. |
| 5 | + No restrictions. Just keep this license if you go on to use this |
| 6 | + code in your future endeavors! Reuse and share. |
| 7 | +
|
| 8 | + This is very simplistic code that allows you to turn the |
| 9 | + SparkFun Thumb Joystick (http://www.sparkfun.com/products/9032) |
| 10 | + into an HID Mouse. The select button on the joystick is set up |
| 11 | + as the mouse left click. |
| 12 | + */ |
| 13 | +#include <Mouse.h> |
| 14 | +int horzPin = A0; // Analog output of horizontal joystick pin |
| 15 | +int vertPin = A1; // Analog output of vertical joystick pin |
| 16 | +int selPin = 9; // select button pin of joystick |
| 17 | + |
| 18 | +int vertZero, horzZero; // Stores the initial value of each axis, usually around 512 |
| 19 | +int vertValue, horzValue; // Stores current analog output of each axis |
| 20 | +const int sensitivity = 200; // Higher sensitivity value = slower mouse, should be <= about 500 |
| 21 | +int mouseClickFlag = 0; |
| 22 | + |
| 23 | +void setup() |
| 24 | +{ |
| 25 | + pinMode(horzPin, INPUT); // Set both analog pins as inputs |
| 26 | + pinMode(vertPin, INPUT); |
| 27 | + pinMode(selPin, INPUT); // set button select pin as input |
| 28 | + digitalWrite(selPin, HIGH); // Pull button select pin high |
| 29 | + delay(1000); // short delay to let outputs settle |
| 30 | + vertZero = analogRead(vertPin); // get the initial values |
| 31 | + horzZero = analogRead(horzPin); // Joystick should be in neutral position when reading these |
| 32 | + |
| 33 | +} |
| 34 | + |
| 35 | +void loop() |
| 36 | +{ |
| 37 | + vertValue = analogRead(vertPin) - vertZero; // read vertical offset |
| 38 | + horzValue = analogRead(horzPin) - horzZero; // read horizontal offset |
| 39 | + |
| 40 | + if (vertValue != 0) |
| 41 | + Mouse.move(0, vertValue/sensitivity, 0); // move mouse on y axis |
| 42 | + if (horzValue != 0) |
| 43 | + Mouse.move(horzValue/sensitivity, 0, 0); // move mouse on x axis |
| 44 | + |
| 45 | + if ((digitalRead(selPin) == 0) && (!mouseClickFlag)) // if the joystick button is pressed |
| 46 | + { |
| 47 | + mouseClickFlag = 1; |
| 48 | + Mouse.press(MOUSE_LEFT); // click the left button down |
| 49 | + } |
| 50 | + else if ((digitalRead(selPin))&&(mouseClickFlag)) // if the joystick button is not pressed |
| 51 | + { |
| 52 | + mouseClickFlag = 0; |
| 53 | + Mouse.release(MOUSE_LEFT); // release the left button |
| 54 | + } |
| 55 | +} |
0 commit comments