Help with making a stepper motor start with a button

Hi everyone,
I am having trouble coding a stepper motor to start with a button. All I want to happen is for the stepper motor to begin rotating around when a button is pressed and for it to continue rotating even when pressure is released from the button. Below is the coding I have done so far but I’m not sure if it is right or where to go from here as it isn’t working.

Any help would be much appreciated!


const int buttonPin = 7; // the pin number for the button

const int buttonInterval = 300; // number of millisecs between button readings
unsigned long previousButtonMillis = 0; // time when button press last checked

#include <Stepper.h>

const int stepsPerMotorRevolution = 32;
const int stepsPerOutputRevolution = 1; // change this to fit the number of steps per revolution of motor

Stepper Stepper1(stepsPerMotorRevolution, 8, 9, 10, 12); //Initialise your stepper motor on pins 8-11

unsigned long previousMillis = 0; // will store last time LED was updated
unsigned long currentMillis = 0;
const long stepinterval = 10;

void setup() {
// put your setup code here, to run once:

pinMode(buttonPin, INPUT_PULLUP);

void loop() {
// put your main code here, to run repeatedly:

currentMillis = millis();


void readButton() {

if (millis() - previousButtonMillis >= buttonInterval) {

if (digitalRead(buttonPin) == LOW) {

previousMillis += stepinterval;
Stepper1.setSpeed(300); //sets the speed of the motor in rpm


Use code tags next time. You don't get a lot of warnings for violating this forum rule.

You have a function called readButton(). That does a lot more than reading a button. It is best if the name of a function matches what it actually does. Take that stepper code out of there and put it in its own function.

Then those two functions need a way of communicating. Maybe a global boolean variable called stepperShouldRun. That can be set to true or false by the button function and the stepping function can use that to decide if it should make a step.


What do you want the code to do exactly after it starts turning? Spin forever? Spin a certain time? Certain steps? What should happen if the button is pressed again?