Digital Joystick

So I need help making this digital joystick for a project. The idea is that when unused, it resets to the center of the screen, and will use a potientiometer joystick to get the data to process. Since I am a complete noob at coding, I got ai to do it, and it always drifts to the bottom right, and dosen't reset to the center of the screen. Here is the said ai code:
#include <Mouse.h>

// Define the analog pins for the joystick
const int xPin = A0;
const int yPin = A1;

// Define a deadzone threshold to ignore minor fluctuations at rest.
const int deadZone = 20; // Adjust as needed

void setup() {
// Begin mouse control (this enables USB mouse emulation)
Mouse.begin();

// Set the joystick pins as inputs.
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
}

void loop() {
// Read the analog values for both axes.
int xReading = analogRead(xPin);
int yReading = analogRead(yPin);

// Calculate the deviation from an assumed center value of 512.
int xDeviation = xReading - 512;
int yDeviation = yReading - 512;

// Check if the deviation is significant (outside the deadzone).
if (abs(xDeviation) > deadZone || abs(yDeviation) > deadZone) {
// Map the deviation to a relative mouse movement.
// The values -10 to 10 determine the speed/sensitivity.
int moveX = map(xDeviation, -512, 511, -10, 10);
int moveY = map(yDeviation, -512, 511, -10, 10);

// Move the mouse pointer relative to its current position.
Mouse.move(moveX, moveY);
}

// A short delay to stabilize the update rate.
delay(10);
}
#include <Mouse.h>

// Define the analog pins for the joystick
const int xPin = A0;
const int yPin = A1;

// Define a deadzone threshold to ignore minor fluctuations at rest.
const int deadZone = 20; // Adjust as needed

void setup() {
// Begin mouse control (this enables USB mouse emulation)
Mouse.begin();

// Set the joystick pins as inputs.
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
}

void loop() {
// Read the analog values for both axes.
int xReading = analogRead(xPin);
int yReading = analogRead(yPin);

// Calculate the deviation from an assumed center value of 512.
int xDeviation = xReading - 512;
int yDeviation = yReading - 512;

// Check if the deviation is significant (outside the deadzone).
if (abs(xDeviation) > deadZone || abs(yDeviation) > deadZone) {
// Map the deviation to a relative mouse movement.
// The values -10 to 10 determine the speed/sensitivity.
int moveX = map(xDeviation, -512, 511, -10, 10);
int moveY = map(yDeviation, -512, 511, -10, 10);

// Move the mouse pointer relative to its current position.
Mouse.move(moveX, moveY);
}

// A short delay to stabilize the update rate.
delay(10);
}
2 Replies
DaDev
DaDev6d ago
@ZBruh10 we dont help with ai code, or help users that use ai code. Sorry rules, you can close this post now.
ZBruh10
ZBruh10OP6d ago
Guess I have to learn the hard way.

Did you find this page helpful?