How to start a stepper motor with a push button, but stop it on its own

Hello,
I'm trying to code a push button to turn on a stepper motor and then the motor turns off after 20 seconds.

How can I do this?

this is the code I have so far.
#include <Stepper.h>

int stepsPerRevolution = 100;
int buttonState = 0;
int ButtonPin = 8;
int count = 0;

Stepper myStepper(stepsPerRevolution, 0, 1, 2, 3);
// the pins are 1N1:0 1N2:1 1N3:2, 1N4:3
void setup() {

//Speed of the motor per revolution:
myStepper.setSpeed(100);

Serial.begin(9600);
pinMode (ButtonPin, INPUT);
}

void loop() {
buttonState = digitalRead (ButtonPin);

if(buttonState== HIGH){

count++;

}

if(count==1){
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
myStepper.setSpeed(100);
(delay(20000)//milliseconds
ds
}

}

I have a super starter Uno R3 Project.

Hi,
as it is the first time using the forum, read the topic.
" How to get the best out of this forum "
Then correct your post by putting the code between the </> tags.
And also correct your code because it has syntax error. It doesn't compile as is.

What happens when you run that? As @ruilviana points out, that won't compile.

Make sure that your button has either a pullup or a pulldown or it won't be reliable. Ideally connect it between the pin and GND and set the configuration to INPUT_PULLUP instead of INPUT.

Hello @wow39 ,

welcome to the Arduino-Forum.

you should read this and take it into your heart.

to be as shortworded like you

you use a library for stepper-motors that offers background step-pulse-creation.
This hsort answer does not help very much - I know.

A stepper-motor driven by the stepper.h-library needs a step-pulse for each step the stepper-motor shall do. Otherwise you would have no control over the stepper-motor.

This means you have to let void loop looping for 20 seconds.
This requires non-blocking timing which is described here.

best regards Stefan

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