/*
Forum: https://forum.arduino.cc/t/turning-a-stepper-motor-off-and-on/1168572
Wokwi: https://wokwi.com/projects/375870418732018689
*/
// Define pins
constexpr byte reverseSwitch = 2; // Push button for reverse
constexpr byte driverPUL = 7; // PUL- pin
constexpr byte driverDIR = 6; // DIR- pin
constexpr byte spd = A0; // Potentiometer
// Variables
unsigned long pd = 500; // Pulse Delay period in microseconds
byte setdir = LOW; // Set Direction
void setup() {
pinMode(reverseSwitch, INPUT_PULLUP);
pinMode (driverPUL, OUTPUT);
pinMode (driverDIR, OUTPUT);
attachInterrupt(digitalPinToInterrupt(reverseSwitch),revmotor, FALLING);
}
void loop() {
pd = map((analogRead(spd)), 0, 1023, 2000, 50);
if (pd < 1950) {
digitalWrite(driverDIR, setdir);
digitalWrite(driverPUL, HIGH);
delayMicroseconds(pd);
digitalWrite(driverPUL, LOW);
delayMicroseconds(pd);
}
}
void revmotor() {
static unsigned long lastAction;
static boolean ISRActive = false;
if (!ISRActive && millis() - lastAction > 500) {
ISRActive = true;
}
if (ISRActive) {
ISRActive = false;
setdir = !setdir;
lastAction = millis();
}
}