From 2d2051e6c20ff30b4bf0f5fe1802386f43671491 Mon Sep 17 00:00:00 2001 From: Zvonimir Rudinski Date: Tue, 28 Apr 2026 19:34:58 +0200 Subject: [PATCH] feat(joystick): add directional input --- include/joystick.hpp | 12 +++++++++++- src/joystick.cpp | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/include/joystick.hpp b/include/joystick.hpp index f8b53f4..299cc17 100644 --- a/include/joystick.hpp +++ b/include/joystick.hpp @@ -12,13 +12,22 @@ * Note: The button is active LOW and requires a pull-up resistor, which can either be external (10kΩ) * or the internal pull-up resistor of the microcontroller (default). */ +enum JoystickDirection { + CENTER, + UP, + DOWN, + LEFT, + RIGHT +}; + class Joystick { public: Joystick(); - double getX() const; double getY() const; bool isPressed() const; + + JoystickDirection getDirection() const; private: uint8_t vrx; uint8_t vry; @@ -26,4 +35,5 @@ class Joystick { const uint8_t xOffset = 13; const uint8_t yOffset = 10; + const uint8_t deadzone = 15; // Deadzone threshold to prevent jitter around the center position }; diff --git a/src/joystick.cpp b/src/joystick.cpp index 98a482a..58865a1 100644 --- a/src/joystick.cpp +++ b/src/joystick.cpp @@ -20,3 +20,22 @@ double Joystick::getY() const { bool Joystick::isPressed() const { return digitalRead(sw) == LOW; } + +// Determine the direction of the joystick based on the X and Y values, considering a deadzone to prevent jitter +JoystickDirection Joystick::getDirection() const { + double x = getX(); + double y = getY(); + + if (abs(x) < deadzone && abs(y) < deadzone) { + return CENTER; + } else if (y > deadzone) { + return UP; + } else if (y < -deadzone) { + return DOWN; + } else if (x > deadzone) { + return RIGHT; + } else if (x < -deadzone) { + return LEFT; + } + return CENTER; // Default to CENTER if no direction is detected +}