How to program two stepper motors running at same speed.

We are trying to program two stepper motors to run at the same time at the same velocity. We are using two A4988 stepper drivers to drive each stepper motor can someone give me some inside.

// defines pins numbers
const int stepPin_1 = 2;
const int dirPin_1 = 3;
const int stepPin_2 = 4;
const int dirPin_2 = 5;

void setup() {
// Sets the two pins as Outputs
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);

}
void loop() {
digitalWrite(3,HIGH); // Enables the motor to move in a particular direction
// Makes 200 pulses for making one full cycle rotation
for(int x = 0; x < 200; x++) {
digitalWrite(2,HIGH);
delayMicroseconds(500);
digitalWrite(2,LOW);
delayMicroseconds(500);
}

digitalWrite(5,HIGH); // Enables the motor to move in a particular direction
// Makes 200 pulses for making one full cycle rotation
for(int x = 0; x < 200; x++) {
digitalWrite(4,HIGH);
delayMicroseconds(500);
digitalWrite(4,LOW);
delayMicroseconds(500);
}

}

Can someone help me?

Put the code to step each motor in the same for loop.

  digitalWrite(5,HIGH); // Enables the motor to move in a particular direction
  digitalWrite(3,HIGH); // Enables the motor to move in a particular direction
  for(int x = 0; x < 200; x++) {
    digitalWrite(2,HIGH);
    digitalWrite(4,HIGH); 
    delayMicroseconds(500);
    digitalWrite(2,LOW);
    digitalWrite(4,LOW); 
    delayMicroseconds(500);
  }

Does that do what you want?

Yes this helps! but now I am facing the problem with its direction. I want to have the motors spin in a direction for a certain amount of time and then spin back.

lissette888:
Yes this helps! but now I am facing the problem with its direction. I want to have the motors spin in a direction for a certain amount of time and then spin back.

Get that to work for 1 motor and then add in the code for the second motor.

If you want the motors to move for a certain length of time rather than a certain number of steps you have 2 options. You can calculate how many steps should happen in that time or you could keep doing single steps until the time has expired.

Don't use delay() or delayMicroseconds() for controlling the time except in a test program. Have a look at how millis() is used in the second example in this Simple Stepper Code. And, more generally, have a look at how millis() is used to manage timing without blocking in Several things at a time

...R

  // Sets the two pins as Outputs
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);

Why does it take 4 statements to set the TWO pins as outputs?