/*
Forum: https://forum.arduino.cc/t/turning-a-stepper-motor-off-and-on/1168572
Wokwi: https://wokwi.com/projects/375869577129168897
*/
// 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);
}
void loop() {
checkReverseButton();
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 checkReverseButton() {
static unsigned long lastChange = 0;
static byte state = HIGH;
static byte lastDetected = HIGH;
byte detected = digitalRead(reverseSwitch);
if (detected != lastDetected) {
lastDetected = detected;
lastChange = millis();
}
if (millis() - lastChange > 30 && state != lastDetected) {
state = lastDetected;
if (state == LOW) {
setdir = !setdir;
}
}
}