/*
Forum: https://forum.arduino.cc/t/stepper-motor-cancellation/1213693
Wokwi: https://wokwi.com/projects/387900608246250497
*/
#include <Stepper.h>
int stepsPerRevolution = 2048;
int motSpeed = 50;
int dt = 500;
const byte button1Pin = 6;
const byte button2Pin = 7;
int motDir = 1;
enum stateType {RUNNING, STOPPED, WAITTORUN};
stateType state = RUNNING;
const unsigned long waitToRunInterval = 5000;
unsigned long limitSwitchActivateTime = 0;
Stepper myStepper(stepsPerRevolution, 2, 4, 3, 5);
void setup()
{
Serial.begin(115200);
Serial.println("Running");
myStepper.setSpeed(motSpeed);
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
}
void loop()
{
stateMachine();
}
void stateMachine() {
switch (state) {
case RUNNING:
myStepper.step(motDir * 1);
delayMicroseconds(dt);
if (limitSwitch()) {
limitSwitchActivateTime = millis();
state = STOPPED;
Serial.println("Stopped");
}
break;
case STOPPED:
if (digitalRead(button2Pin) == LOW) {
state = WAITTORUN;
Serial.println("Start again if delay time is expired");
}
break;
case WAITTORUN:
if (millis()-limitSwitchActivateTime >= waitToRunInterval){
state = RUNNING;
}
break;
}
}
boolean limitSwitch() {
static unsigned long lastChange = 0;
static byte lastState = HIGH;
static byte state = HIGH;
byte actState = digitalRead(button1Pin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
}
if (state != actState && millis() - lastChange > 20 ) {
state = actState;
return state;
}
return false;
}