Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//include the third party library to manage HID
#include "HID-Project.h"
//declare understandable var to recognise button in the code, the X and Y axis of the analog joystick
const int analogJoyButton = 2;
const int joystickX = A0;
const int joystickY = A1;
int lastButtonStatus[32];
void setup() {
//define the diffent pin of the arduino as input
pinMode(analogJoyButton, INPUT_PULLUP);
pinMode(joystickX, INPUT);
pinMode(joystickY, INPUT);
//initialise the gamepad
Gamepad.begin();
}
//function that will be executed again and again and again...
void loop() {
//to keep the loop clean and understandable
//joystick management externalised to another function
//Button management externalised to another function
ButtonCheck(analogJoyButton, 1);
analogJoyAxisCheck(joystickX , joystickY);
}
void analogJoyAxisCheck(int joyX , int joyY) {
//initialise variable that will be needed
int xMap, yMap, xValue, yValue;
//read the input value of the analog joystick x and y axis
xValue = analogRead(joyX);
yValue = analogRead(joyY);
// after playing with the joystick and sending
// value in the serial bus Serial.println(xValue); and Serial.println(yValue);
// it appears that center of joystick is x:517 and y:531
// max/top y: 1023 min/bottom y :0
// max/right x: 1023 min/left x :0
//we map the scale to transform value from 0 to 1023 into something from -32765 to 32766
xMap = map(xValue, 0, 1023, -32765, 32766);
yMap = map(yValue, 0, 1023, -32765, 32766);
//once we have the matching coordinates, we can send it to the gamepad
Gamepad.xAxis(xMap);
Gamepad.yAxis(yMap);
Gamepad.write();
}
// function that check the button state
// the parameters are
// inputNB => the pin nb of the button of the analog joystick
// gamepadButtonNb => which gamepad number will be pressed when the analog joystick is pressed
void ButtonCheck(int inputNb, int gamepadButtonNb) {
//we check and store the button status
int ButtonVal = digitalRead(inputNb);
// if the button state have changed, it means the user pressed or released the physical button
if (ButtonVal != lastButtonStatus[inputNb]) {
// if the status is LOW, it means the user pressed the physical push button
// remember, the INPUT_PULLUP invert the value
if (ButtonVal == LOW) {
//don't forget to update the last status of the button
lastButtonStatus[inputNb] = LOW;
//and then we "press" the gamepad button
Gamepad.press(gamepadButtonNb);
Gamepad.write();
}
else { // if the input is HIGH, it means the user released the physical push button
//don't forget to update the last status of the button
lastButtonStatus[inputNb] = HIGH;
//and then we "release" the gamepad button
Gamepad.release(gamepadButtonNb);
Gamepad.write();
}
}
}