I'm using a Nema 17 stepper motor (200 steps) and a DRV8825 motor driver. This is the configuration I am using:
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:
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.
It only moves in one direction. I can't get it to move anti-clockwise.
-
1the wiring diagram shows connections different from the codejsotola– jsotola01/31/2024 16:43:39Commented Jan 31, 2024 at 16:43
-
Just been troubleshooting something similar, where stepper only moves one direction. Turned out my arduino was the problem - the dir pin was 1v low, 3v high instead of 5v like it should've been.Ben Lucy– Ben Lucy10/13/2024 15:23:19Commented Oct 13, 2024 at 15:23
1 Answer 1
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);
}
Explore related questions
See similar questions with these tags.