fix(joystick): debounce joystick button

This commit is contained in:
2026-04-29 01:33:41 +02:00
parent 28af5da4f3
commit ad1c76106a
3 changed files with 43 additions and 6 deletions
+2
View File
@@ -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
+14 -2
View File
@@ -1,5 +1,6 @@
#pragma once
#include <Arduino.h>
#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;
+27 -4
View File
@@ -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