//https://www.circuits-diy.com/stepper-motor-and-limit-switch-arduino-tutorial/
#include <ezButton.h>
#include <AccelStepper.h>
#define STEPPER1_DIR_PIN 16
#define STEPPER1_STEP_PIN 17
#define DIRECTION_CCW -1
#define DIRECTION_CW 1
#define MAX_POSITION 0x7FFFFFFF // maximum of position we can set (long type)
ezButton limitSwitch(23); // create ezButton object that attach to pin A0;
AccelStepper stepper1(AccelStepper::DRIVER, STEPPER1_STEP_PIN, STEPPER1_DIR_PIN);
int count = 0;
int direction = DIRECTION_CW;
long targetPos = 0;
void setup() {
Serial.begin(9600);
limitSwitch.setDebounceTime(20); // set debounce time to 50 milliseconds
stepper1.setMaxSpeed(500.0); // set the maximum speed
stepper1.setAcceleration(50.0); // set acceleration
stepper1.setSpeed(100); // set initial speed
stepper1.setCurrentPosition(0); // set position
targetPos = direction * MAX_POSITION;
stepper1.moveTo(targetPos);
}
void loop() {
limitSwitch.loop(); // MUST call the loop() function first
if (limitSwitch.isPressed()) {
count++;
Serial.print(F("The limit switch: TOUCHED count= "));
Serial.println(count);
//direction *= -1; // change direction
//Serial.print(F("The direction -> "));
//if (direction == DIRECTION_CW)
//Serial.println(F("CLOCKWISE"));
//else
// Serial.println(F("ANTI-CLOCKWISE"));
targetPos = direction * MAX_POSITION;
stepper1.setCurrentPosition(0); // set position
stepper1.moveTo(targetPos);
}
// without this part, the move will stop after reaching maximum position
if (stepper1.distanceToGo() == 0) { // if motor moved to the maximum position
stepper1.setCurrentPosition(0); // reset position to 0
stepper1.moveTo(targetPos); // move the motor to maximum position again
}
stepper1.run(); // MUST be called in loop() function
}