3

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.

ocrdu
  • 1,795
  • 3
  • 12
  • 24

1 Answers1

3

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); }

ocrdu
  • 1,795
  • 3
  • 12
  • 24
liaifat85
  • 251
  • 1
  • 4