/*
Forum: https://forum.arduino.cc/t/stepper-motor-cancellation/1213693
Wokwi: https://wokwi.com/projects/387470045236839425
*/
#include <Stepper.h>
int stepsPerRevolution = 2048;
int motSpeed = 50;
int dt = 500;
const byte button1Pin = 6;
const byte button2Pin = 7;
int motDir = 1;
Stepper myStepper(stepsPerRevolution, 2, 4, 3, 5);
void setup()
{
Serial.begin(115200);
myStepper.setSpeed(motSpeed);
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
}
byte runStepper = true;
void loop()
{
if (digitalRead(button2Pin) == LOW) {
runStepper = true;
}
while (runStepper) {
myStepper.step(motDir * 1);
delayMicroseconds(dt);
if (limitSwitch()) {
runStepper = false;
}
}
}
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;
Serial.println(state);
return state;
}
return false;
}