#include <Stepper.h>
const int stepsPerRevolution = 200; // Number of steps per revolution for your motor
const int stepSegment = 20; // Segment size (20 steps per segment)
Stepper myStepper(stepsPerRevolution, 10, 11, 12, 13);
#define LimitBtn 9
byte lastLimitBtnState = HIGH; // Set initial state to HIGH for INPUT_PULLUP
unsigned long debounceDuration = 50; // millis
unsigned long lastTimeLimitBtnStateChanged = 0;
void setup() {
pinMode(LimitBtn, INPUT_PULLUP);
myStepper.setSpeed(10); // Set motor speed to 10 RPM
Serial.begin(9600);
// Find home position at startup
Serial.println("Finding home position...");
while (digitalRead(LimitBtn) == HIGH) { // Move until the limit switch is LOW
myStepper.step(-1); // Move step by step in a direction to find home
delay(10); // Small delay between steps
}
Serial.println("Home position found!");
}
void loop() {
// Handle Limit Button
if (millis() - lastTimeLimitBtnStateChanged > debounceDuration) {
byte limitBtnState = digitalRead(LimitBtn);
if (limitBtnState != lastLimitBtnState) {
lastTimeLimitBtnStateChanged = millis();
lastLimitBtnState = limitBtnState;
if (limitBtnState == LOW) {
// Move clockwise when the limit button is pressed
Serial.println("clockwise");
myStepper.step(200);
delay(500);
} else {
// Stop when the limit button is released (HIGH)
Serial.println("stopped");
myStepper.step(0); // Stop the motor
delay(500);
}
}
}
}