| 1 |
/* |
| 2 |
ButtonMouseControl |
| 3 |
|
| 4 |
For Leonardo and Due boards only. |
| 5 |
|
| 6 |
Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due. |
| 7 |
|
| 8 |
Hardware: |
| 9 |
- five pushbuttons attached to D2, D3, D4, D5, D6 |
| 10 |
|
| 11 |
The mouse movement is always relative. This sketch reads four pushbuttons, |
| 12 |
and uses them to set the movement of the mouse. |
| 13 |
|
| 14 |
WARNING: When you use the Mouse.move() command, the Arduino takes over your |
| 15 |
mouse! Make sure you have control before you use the mouse commands. |
| 16 |
|
| 17 |
created 15 Mar 2012 |
| 18 |
modified 27 Mar 2012 |
| 19 |
by Tom Igoe |
| 20 |
|
| 21 |
This example code is in the public domain. |
| 22 |
|
| 23 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/ButtonMouseControl |
| 24 |
*/ |
| 25 |
|
| 26 |
#include "Mouse.h" |
| 27 |
|
| 28 |
// set pin numbers for the five buttons: |
| 29 |
const int upButton = 2; |
| 30 |
const int downButton = 3; |
| 31 |
const int leftButton = 4; |
| 32 |
const int rightButton = 5; |
| 33 |
const int mouseButton = 6; |
| 34 |
|
| 35 |
int range = 5; // output range of X or Y movement; affects movement speed |
| 36 |
int responseDelay = 10; // response delay of the mouse, in ms |
| 37 |
|
| 38 |
|
| 39 |
void setup() { |
| 40 |
// initialize the buttons' inputs: |
| 41 |
pinMode(upButton, INPUT); |
| 42 |
pinMode(downButton, INPUT); |
| 43 |
pinMode(leftButton, INPUT); |
| 44 |
pinMode(rightButton, INPUT); |
| 45 |
pinMode(mouseButton, INPUT); |
| 46 |
// initialize mouse control: |
| 47 |
Mouse.begin(); |
| 48 |
} |
| 49 |
|
| 50 |
void loop() { |
| 51 |
// read the buttons: |
| 52 |
int upState = digitalRead(upButton); |
| 53 |
int downState = digitalRead(downButton); |
| 54 |
int rightState = digitalRead(rightButton); |
| 55 |
int leftState = digitalRead(leftButton); |
| 56 |
int clickState = digitalRead(mouseButton); |
| 57 |
|
| 58 |
// calculate the movement distance based on the button states: |
| 59 |
int xDistance = (leftState - rightState) * range; |
| 60 |
int yDistance = (upState - downState) * range; |
| 61 |
|
| 62 |
// if X or Y is non-zero, move: |
| 63 |
if ((xDistance != 0) || (yDistance != 0)) { |
| 64 |
Mouse.move(xDistance, yDistance, 0); |
| 65 |
} |
| 66 |
|
| 67 |
// if the mouse button is pressed: |
| 68 |
if (clickState == HIGH) { |
| 69 |
// if the mouse is not pressed, press it: |
| 70 |
if (!Mouse.isPressed(MOUSE_LEFT)) { |
| 71 |
Mouse.press(MOUSE_LEFT); |
| 72 |
} |
| 73 |
} |
| 74 |
// else the mouse button is not pressed: |
| 75 |
else { |
| 76 |
// if the mouse is pressed, release it: |
| 77 |
if (Mouse.isPressed(MOUSE_LEFT)) { |
| 78 |
Mouse.release(MOUSE_LEFT); |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
// a delay so the mouse doesn't move too fast: |
| 83 |
delay(responseDelay); |
| 84 |
} |