Dear folks,
I have a problem in my project. This project builds a simple uniaxial mouse emulator by using Arduino Leonardo board and a potentiometer (pot) and a switch. My desire is to achieve X axis mouse control by using a pot. The switch here is to turn on and off the Leonardo mouse control.
My code is working OK but I have one big challenage. The mouse movement controlled by the pot can not cover the whole X range of computer screen, which, in other words, goes from the left end of screen to the right end of screen. I try to use the map syntax and find several codes that use map syntax in joystick mouse control. I post my code here and let me know where I should improve my code. Thanks a lot.
const int switchPin = 2; // switch to turn on and off mouse control
const int xAxis = A0; // joystick X axis
const int ledPin = 13; // Mouse control LED
// parameters for reading the joystick:
int range = 12; // output range of X or Y movement
int responseDelay = 5; // response delay of the mouse, in ms
int threshold = range/4; // resting threshold
int center = range/2; // resting position value
int prevXreading = 0;
int prevYreading = 0;
boolean mouseIsActive = false; // whether or not to control the mouse
int prevSwitchState = LOW; // previous switch state
void setup() {
pinMode(switchPin, INPUT); // the switch pin
pinMode(ledPin, OUTPUT); // the LED pin
// take control of the mouse:
Mouse.begin();
}
void loop() {
// read the switch:
int switchState = digitalRead(switchPin);
// if it's changed and it's high, toggle the mouse state:
if (switchState != prevSwitchState) {
if (switchState == HIGH) {
mouseIsActive = !mouseIsActive;
// turn on LED to indicate mouse state:
digitalWrite(ledPin, mouseIsActive);
}
}
// save switch state for next comparison:
prevSwitchState = switchState;
int currXreading = analogRead(xAxis);
int xReading = prevXreading - currXreading;
prevXreading = currXreading;
// if the mouse control state is active, move the mouse:
if (mouseIsActive) {
Mouse.move(xReading, 0, 0);
}
}