/*
Forum: https://forum.arduino.cc/t/stop-the-rotation-of-stepper-motor-when-the-key-is-pressed/1164919/8
Wokwi: https://wokwi.com/projects/374954917803485185
*/
#include <AccelStepper.h>
#define STEPS_PER_REVOLUTION 1000 // Change this to match your stepper motor's specification
#define DIR_PIN 8
#define STEP_PIN 9
const int pushButtonPin = 12; // Replace with the actual pin connected to the push button
constexpr int maxSpeed = 2000; // Set the maximum speed of the stepper motor (adjust as needed)
constexpr int runAtSpeed = 1000; // Set the speed of the stepper motor (adjust as needed)
AccelStepper mystepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
boolean stepperOn = false;
boolean motorRunning = true;
void setup() {
mystepper.setMaxSpeed(maxSpeed);
pinMode(pushButtonPin, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("Begin");
}
void loop() {
int buttonState = digitalRead(pushButtonPin);
if (buttonState == LOW && !stepperOn ) {
Serial.println("Start Rotating ");
mystepper.setSpeed(runAtSpeed);
stepperOn = true;
}
if (Serial.available() > 0) {
char command = Serial.read();
if (command == 's') {
// Move stepper motor for 3 seconds
Serial.println("Start received");
mystepper.setSpeed(runAtSpeed);
stepperOn = true;
}
if (command == 'p') {
Serial.println("Stop received");
mystepper.stop();
stepperOn = false;
}
}
if (stepperOn) {
mystepper.runSpeed();
}
}