1

I am driving a bipolar stepper motor with an a4988 driver using the AccelStepper library. My goal is to press a button and the motor moves CW, then another button for CCW.

I have looked at another post with a very similar issue, but the solution does not seem to apply well to the AccelStepper library, which I would really like to use given its versatility.

Currently, whichever button I press, the motor moves CCW. Any help would be greatly appreciated!

#include <AccelStepper.h>
AccelStepper stepperX(1, 3, 2);

void setup() {
  pinMode(8, INPUT)
  pinMode(9, INPUT);

  stepperX.setMaxSpeed(100.0);
  stepperX.setAcceleration(100.0);
}

int moveRight = 1000;              //arbitrarily high number
int moveLeft = -1000;              //arbitrarily low number

void loop() {
  while (digitalRead(8) == HIGH) { //when d8 button is pressed move left
    stepperX.moveTo(moveLeft);     //set move
    if (digitalRead(8) == LOW) {   //if not pressed, kill loop
      stepperX.stop();
      break;
    }
    stepperX.run();
  }

  while (digitalRead(9) == HIGH) { //when d9 button is pressed move right
    stepperX.moveTo(moveRight);    //set move
    if (digitalRead(9) == LOW) {   //if not pressed, kill loop
      stepperX.stop();
      break;
    }
    stepperX.run();
  }
}
1
  • start debugging by reducing you code to moving CW for one second ... stop for one second ... move CCW for one second ... stop for one second – jsotola Feb 21 at 17:38
1

You work with accelleration and absolute positions. Are you aware of that? This Library is not made for running permanently in the same direction. It let you define a position where the movement should end, an acceleration or speed and the controller moves the motor to that position.

The run method must be called permanently, It triggers the steps. So, I put it directly into the loop() method.

The following prog should hopefully move the motor towards position 1000 if you press the 8-button, towards position -1000 if you press the 9-button and stops if both buttons are off. I have not the hardware available at the moment, you it's just blind programming. Use it as an idea.

#include <AccelStepper.h>
AccelStepper stepperX(1, 3, 2);

void setup() 
{
  pinMode(8, INPUT)
  pinMode(9, INPUT);

  stepperX.setMaxSpeed(100.0);
  stepperX.setAcceleration(3.0);
}

int positivePosition = 1000;
int negativePosition = -1000;

void loop() 
{
  if ( digitalRead(8) == HIGH ) 
  { 
    stepperX.moveTo(positivePosition);
  }
  else if (digitalRead(9) == HIGH) 
  {
    stepperX.moveTo(negativePosition);
  }
  else
  {
    stepperX.stop();
  }
  stepperX.run();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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