0

I have a problem. I am using a stepper motor with 2 buttons. In my code I am trying to rotate the stepper motor clockwise while holding button1 and counter-clockwise while holding button2. To do that, I had the following code:

#include <AccelStepper.h>

// Define button pins
#define btnLowerPin 5
#define btnRaisePin 6

// Define stepper motor connections and motor interface type.
#define dirPin 2
#define stepPin 3

int btnLowerState = 0; 
int btnRaiseState = 0; 

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(AccelStepper::DRIVER, stepPin, dirPin);

void setup() {
  // initialize the button pins as an input:
  pinMode(btnLowerPin, INPUT);
  pinMode(btnRaisePin, INPUT);
  
  // Set the maximum speed in steps per second:
  stepper.setMaxSpeed(1000);
}
void loop() {
  // read the state of the button values:
  btnLowerState = digitalRead(btnLowerPin);
  btnRaiseState = digitalRead(btnRaisePin);

  if (btnLowerState == LOW) {
    stepper.setSpeed(-1000);
    stepper.runSpeed();
  }
  else if (btnRaiseState == LOW) {
    stepper.setSpeed(1000);
    stepper.runSpeed();
  }
  else {
    stepper.setSpeed(0);
    stepper.runSpeed();
  }
}

This code worked, but I have to accelerate the motor to the speed of 1000. I found this article that explains how to do that: https://www.makerguides.com/28byj-48-stepper-motor-arduino-tutorial/. In code #3 they use the following code:

void setup() {
  // Set the maximum steps per second:
  stepper.setMaxSpeed(1000);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(200);
}
void loop() {
  stepper.moveTo(8192);
  stepper.runToPosition();
  
  delay(1000);
  
  stepper.moveTo(0);
  stepper.runToPosition();
  
  delay(1000);
}

Now I tried combining it, but the problem is that I don't know how far the motor has to rotate, because its While holding the button. Here was my code:

void loop() {
  // read the state of the button values:
  btnLowerState = digitalRead(btnLowerPin);
  btnRaiseState = digitalRead(btnRaisePin);

  if (btnLowerState == LOW) {
    stepper.moveTo(8000);
    stepper.runToPosition();
  }
  else if (btnRaiseState == LOW) {
    stepper.moveTo(0);
    stepper.runToPosition();
  }
  else {
    stepper.setSpeed(0);
    stepper.runSpeed();
  }
}

But this code stops when the loop is over and restarts the acceleration. How can I fix this? So in short:

  • The motor needs to accelerate when you start holding the button.
  • The acceleration has to be 300 and max speed 1000.
  • When you release the button it decelerates to 0.
1
  • 1
    I think you should be able to use move() instead of moveTo() – towe Nov 16 '20 at 9:44

Your Answer

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

Browse other questions tagged or ask your own question.