controlling the mouse with arduino
Using the arduino to control a game with wii nunchuck
code:
#include <Wire.h>
#include <ArduinoNunchuk.h>
#define BAUDRATE 19200
ArduinoNunchuk nunchuk = ArduinoNunchuk();
const int xAxis = A5; // joystick X axis
const int yAxis = A4; // joystick Y axis
// parameters for reading the joystick:
int range = 40; // output range of X or Y movement
int responseDelay = 20; // response delay of the mouse, in ms
int threshold = range/4; // resting threshold
int center = range/2; // resting position value
void setup() {
Serial.begin(BAUDRATE);
nunchuk.init();
delay(20000);
Mouse.begin();
Keyboard.begin();
}
void loop() {
nunchuk.update();
//int xReading = readAxis(A5);
// int yReading = readAxis(A4);
if (nunchuk.analogX<128)
{
Keyboard.release('d');
Keyboard.press('a');//left
}
if (nunchuk.analogX>128)
{
Keyboard.release('a');
Keyboard.press('d');//left
}
if (nunchuk.analogY>128)
{
Keyboard.release('s');
Keyboard.press('w');//left
}
if (nunchuk.analogY<128)
{
Keyboard.release('w');
Keyboard.press('s');//left
}
if (nunchuk.analogX==128)
{
Keyboard.release('a');
Keyboard.release('d');
}
if (nunchuk.analogY==128)
{
Keyboard.release('w');
Keyboard.release('s');
}
if (nunchuk.zButton)
{
Keyboard.press('q');
delay(10);
Keyboard.release('q');
}
if (nunchuk.cButton)
{
Keyboard.press('e');
delay(10);
Keyboard.release('e');
}
//Mouse.move(readAxisx(nunchuk.analogX), readAxisy(nunchuk.analogY), 0);
}
/*
reads an axis (0 or 1 for x or y) and scales the
analog input range to a range from 0 to <range>
*/
int readAxisx(int thisAxis) {
// read the analog input:
//int reading = analogRead(thisAxis);
// map the reading from the analog input range to the output range:
int reading = map(thisAxis, 0, 255, 0, range);
// if the output reading is outside from the
// rest position threshold, use it:
int distance = reading - center;
if (abs(distance) < threshold) {
distance = 0;
}
// return the distance for this axis:
return distance;
}
int readAxisy(int thisAxis) {
// read the analog input:
//int reading = analogRead(thisAxis);
// map the reading from the analog input range to the output range:
int reading = map(thisAxis, 255, 0, 0, range);
// if the output reading is outside from the
// rest position threshold, use it:
int distance = reading - center;
if (abs(distance) < threshold) {
distance = 0;
}
// return the distance for this axis:
return distance;
}