Stepper Drift with set steps

I have a simple sketch with some subs to turn a stepper using a Mega and RAMPS 1.4 board. I have the motor on the x axis and the below sub to turn it 50 steps. Pin 54 is the step pin to the controller. When it is called, the stepper moves correctly and is visually 90 degrees turned but after running this 10+ times the position drifts and is off about 15 or so degrees, which will only get worse. What am I overlooking?

void Rotor90() {
digitalWrite(PWR_LED_PIN, LOW);
while (i < 51) {
digitalWrite(54, HIGH);
delay(10);
digitalWrite(54, LOW);
delay(10);
i++;
}
i=0;
digitalWrite(PWR_LED_PIN, HIGH);
}

0 to 50 is 51 steps.

Is the global variable 'i' used anywhere else in your sketch? The function you show assumes that 'i' is always 0 when the function starts but only guarantees that it is 0 when the function ends.

I recommend a 'for' loop for counting:

void Rotor90()
{
  digitalWrite(PWR_LED_PIN, LOW);
  for (int step = 0; step < 50; step++)
  {
    digitalWrite(54, HIGH);
    delay(10);
    digitalWrite(54, LOW);
    delay(10);
  }
  digitalWrite(PWR_LED_PIN, HIGH);
}

As groundFungus said you have 1 too many steps. Every time you execute this function you will add 1.8 degrees. After 10 runs you will be off 18 degrees. Use johnwasser's suggestion and your step variable will be properly scoped.

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