#include <AccelStepper.h>
// Define the motor interface type. Can be full step, half step, etc.
#define MotorInterfaceType 1
// Define motor connections and motor interface type. Motor 1
#define dirPin1 11
#define stepPin1 10
AccelStepper stepper1(MotorInterfaceType, stepPin1, dirPin1);
// Motor 2
#define dirPin2 6
#define stepPin2 5
AccelStepper stepper2(MotorInterfaceType, stepPin2, dirPin2);
// Joystick pins
#define joyX A0
#define joyY A1
#define joyButton A2 // Assuming the button is connected to digital pin 6
// Steps per revolution for your stepper motor (change as per your motor specification)
#define stepsPerRevolution 200
void setup() {
// Set the maximum speed and acceleration for each stepper
stepper1.setMaxSpeed(100);
stepper1.setAcceleration(500);
stepper2.setMaxSpeed(100);
stepper2.setAcceleration(500);
// Initialize the joystick button pin
pinMode(joyButton, INPUT_PULLUP); // Using internal pull-up resistor
// Initialize serial communication
Serial.begin(9600);
}
void loop() {
// Read joystick values
int xValue = analogRead(joyX);
int yValue = analogRead(joyY);
bool buttonPressed = digitalRead(joyButton) == LOW;
if (buttonPressed) {
// If button is pressed, make both motors complete one full rotation
stepper1.move(stepsPerRevolution);
stepper2.move(stepsPerRevolution);
// Move both motors to their target positions
while (stepper1.distanceToGo() != 0 || stepper2.distanceToGo() != 0) {
stepper1.run();
stepper2.run();
}
} else {
// Map joystick values to stepper speeds (-1000 to 1000)
int motorSpeed1 = map(xValue, 0, 1023, -1000, 1000);
int motorSpeed2 = map(yValue, 0, 1023, -1000, 1000);
// Set motor speeds
stepper1.setSpeed(motorSpeed1);
stepper2.setSpeed(motorSpeed2);
// Move the motors
stepper1.runSpeed();
stepper2.runSpeed();
}
// Print joystick values for debugging
Serial.print("X: ");
Serial.print(xValue);
Serial.print(" Y: ");
Serial.println(yValue);
}