Arduino Stepper Motor Button Control

Is it possible to program an Arduino that when I hold down a button it makes a stepper motor go for a specific amount of time and then stop? I don't want it to go the whole time I have the button held down, I want to specify an amount of time that it goes. Is this possible?

Yes it is.

1 Like

Yes.
Use a non-blocking delay, which is fairly easy to do.

int flag = 0;
int prevMillis = 0;
void loop() {
  if (digitalRead(yourButton) == HIGH) {
    if (flag == 0) {
      flag = 1;
    }
  }
  if (flag == 1) {
    yourStepper.doSomething();
    if (millis() - prevMillis >= delayTime) {
      prevMillis = millis();
      flag = 2;
    }
  }
  if (digitalRead(yourButton) == LOW) {
    if (flag == 2) {
      flag = 0;
    }
    prevMillis = millis();
  }
}

This code works like this.
If your button is pressed, and flag is equal to 0, then set flag to 1.
If flag is equal to 1, do something with the stepper for delayTime milliseconds. Then, set flag to 2.
Wait until the button is released to set flag back to 0.

Thank you for the info! I am new to Arduino so it's hard for me to understand how exactly to do this... Is this all the code I would need for the project? How do I assemble the components correctly?
Any help would be greatly appreciated!

What kind of stepper do you have? What kind of stepper driver?

I am not sure, it is the one that came with the Arduino Uno set

Is it this?

Yes, I believe so!


Make this circuit

Thank you! So my project is a vent cover... Initially, I had made it remote controlled and it worked great except it was always on and thus drained the batteries and made the motor very hot... If I do it this way, the power will be cut as long as I'm not pressing the button, correct?

The power will still be connected, unless you use a power switch.

Ok, how is that different from a button?

#include <Stepper.h>

#define STEPS 32

Stepper stepper(STEPS, 8, 10, 9, 11);

void setup() {
  stepper.setSpeed(200);
  stepper.step(1024);
}

void loop() {
  // NOTHING NEEDED HERE
}

Use this code instead, much simpler

Get rid of the button in the schematic i posted.
Just connect the button between the Arduino's vin and the power source
Pushing the button turns on power to the Arduino, and it rotates the motor, then stops.
Releasing the button disconnects power to everything

Ok, so I would just have to hold it down long enough for it to run the code?

Yeah. Your new circuit is this:

Got it, thank you so much!

Is it working?

I didn't get to try it yet, but I will let you know!