I need help making a Stepper motor change directions and turn a certain distance

I'm really new to Arduino, I've done some research but everything is still really alien to me. I have a stepper motor that is able to continuously run in one direction and change directions when I press a button. I've only gotten this code from youtube tutorials and I have a barebones understanding of how it works. I want the Stepper motor to move a certain number of rotations and then stop and then when I press the button again, I want it to spin the same number of rotations backwards. Can anyone help with this or point me in the direction of tutorials I can use? Thanks

#include <Stepper.h>
int stepsPerRevolution=2048;
int motSpeed=10;
int dt=500;


int buttonPin=2;
int motDir=1;
int buttonValNew;
int buttonValOld=1;
Stepper myStepper(stepsPerRevolution, 8,10,9,11);
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
myStepper.setSpeed(motSpeed);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
}

void loop() {
buttonValNew=digitalRead(buttonPin);
if (buttonValOld==1 && buttonValNew==0){
  motDir=motDir*(-1);
}
myStepper.step(motDir*1);
buttonValOld=buttonValNew;
}

For more information it's best to look into the library you are using.
https://www.arduino.cc/reference/en/libraries/stepper/
In your sketch

myStepper.step(motDir*1);

is called every cycle, adding another step to the position, causing a constant speed.
changing it to:

void loop() {
buttonValNew=digitalRead(buttonPin);
if (buttonValOld==1 && buttonValNew==0){
  motDir=motDir*(-1);
  myStepper.step(motDir*1);
}
buttonValOld=buttonValNew;
}

Will cause it to run 1 step forward/backward every time the button is pushed.
As 1 steps on 2048 is difficult to see it's better to change the value of motDir to 2048 to get a full revolution.

int motDir=2048;

Thank you so much.

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