-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArduino_BMS_Control_As_Gamepad.ino
113 lines (100 loc) · 2.09 KB
/
Arduino_BMS_Control_As_Gamepad.ino
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "HID-Project.h"
#define INT16_MAX 32767
#define INT16_MIN -32768
//common
unsigned long elapsed = 0;
//scratch
const unsigned long ACTIVE_TIME = 150000; //us
const int THRESHOLD = 750;
const int THRES_LOW = 850;
const int THRES_HIGH = 650;
long scrTimer = 0;
bool toRight;
int d1f, d2f;
int list[8][4] = {
{1, 1, 0, 1},
{1, 0, 1, 1},
{0, 0, 1, 0},
{0, 1, 0, 0},
{1, 1, 1, 0},
{1, 0, 0, 0},
{0, 1, 1, 1},
{0, 0, 0, 1}
};
//keys
const unsigned long INTERVAL = 10000; //minimum input interval in us
unsigned long ptime[9];
void setup() {
//common
Gamepad.begin();
for (int i = 2; i < 11; i++){ //set pinmode
pinMode(i, INPUT_PULLUP);
}
elapsed = micros();
//scratch
toRight = false;
d1f = analogRead(A1) < THRESHOLD ? 0 : 1;
d2f = analogRead(A2) < THRESHOLD ? 0 : 1;
//keys
for (int i = 0; i < 9; i++){
ptime[i] = 0;
}
}
void loop() {
//common
unsigned long now = micros();
if (now < elapsed) { //overflow!
elapsed = now;
return;
}
long tdif = now - elapsed;
elapsed = now;
//scratch
int d1l, d2l;
int thres1 = d1f == 0 ? THRES_LOW : THRES_HIGH;
int thres2 = d2f == 0 ? THRES_LOW : THRES_HIGH;
d1l = analogRead(A1) < thres1 ? 0 : 1;
d2l = analogRead(A2) < thres2 ? 0 : 1;
bool triggered = false;
int state[4] = {d1f, d1l, d2f, d2l};
for (int i = 0; i < 8; i++) {
if (memcmp(list[i], state, sizeof(int) * 4) == 0) { //compare
scrTimer = ACTIVE_TIME;
triggered = true;
toRight = i < 4;
break;
}
}
if (!triggered) {
scrTimer -= tdif;
}
if (scrTimer > 0) {
if (toRight) {
//Right Turn
Gamepad.xAxis(INT16_MAX);
} else {
//Left Turn
Gamepad.xAxis(INT16_MIN);
}
} else {
//No Input
scrTimer = 0;
Gamepad.xAxis(0);
}
d1f = d1l;
d2f = d2l;
//keys
for (int i = 0; i < 9; i++) {
ptime[i] = min(ptime[i] + tdif, INTERVAL);
if (!digitalRead(i + 2)) {
Gamepad.press(i + 1);
ptime[i] = 0;
} else {
if (ptime[i] < INTERVAL){ //burst!
continue;
}
Gamepad.release(i + 1);
}
}
Gamepad.write();
}