Going back to the origin: Arduino program with stepper motor not going back

Thread Starter

Adamelli

Joined Sep 14, 2020
9
This is part of a more complicated program. I reduced it as much as possible. The point is to draw a shape with two stepper motors. The minimal code for only running one motor in the x-direction is below. So it just draws a line and goes back.

The goal is to be able to stop the motor, stop drawing the shape/line, and go back to the origin (starting position). It does this sometimes. First I'm confused why the position goes back to the origin for `2000-x2` when the whole x-axis goes from +4000 to -4000 (for x2). Before, it was always going double. That's my main inquiry.

Arduino settings
  • Serial Monitor set to 115200 baud
  • Stepper motor and driver not needed.

If you want to run it yourself, there is a "Entered for-loop" that prints to the Serial Monitor to signify successfully entering into the loop that resets to the origin. Although, it usually goes too far or too short anyway. The moving motor is a good way to show I keep failing.


C:
bool runIt = false;
const int dirPinX = 2;  // direction pin for motor
const int stepPinX = 3; // step pin for motor

volatile float deltaX = 0;
volatile float h = 0;   // theta
volatile float x1 = 0;
volatile float x2 = 0;

void setup()
{
  Serial.begin(115200);

  pinMode(stepPinX, OUTPUT);
  pinMode(dirPinX, OUTPUT);
}

void loop()
{         
  if(runIt == false)
    circle();
}

void circle()
{
  float deltaH = PI/(20*200*4);

  while (h <  2*PI)
  {
    if(Serial.available() > 0)
    {
      goToOrigin();
      break;
    }

    x1 = cos(h)*20*200;
    x2 = cos(h + deltaH)*20*200;

    drawLocus();
    h += deltaH;
    
    Serial.print(x2);
    Serial.print("\t");
    Serial.print(h);
    Serial.println();
  }
}

void stepX()
{
  if (deltaX < 0) // Set motor direction clockwise
    digitalWrite(dirPinX, HIGH);

  else
    digitalWrite(dirPinX, LOW);


  digitalWrite(stepPinX, HIGH);
  delayMicroseconds(6);
  digitalWrite(stepPinX, LOW);
  delayMicroseconds(6);
}



void drawLocus()
{
  deltaX += x2 - x1;
  if (abs(deltaX) > 2)
  {
    stepX();
    deltaX = 0;
  }
}

void goToOrigin()
{
  Serial.println("Going to Origin");


  digitalWrite(dirPinX, LOW);

  int fudge = 1;
  
//  if(x2 < 0 && h < PI)  // h = theta
//    fudge = 0.5;

Serial.println(x2);

//  for(int i = 0; i < fudge*abs(2000-abs(x2)); i++)

  for(int i = 0; i < 2000-x2; i++)
  {    
    Serial.print("Entered for-loop, i: ");
    Serial.print(i);
    Serial.println();
    
    digitalWrite(stepPinX, HIGH);
    delayMicroseconds(100);
    digitalWrite(stepPinX, LOW);
    delayMicroseconds(100);
  }

    
  Serial.read();
  delay(5000);
  h = 0;
  runIt = true;
}
It could be a hardware issue with the motor not stepping or something. But I'm pretty sure the issue has to do with the program, and why does 2000 sometimes work and not 4000?
 
Top