Toggle Stepper motor on and off with push button

OK, not that hard. An extra variable and an if structure and ...

// Include the AccelStepper Library
#include <Stepper.h>
int stepsPerRevolution = 2048;
int motSpeed = 10;
int dt = 500;

int buttonPin = 6;
int motDir = 1;
bool motRun = false;

Stepper myStepper(stepsPerRevolution, 2, 4, 3, 5);

void setup()
{
   Serial.begin(9600);
   myStepper.setSpeed(motSpeed);
   pinMode(buttonPin, INPUT_PULLUP);
   //digitalWrite(buttonPin, HIGH);
}

void loop()
{
   static bool buttonValOld = 1;
   bool buttonValNew = digitalRead(buttonPin);
   if (buttonValOld  != buttonValNew)
   {
      if (buttonValNew == LOW)

      {
         motRun = !motRun;
      }
      buttonValOld = buttonValNew;
   }

   if (motRun)
   {
      myStepper.step(motDir * 1);
      delayMicroseconds(dt);
   }
   else
   {
      myStepper.step(0);
   }
}

My state change tutorial if you are interested.

2 Likes