blob: 986a3faaf1fdcbecb9ad2b9a509b4848ea075398 [file] [log] [blame]
Philipp Schrader790cb542023-07-05 21:06:52 -07001#include "y2019/joystick_angle.h"
2
Tyler Chatowc8012ca2019-02-18 22:33:01 -08003#include <cmath>
4
5#include "frc971/zeroing/wrap.h"
Tyler Chatowd28951f2019-02-16 20:12:28 -08006
7namespace y2019 {
8namespace input {
9namespace joysticks {
10
Tyler Chatowc8012ca2019-02-18 22:33:01 -080011using ::frc971::zeroing::Wrap;
12
13bool AngleCloseTo(double angle, double near, double range) {
14 double wrapped_angle = Wrap(near, angle, 2 * M_PI);
15
16 return ::std::abs(wrapped_angle - near) < range;
17}
18
Tyler Chatowd28951f2019-02-16 20:12:28 -080019JoystickAngle GetJoystickPosition(const JoystickAxis &x_axis,
20 const JoystickAxis &y_axis,
21 const Data &data) {
22 return GetJoystickPosition(data.GetAxis(x_axis), data.GetAxis(y_axis));
23}
24
25JoystickAngle GetJoystickPosition(float x_axis, float y_axis) {
Tyler Chatowc8012ca2019-02-18 22:33:01 -080026 const float magnitude = hypot(x_axis, y_axis);
27
28 if (magnitude < 0.5) {
29 return JoystickAngle::kDefault;
Tyler Chatowd28951f2019-02-16 20:12:28 -080030 }
Tyler Chatowc8012ca2019-02-18 22:33:01 -080031
32 double angle = atan2(y_axis, x_axis);
33
34 if (AngleCloseTo(angle, M_PI / 3, M_PI / 6)) {
35 return JoystickAngle::kUpperRight;
36 } else if (AngleCloseTo(angle, 2 * M_PI / 3, M_PI / 6)) {
37 return JoystickAngle::kUpperLeft;
38 } else if (AngleCloseTo(angle, M_PI, M_PI / 6)) {
39 return JoystickAngle::kMiddleLeft;
40 } else if (AngleCloseTo(angle, 0, M_PI / 6)) {
41 return JoystickAngle::kMiddleRight;
42 } else if (AngleCloseTo(angle, -M_PI / 3, M_PI / 6)) {
43 return JoystickAngle::kLowerRight;
44 } else if (AngleCloseTo(angle, -2 * M_PI / 3, M_PI / 6)) {
45 return JoystickAngle::kLowerLeft;
46 }
47
Tyler Chatowd28951f2019-02-16 20:12:28 -080048 return JoystickAngle::kDefault;
49}
Tyler Chatowd28951f2019-02-16 20:12:28 -080050} // namespace joysticks
51} // namespace input
52} // namespace y2019