2

I'm using a Nema 17 stepper motor (200 steps) and a DRV8825 motor driver. This is the configuration I am using:

enter image description here

I am using a 9 V power supply. The dirPin is connected to pin 3 on the Arduino board, and my stepPin to pin 2.

What I'm trying to do is move the motor 100 steps clockwise and then move it 100 steps anti-clockwise, so that it returns to the starting position. This is the code I am using:

#include <AccelStepper.h>

#define dirPin 3
#define stepPin 2
#define motorInterfaceType 1

int SPR = 200;

AccelStepper stepper(motorInterfaceType, stepPin, dirPin); 

void setup() {
  pinMode(dirPin,OUTPUT);
  pinMode(stepPin,OUTPUT);
  // put your setup code here, to run once:
  stepper.setMaxSpeed(200);
  stepper.setAcceleration(30);
}

void loop() {
  // put your main code here, to run repeatedly:
  stepper.moveTo(100);

  stepper.runToPosition();
  delay(1000);

  stepper.moveTo(-100);

  stepper.runToPosition();
  delay(1000);
}

I have two issues:

  1. Before moving the motor 100 steps, it moves a couple of steps (like 15°), and then it starts moving, first 100 steps, and then 200 steps. That would be the first iteration, and I don't understand why it moves those 200 steps. And then, in the following iterations, the motor just moves 200 steps.

  2. It only moves in one direction. I can't get it to move anti-clockwise.

1
  • 1
    the wiring diagram shows connections different from the code
    – jsotola
    Jan 31 at 16:43

1 Answer 1

2

The moveTo() function takes absolute positions, so if you want to move in both directions, you should adjust the target positions accordingly.

You can modify your loop() function as follows:

void loop() {
  stepper.moveTo(100);
  stepper.runToPosition();
  delay(1000);

  stepper.moveTo(0); // Move back to the starting position
  stepper.runToPosition();
  delay(1000);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.