diff --git a/include/constants.hpp b/include/constants.hpp index 88aa324..53c6ffc 100644 --- a/include/constants.hpp +++ b/include/constants.hpp @@ -9,3 +9,5 @@ #define ACTION_INTERVAL 60000 // 1 minute #define MAXIMUM_STAT 100 + +#define DEBOUNCE_DELAY 50 // Debounce delay in milliseconds for the joystick button diff --git a/include/joystick.hpp b/include/joystick.hpp index 2deb4bd..5060844 100644 --- a/include/joystick.hpp +++ b/include/joystick.hpp @@ -1,5 +1,6 @@ #pragma once #include +#include "constants.hpp" /* * A helper class to read values from the KY-023 joystick module. @@ -25,13 +26,24 @@ class Joystick { Joystick(); double getX() const; double getY() const; - bool isPressed() const; + bool isPressed(); JoystickDirection getDirection() const; private: + class Switch { + public: + Switch(uint8_t pin); + bool isPressed(); + private: + uint8_t pin; + bool lastKnownState; + bool lastStableState; + uint64_t lastDebounceTime; + }; + uint8_t vrx; uint8_t vry; - uint8_t sw; + Switch sw; uint8_t xOffset; uint8_t yOffset; diff --git a/src/joystick.cpp b/src/joystick.cpp index ee867d8..eb71e05 100644 --- a/src/joystick.cpp +++ b/src/joystick.cpp @@ -1,10 +1,33 @@ #include "joystick.hpp" +Joystick::Switch::Switch(uint8_t pin) : pin(pin), lastKnownState(HIGH), lastStableState(HIGH), lastDebounceTime(0) { + pinMode(pin, INPUT_PULLUP); // Use internal pull-up resistor +} + +bool Joystick::Switch::isPressed() { + bool state = digitalRead(pin); + + // Check for state change and debounce + if (state != lastKnownState) { + lastDebounceTime = millis(); // Reset debounce timer + lastKnownState = state; + } + + // If the state has been stable for longer than the debounce delay, update the stable state + if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) { + if (lastStableState != state) { + lastStableState = state; // Update stable state + return state == LOW; // Return true if the button is pressed (active LOW) + } + } + + return false; // No change in button state +} + // Initialize the joystick pins in the constructor -Joystick::Joystick() : vrx(A0), vry(A1), sw(4) { +Joystick::Joystick() : vrx(A0), vry(A1), sw(Switch(4)) { pinMode(vrx, INPUT); pinMode(vry, INPUT); - pinMode(sw, INPUT_PULLUP); // Calibrate the joystick by reading the center position and storing it as an offset xOffset = map(analogRead(vrx), 0, 1023, -100, 100); @@ -21,8 +44,8 @@ double Joystick::getY() const { } // Check if the joystick button is pressed (active LOW) -bool Joystick::isPressed() const { - return digitalRead(sw) == LOW; +bool Joystick::isPressed() { + return sw.isPressed(); } // Determine the direction of the joystick based on the X and Y values, considering a deadzone to prevent jitter