blob: 9baf9ed90522ecc21c4d9d44223e159af1ec6f89 [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
Stephan Pleinesf63bde82024-01-13 15:59:33 -08007namespace y2019::input::joysticks {
Tyler Chatowd28951f2019-02-16 20:12:28 -08008
Tyler Chatowc8012ca2019-02-18 22:33:01 -08009using ::frc971::zeroing::Wrap;
10
11bool AngleCloseTo(double angle, double near, double range) {
12 double wrapped_angle = Wrap(near, angle, 2 * M_PI);
13
14 return ::std::abs(wrapped_angle - near) < range;
15}
16
Tyler Chatowd28951f2019-02-16 20:12:28 -080017JoystickAngle GetJoystickPosition(const JoystickAxis &x_axis,
18 const JoystickAxis &y_axis,
19 const Data &data) {
20 return GetJoystickPosition(data.GetAxis(x_axis), data.GetAxis(y_axis));
21}
22
23JoystickAngle GetJoystickPosition(float x_axis, float y_axis) {
Tyler Chatowc8012ca2019-02-18 22:33:01 -080024 const float magnitude = hypot(x_axis, y_axis);
25
26 if (magnitude < 0.5) {
27 return JoystickAngle::kDefault;
Tyler Chatowd28951f2019-02-16 20:12:28 -080028 }
Tyler Chatowc8012ca2019-02-18 22:33:01 -080029
30 double angle = atan2(y_axis, x_axis);
31
32 if (AngleCloseTo(angle, M_PI / 3, M_PI / 6)) {
33 return JoystickAngle::kUpperRight;
34 } else if (AngleCloseTo(angle, 2 * M_PI / 3, M_PI / 6)) {
35 return JoystickAngle::kUpperLeft;
36 } else if (AngleCloseTo(angle, M_PI, M_PI / 6)) {
37 return JoystickAngle::kMiddleLeft;
38 } else if (AngleCloseTo(angle, 0, M_PI / 6)) {
39 return JoystickAngle::kMiddleRight;
40 } else if (AngleCloseTo(angle, -M_PI / 3, M_PI / 6)) {
41 return JoystickAngle::kLowerRight;
42 } else if (AngleCloseTo(angle, -2 * M_PI / 3, M_PI / 6)) {
43 return JoystickAngle::kLowerLeft;
44 }
45
Tyler Chatowd28951f2019-02-16 20:12:28 -080046 return JoystickAngle::kDefault;
47}
Stephan Pleinesf63bde82024-01-13 15:59:33 -080048} // namespace y2019::input::joysticks