blob: 90baf32e71a5443e6a4a8c91d781a6f54e9a72d0 [file] [log] [blame]
Tyler Chatowc8012ca2019-02-18 22:33:01 -08001#include <cmath>
2
3#include "frc971/zeroing/wrap.h"
Tyler Chatowd28951f2019-02-16 20:12:28 -08004#include "y2019/joystick_angle.h"
5
6namespace y2019 {
7namespace input {
8namespace joysticks {
9
Tyler Chatowc8012ca2019-02-18 22:33:01 -080010using ::frc971::zeroing::Wrap;
11
12bool AngleCloseTo(double angle, double near, double range) {
13 double wrapped_angle = Wrap(near, angle, 2 * M_PI);
14
15 return ::std::abs(wrapped_angle - near) < range;
16}
17
Tyler Chatowd28951f2019-02-16 20:12:28 -080018JoystickAngle GetJoystickPosition(const JoystickAxis &x_axis,
19 const JoystickAxis &y_axis,
20 const Data &data) {
21 return GetJoystickPosition(data.GetAxis(x_axis), data.GetAxis(y_axis));
22}
23
24JoystickAngle GetJoystickPosition(float x_axis, float y_axis) {
Tyler Chatowc8012ca2019-02-18 22:33:01 -080025 const float magnitude = hypot(x_axis, y_axis);
26
27 if (magnitude < 0.5) {
28 return JoystickAngle::kDefault;
Tyler Chatowd28951f2019-02-16 20:12:28 -080029 }
Tyler Chatowc8012ca2019-02-18 22:33:01 -080030
31 double angle = atan2(y_axis, x_axis);
32
33 if (AngleCloseTo(angle, M_PI / 3, M_PI / 6)) {
34 return JoystickAngle::kUpperRight;
35 } else if (AngleCloseTo(angle, 2 * M_PI / 3, M_PI / 6)) {
36 return JoystickAngle::kUpperLeft;
37 } else if (AngleCloseTo(angle, M_PI, M_PI / 6)) {
38 return JoystickAngle::kMiddleLeft;
39 } else if (AngleCloseTo(angle, 0, M_PI / 6)) {
40 return JoystickAngle::kMiddleRight;
41 } else if (AngleCloseTo(angle, -M_PI / 3, M_PI / 6)) {
42 return JoystickAngle::kLowerRight;
43 } else if (AngleCloseTo(angle, -2 * M_PI / 3, M_PI / 6)) {
44 return JoystickAngle::kLowerLeft;
45 }
46
Tyler Chatowd28951f2019-02-16 20:12:28 -080047 return JoystickAngle::kDefault;
48}
Tyler Chatowd28951f2019-02-16 20:12:28 -080049} // namespace joysticks
50} // namespace input
51} // namespace y2019