I want motor X moves when received command like "C,100,10" or "W,100,10" and motor y moves when i send "Y,100,10" or "Z,100,10".
In the current version of the code motors move independent then the code. When i send "Y,100,10" motor x is moving or motor y moves independent of the "Y" or "Z".
Any help i appreciate.
#include <AccelStepper.h>
const int motorXPin1 = 2; // Connect to motor driver IN1
const int motorXPin2 = 3; // Connect to motor driver IN2
const int motorXPin3 = 4; // Connect to motor driver IN3
const int motorXPin4 = 5; // Connect to motor driver IN4
const int motorYPin1 = 6; // Connect to motor driver IN1 for motor Y
const int motorYPin2 = 7; // Connect to motor driver IN2 for motor Y
const int motorYPin3 = 8; // Connect to motor driver IN3 for motor Y
const int motorYPin4 = 9; // Connect to motor driver IN4 for motor Y
// Create stepper motor objects for X and Y
AccelStepper stepperX(AccelStepper::FULL4WIRE, motorXPin1, motorXPin3, motorXPin2, motorXPin4);
AccelStepper stepperY(AccelStepper::FULL4WIRE, motorYPin1, motorYPin3, motorYPin2, motorYPin4);
void setup() {
// Set maximum speed and acceleration (adjust as needed)
stepperX.setMaxSpeed(1000); // Maximum steps per second for X
stepperX.setAcceleration(500); // Acceleration in steps per second^2 for X
stepperY.setMaxSpeed(1000); // Maximum steps per second for Y
stepperY.setAcceleration(500); // Acceleration in steps per second^2 for Y
// Set initial positions (0 degrees)
stepperX.setCurrentPosition(0);
stepperY.setCurrentPosition(0);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
// Example: parsing commands like "X100" or "Y200"
if (command.startsWith("X")) {
int targetX = command.substring(1).toInt();
moveStepperX(targetX);
} else if (command.startsWith("Y")) {
int targetY = command.substring(1).toInt();
moveStepperY(targetY);
}
}
Serial.print("X Position: ");
Serial.println(stepperX.currentPosition());
Serial.print("Y Position: ");
Serial.println(stepperY.currentPosition());
}
void moveStepperX(int targetX) {
int stepsToMove = targetX - stepperX.currentPosition();
stepperX.moveTo(targetX);
while (stepperX.distanceToGo() != 0) {
stepperX.run();
}
}
void moveStepperY(int targetY) {
int stepsToMove = targetY - stepperY.currentPosition();
stepperY.moveTo(targetY);
while (stepperY.distanceToGo() != 0) {
stepperY.run();
}
}