Stepper Motor - Why doesn't this code work

Hi,

I am using a DVR 8825 to drive a NEMA 17 stepper motor.

Can someone explain to me why the following code will drive the motor properly:

#define dirPin 2
#define stepPin 3
#define stepsPerRevolution 200

void setup() {
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {
 
  for (int i = 0; i < stepsPerRevolution; i++) {
    // These four lines result in 1 step:
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(1000);
  }
}

But this code will not drive the motor properly (motor is very loud and rotates at about 1/8 the speed of when the other code is used):

#define dirPin 2
#define stepPin 3
#define stepsPerRevolution 200

void setup() {
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {

    // These four lines result in 1 step:
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(1000);
}

These two versions of the code seem functionally the same to me. What am I missing?

I would expect the second code to drive the stepper slightly slower because of the return out of loop back to main and a subsequent call to loop between every step.

I can't explain why it's so significantly different. Which Arduino are you using?

I'm using the Uno.

I tried this:

#define stepPin 3
#define stepsPerRevolution 200

unsigned long steps=0;
void setup()
{
  Serial.begin(115200);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop()
{
  //for (int i = 0; i < stepsPerRevolution; i++)
  {
    // These four lines result in 1 step:
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(1000);
    steps++;
  }
  if(steps > 4000UL)
    {
    Serial.println(millis());
    while(1)
      ;  
    }
}

It took 8083 milliseconds. When I uncommented the for loop, it took 8481. I didn't have a stepper hooked up, but that should make no difference. Still a mystery, I wonder if you have an issue with power.

Note that 4000 is divisible by 200 so I think the version with the loop will count to 4200. Counting to 4200 instead of 4000 would make the 'no-loop' time be 8487 (8083 * 4200/4000). Looks like the difference in speed is VERY small.

Given that I don't seem to be crazy regarding the code I started swapping out hardware components. Seems that there was something wrong with the DVR 8825 as it works with both versions of the code after changing it out. Thanks for helping me troubleshoot!

Its very easy to blow such a driver if the connections to the motor aren't rock-solid -
any hint of intermittent connection, or deliberately disconnecting the motor when
the driver is powered up will likely destroy the driver.

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