After trying to solve the code for multiple weeks, we changed the wiring as well, however that did not work but we have finally fixed the code so here it is, and the v2 gun is almost finished as well so here's the code:
#include <Mouse.h>
#include "Keyboard.h"
int horzPin = A0; // Analog pin for horizontal joystick
int vertPin = A1; // Analog pin for vertical joystick
int selPin = 8; // Joystick button (select pin)
int vertZero, horzZero; // Stores joystick center values
int vertValue, horzValue; // Stores joystick axis readings
const float sensitivity = 200.0; // Sensitivity (float for precision)
int mouseClickFlag = 0;
int invertMouse = -1; // Non-inverted movement
// Button pin assignments
const int buttonW = 2; // Button for printing 'W'
const int buttonS = 3; // Button for printing 'S'
const int buttonMouseClick = 4; // Button for mouse left click
void setup() {
// Joystick setup
pinMode(horzPin, INPUT);
pinMode(vertPin, INPUT);
pinMode(selPin, INPUT_PULLUP);
vertZero = analogRead(vertPin); // Calibrate initial neutral position
horzZero = analogRead(horzPin);
Mouse.begin(); // Initialize mouse emulation
Keyboard.begin(); // Initialize keyboard emulation
// Button setup
pinMode(buttonW, INPUT_PULLUP); // Button for 'W'
pinMode(buttonS, INPUT_PULLUP); // Button for 'S'
pinMode(buttonMouseClick, INPUT_PULLUP); // Button for mouse left click
}
void loop() {
// --- Joystick Movement ---
vertValue = analogRead(vertPin) - vertZero; // Vertical movement
horzValue = analogRead(horzPin) - horzZero; // Horizontal movement
if (abs(vertValue) > 5) { // Ignore small offsets
Mouse.move(0, vertValue / sensitivity); // Move mouse vertically
}
if (abs(horzValue) > 5) { // Ignore small offsets
Mouse.move(invertMouse * horzValue / sensitivity, 0); // Move mouse horizontally
}
// --- Joystick Button (Print 'R') ---
if (digitalRead(selPin) == LOW) { Keyboard.print("R"); // Print 'R' when joystick button is pressed
delay(50); // Debounce delay
}
// --- Button 1: Print 'W' Continuously ---
if (digitalRead(buttonW) == LOW) { Keyboard.print("W"); // Print 'W' while button is held
delay(50); // Typing rate
}
// --- Button 2: Print 'S' Continuously ---
if (digitalRead(buttonS) == LOW) { Keyboard.print("S"); // Print 'S' while button is held
delay(50); // Typing rate
}
// --- Button 3: Simulate Left Mouse Click ---
if (digitalRead(buttonMouseClick) == LOW) { Mouse.click(MOUSE_LEFT); // Perform a mouse left click
delay(50); // Avoid multiple rapid clicks
}
}
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.