Help getting stepper motor running for 5 seconds with the press of a button

Hi, I need some help getting this motor running for 5 seconds with the press of a button, I'm thinking its a problem with the code since I'm a beginner
This is the entirety of my code / /

#include <AccelStepper.h>


#define dirPin 2
#define stepPin 3
#define motorInterfaceType 1
int button = 7;


AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);

void setup() {
  pinMode(button,INPUT);
  pinMode(13,OUTPUT);

  stepper.setMaxSpeed(1000);
}

void loop() {
  if (digitalRead(button) == HIGH) {
    digitalWrite(13,HIGH);
    // Set the speed in steps per second:
    stepper.setSpeed(500);
    // Step the motor with a constant speed as set by setSpeed():
    stepper.runSpeed();
    delay(5000);
  }
    else {
      digitalWrite(13,LOW);
    }

  
}

I'm using a Nema 17 stepper motor and a A4988 driver

any help will be appreciated :slight_smile:

What does the code actually do? How is that different from what you want?

Is there a pulldown resistor on the button input?

Karma for code tags on first post.

jakusu:
Hi, I need some help getting this motor running for 5 seconds with the press of a button, I'm thinking its a problem with the code since I'm a beginner

These two lines of code are completely at odds with each other

   stepper.runSpeed();
    delay(5000);

[/quote]
The line stepper.runSpeed() needs to be called very frequently - much faster than the expected step rate - and the delay() just blocks the Arduiino from doing anything.

Have a look at how millis() is used to manage timing without blocking in Several Things at a Time.

And see Using millis() for timing. A beginners guide if you need more explanation.

...R
Stepper Motor Basics
Simple Stepper Code