// Define joystick pins
const int Xpin = A0; // Joystick X-axis for speed control
const int Ypin = A1; // Joystick Y-axis for direction control
// Define motor driver pins
const int speedPin = 11; // PWM pin for motor speed
const int dir1 = 9; // Direction control pin 1
const int dir2 = 10; // Direction control pin 2
// Variables to store joystick values
int Xval = 0;
int Yval = 0;
// Define dead zone for joystick to prevent unintentional motor movement
const int deadZone = 50;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set motor pins as outputs
pinMode(speedPin, OUTPUT);
pinMode(dir1, OUTPUT);
pinMode(dir2, OUTPUT);
// Set joystick pins as inputs
pinMode(Xpin, INPUT);
pinMode(Ypin, INPUT);
}
void loop() {
// Read joystick values
Xval = analogRead(Xpin); // Read speed control value
Yval = analogRead(Ypin); // Read direction control value
// Map X-axis joystick value to motor speed (0 to 255)
int motorSpeed = map(Xval, 0, 1023, 0, 255);
// Determine motor direction based on Y-axis joystick value
if (Yval > (512 + deadZone)) {
// Forward direction
digitalWrite(dir1, LOW);
digitalWrite(dir2, HIGH);
} else if (Yval < (512 - deadZone)) {
// Backward direction
digitalWrite(dir1, HIGH);
digitalWrite(dir2, LOW);
} else {
// Stop motor (dead zone)
digitalWrite(dir1, LOW);
digitalWrite(dir2, LOW);
motorSpeed = 0; // Set speed to 0
}
// Apply motor speed
analogWrite(speedPin, motorSpeed);
// Print joystick and motor status to the serial monitor
Serial.print("X Value = ");
Serial.print(Xval);
Serial.print(", Y Value = ");
Serial.print(Yval);
Serial.print(", Motor Speed = ");
Serial.print(motorSpeed);
Serial.print(", Motor Direction = ");
if (Yval > (512 + deadZone)) {
Serial.println("Forward");
} else if (Yval < (512 - deadZone)) {
Serial.println("Backward");
} else {
Serial.println("Stopped");
}
// Short delay before next loop iteration
delay(100);
}