Making duo stepper motors run for certain times

I am looking to figure out a way to run my current code for a certain amount of time in each direction. What the code does right now is rotates a certain number of steps in one direction and the reverses the same distance. The problem I have run into is that there is a limit for the x variable in the code. Once this limit is passed that motors turn in one direction infinitely. I was wondering if there was a way to fix the code, add a clock for run time in each direction, or if there is a code to replace this that will allow for me to run the two stepper motors simultaneously. I am trying to get two lead screws to run a gantry bar from one end to the other and back.

//Pins for stepper motor 1
const int stepPina = 3;  //PUL+ pin for rotation
const int dirPina = 2;   //DIR+ Pin Direction
const int enPina = 8;    //ENA+ Pin for enable

//Pins for stepper motor 2
const int stepPinb = 5;  //PUL+ pin for rotation
const int dirPinb = 4;   //DIR+ pin Direction
const int enPinb = 9;    // ENA+ Pin for enable

void setup() {
  // put your setup code here, to run once:
  //setup for motor 1
  pinMode(stepPina, OUTPUT);
  pinMode(dirPina, OUTPUT);
  pinMode(enPina, OUTPUT);
  digitalWrite(enPina, LOW);

  //setup for motor 2
  pinMode(stepPinb, OUTPUT);
  pinMode(dirPinb, OUTPUT);
  pinMode(enPinb, OUTPUT);
  digitalWrite(enPinb, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(dirPinb, LOW);
  digitalWrite(dirPina, LOW);        //HIGH or LOW to change Direction: Stepper Motor 1
  for (int x = 0; x < 32000; x++) {  //Figure out ghost function of x. mo dulo: define as integer, always
    digitalWrite(stepPina, HIGH);
    delayMicroseconds(25);
    digitalWrite(stepPina, LOW);
    delayMicroseconds(25);
    digitalWrite(stepPinb, HIGH);
    delayMicroseconds(25);
    digitalWrite(stepPinb, LOW);
    delayMicroseconds(25);
  }


  delay(1000);  //1 second delay between direction change

  digitalWrite(dirPinb, HIGH);
  digitalWrite(dirPina, HIGH);       //HIGH or LOW to change Direction
  for (int x = 0; x < 32767; x++) {  // A<x<B

    digitalWrite(stepPinb, HIGH);
    delayMicroseconds(25);
    digitalWrite(stepPinb, LOW);
    delayMicroseconds(25);
    digitalWrite(stepPina, HIGH);
    delayMicroseconds(25);
    digitalWrite(stepPina, LOW);
    delayMicroseconds(25);
  }

  exit(0);  //end code
}

Rather the limit is the integer type variable You use. Use long, or unsigned long instead.

Try: for ( long x = 0; x < 7fffffffH; x++; {

2 Likes

Yes you can also modify your code to time or time control the steppers. Hint: get rid of the delay() statements in your code.

Sorry for taking a week to get back to you. This was the exact answer I was looking for, but was unable to find it on my own, no matter where I looked.

Thanks for telling.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.