so I have a three way momentary switch hooked up to pin 14 for left pin 18 for right and then center is on the ground trying to get it to control left and right keyboard input or any input really with this code i get just pretty uncontrolled input left and right ill press right and it may work it may not or it may just go left for whatever time it feels like could it be an issue with the switch or connections or just bad code?
#include <Keyboard.h>
// Define the input pins
const int inputLeft = 14; // Input for left key
const int inputRight = 18; // Input for right key
// Variables for debouncing and state change detection
bool lastStateLeft = LOW;
bool currentStateLeft = LOW;
bool lastStateRight = LOW;
bool currentStateRight = LOW;
unsigned long lastDebounceTimeLeft = 0;
unsigned long lastDebounceTimeRight = 0;
const unsigned long debounceDelay = 50; // Debounce time in milliseconds
void setup() {
// Initialize the Keyboard library
Keyboard.begin();
// Set the input pins as inputs
pinMode(inputLeft, INPUT);
pinMode(inputRight, INPUT);
}
void loop() {
// Read the current state of the inputs
int readingLeft = digitalRead(inputLeft);
int readingRight = digitalRead(inputRight);
// Debounce the left input
if (readingLeft != lastStateLeft) {
lastDebounceTimeLeft = millis();
}
if ((millis() - lastDebounceTimeLeft) > debounceDelay) {
if (readingLeft != currentStateLeft) {
currentStateLeft = readingLeft;
if (currentStateLeft == HIGH) {
Keyboard.press(KEY_LEFT_ARROW);
} else {
Keyboard.release(KEY_LEFT_ARROW);
}
}
}
lastStateLeft = readingLeft;
// Debounce the right input
if (readingRight != lastStateRight) {
lastDebounceTimeRight = millis();
}
if ((millis() - lastDebounceTimeRight) > debounceDelay) {
if (readingRight != currentStateRight) {
currentStateRight = readingRight;
if (currentStateRight == HIGH) {
Keyboard.press(KEY_RIGHT_ARROW);
} else {
Keyboard.release(KEY_RIGHT_ARROW);
}
}
}
lastStateRight = readingRight;
}