Hi guys a complete beginner here trying to get my hands dirty in the world of Arduino, i am trying to use a limit switch to change the direction of rotation of the Nema23 Stepper motor. What I want to achieve is say that the stepper motor is rotating in clockwise direction at a low rpm, say If the limit switch is pressed it should complete one entire circle in the anti-clockwise direction/opposite direction and should break out of the clockwise/(earlier direction of) rotation.
#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;
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);
for (int i = 0; i < stepsToMove; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(20);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay - 20);
}
}
void loop() {
digitalWrite(dirPin, LOW);
for (int i = 0; i < stepsToMove; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(20);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay - 20);
if (digitalRead(LIMIT_SWITCH_PIN) == LOW) {
switchHit();
break;
}
}
delay(3000);
Here is the code that I am using.
The problem I am facing is that, say the stepper motor is in the process of rotating in a specific direction and I press the limit switch it changes direction but doesn't complete one full rotation in the opposite direction for some reason, it misses some steps, and ideas how can this be fixed?
Any help would be greatly appreciated.
20 posts - 3 participants