// https://forum.arduino.cc/t/trying-to-use-a-limit-switch-to-change-the-direction-of-rotation-of-stepper-motor/1250150
#include <Servo.h> //Servo library
// Pin Definitions
#define LIMIT_SWITCH_PIN 7
#define dirPin 2 // Direction
#define stepPin 3 // Step Pulse
#define enaPin 4 // Enable Motor
// Variables
int stepDelay = 1250; // Delay between steps in microseconds
int stepsToMove = 800;
bool run = true;
//-------------------------------------------------------------
void setup() {
Serial.begin(9600);
pinMode(LIMIT_SWITCH_PIN, INPUT_PULLUP);
// // Set pin modes
pinMode(enaPin, OUTPUT);
digitalWrite(enaPin, LOW); // Enable motor
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
}
//-------------------------------------------------------------
void switchHit() {
digitalWrite(dirPin, HIGH); // Set direction to clockwise
for (int i = 0; i < stepsToMove; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(20);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay - 20);
}
run = false;
}
//-------------------------------------------------------------
void loop() {
if ( run == true) {
digitalWrite(dirPin, LOW); // Set direction to clockwise
for (int i = 0; i < stepsToMove; i++) {
if (digitalRead(LIMIT_SWITCH_PIN) == LOW) {
Serial.println("Activated!");
switchHit();
break;
}
digitalWrite(stepPin, HIGH);
delayMicroseconds(20);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay - 20);
}
delay(3000); // Delay for 1 second
}
}