/*
Forum: https://forum.arduino.cc/t/stop-the-rotation-of-stepper-motor-when-the-key-is-pressed/1164919/16
Wokwi: https://wokwi.com/projects/375498290494353409
*/
#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;
void setup() {
mystepper.setMaxSpeed(maxSpeed);
pinMode(pushButtonPin, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("Begin");
}
void loop() {
reactOnButton();
reactOnSerial();
handleStepper();
}
void handleStepper(){
if (stepperOn){
mystepper.runSpeed();
}
}
void reactOnButton(){
if (buttonReleased()) {
if (stepperOn) {
Serial.println("Button stops");
stopStepper();
} else {
Serial.println("Button starts");
startStepper();
}
}
}
void reactOnSerial(){
if (Serial.available() > 0) {
char command = Serial.read();
switch (command) {
case 's' : startStepper();
break;
case 'p' : stopStepper();
break;
}
}
}
void startStepper() {
Serial.println("Start received");
mystepper.setSpeed(runAtSpeed);
stepperOn = true;
}
void stopStepper() {
Serial.println("Stop received");
mystepper.stop();
stepperOn = false;
}
boolean buttonReleased() {
static unsigned long lastTime = 0;
static int lastState = HIGH;
static int state = HIGH;
boolean returnState = false;
int actState = digitalRead(pushButtonPin);
if (actState != lastState) {
lastTime = millis();
lastState = actState;
}
if (millis() - lastTime > 30 && state != lastState) {
state = lastState;
if (state) {
returnState = true;
}
}
return returnState;
}