|
0
|
1 #if defined(ARDUINO) && ARDUINO >= 100
|
|
|
2 #include "Arduino.h"
|
|
|
3 #else
|
|
|
4 #include "WProgram.h"
|
|
|
5 #endif
|
|
|
6
|
|
|
7 #include "Joystick.h"
|
|
|
8
|
|
|
9
|
|
|
10 /**
|
|
|
11 see Joystick.h for description.
|
|
|
12 */
|
|
|
13
|
|
|
14 Joystick::Joystick() {}
|
|
|
15
|
|
|
16 /**
|
|
|
17 setup joystick instance
|
|
|
18
|
|
|
19 @param {byte} pinX input pin for x axis
|
|
|
20 @param {byte} pinY input pin for y axis
|
|
|
21 @param {byte} pinB input pin for button
|
|
|
22 */
|
|
|
23 void Joystick::setup(byte pinX, byte pinY, byte pinB) {
|
|
|
24 this->setup(pinX, pinY, pinB, true);
|
|
|
25 }
|
|
|
26
|
|
|
27
|
|
|
28 /**
|
|
|
29 setup joystick instance
|
|
|
30
|
|
|
31 @param {byte} pinX input pin for x axis
|
|
|
32 @param {byte} pinY input pin for y axis
|
|
|
33 @param {byte} pinB input pin for button
|
|
|
34 @param {bool} flipY mirror y axis output
|
|
|
35 */
|
|
|
36 void Joystick::setup(byte pinX, byte pinY, byte pinB, bool flipY) {
|
|
|
37 this->x.setup(pinX);
|
|
|
38 this->y.setup(pinY);
|
|
|
39 this->b.setup(pinB, true);
|
|
|
40 this->centerX = 512;
|
|
|
41 this->centerY = 512;
|
|
|
42 this->flipY = flipY;
|
|
|
43 }
|
|
|
44
|
|
|
45
|
|
|
46 void Joystick::update() {
|
|
|
47 this->update(millis());
|
|
|
48 }
|
|
|
49
|
|
|
50
|
|
|
51 void Joystick::update(unsigned long ms) {
|
|
|
52 this->x.update(ms);
|
|
|
53 this->y.update(ms);
|
|
|
54 this->b.update(ms);
|
|
|
55 float vx = 0;
|
|
|
56 float vy = 0;
|
|
|
57 // if not calibrated yet, and stick is stopped within the center deadzone,
|
|
|
58 // auto-calibrate to that point
|
|
|
59 if(!this->isCalibrated) {
|
|
|
60 bool inDeadzone = abs(512-this->x.value) < Joystick::CENTER_DEADZONE &&
|
|
|
61 abs(512-this->y.value) < Joystick::CENTER_DEADZONE;
|
|
|
62 if(inDeadzone) {
|
|
|
63 if(this->x.isStopped && this->y.isStopped) {
|
|
|
64 this->isCalibrated = true;
|
|
|
65 this->centerX = this->x.value;
|
|
|
66 this->centerY = this->y.value;
|
|
|
67 #ifdef DEBUG
|
|
|
68 Serial.print("Joystick calibrated, center=");
|
|
|
69 Serial.print(this->centerX);
|
|
|
70 Serial.print(",");
|
|
|
71 Serial.println(this->centerY);
|
|
|
72 #endif
|
|
|
73 }
|
|
|
74 else return;
|
|
|
75 }
|
|
|
76 }
|
|
|
77 vx = this->x.value - this->centerX;
|
|
|
78 if(vx < 0)
|
|
|
79 this->vx = vx*100/this->centerX;
|
|
|
80 else
|
|
|
81 this->vx = vx*100/(1023-this->centerX);
|
|
|
82 vy = this->y.value - this->centerY;
|
|
|
83 if(vy < 0)
|
|
|
84 this->vy = vy*100/this->centerY;
|
|
|
85 else
|
|
|
86 this->vy = vy*100/(1023-this->centerY);
|
|
|
87 // flip vy to cartesian logic
|
|
|
88 if(this->flipY)
|
|
|
89 this->vy = -this->vy;
|
|
|
90 }
|
|
|
91
|
|
|
92
|
|
|
93
|