Hardware Reference
In-Depth Information
}
//Read a button and issue a mouse command
void readButton(int pin, char mouseCommand)
{
//If button is depressed, click if it hasn't already been clicked
if (digitalRead(pin) == HIGH)
{
if (!Mouse.isPressed(mouseCommand))
{
Mouse.press(mouseCommand);
}
}
//Release the mouse if it has been clicked.
else
{
if (Mouse.isPressed(mouseCommand))
{
Mouse.release(mouseCommand);
}
}
}
This is definitely one of the more complicated sketches that have been covered
so far, so it's worth stepping through it to both understand the newly introduced
functions and the program flow used to make the joystick mouse.
Each of the button and joystick pins are defined at the top of the sketch, and
the mouse library is started in the setup. Each time through the loop, the joystick
values are read and mapped to movement values for the mouse. The mouse
buttons are also monitored and the button presses are transmitted if necessary.
A readJoystick() function was created to read the joystick values and map
them. Each joystick axis has a range of 1024 values when read into the analog-to-
digital converter (ADC). However, mouse motions are relative. In other words,
passing a value of 0 to Mouse.move() for each axis will result in no movement
on that axis. Passing a positive value for the x-axis will move the mouse to the
right, and a negative value will move it to the left. The larger the value, the
more the mouse will move. Hence, in the readJoystick() function, a value of
0 to 1023 is mapped to a value of -10 to 10 . A small buffer value around 0 is
added where the mouse will not move. This is because even while the joystick
is in the middle position, the actual value may fluctuate around 512 . By setting
the desired distance back to 0 after being mapped within a certain range, you
guarantee that the mouse will not move on its own while the joystick is not being
actuated. Once the values are ascertained, Mouse.move() is given the x and y
values to move the mouse. A third argument for Mouse.move() determines the
movement of the scroll wheel.
Search WWH ::




Custom Search