#include <AccelStepper.h>
// Define pins for the switch and stepper driver
const int switchPin1 = 2; // one side of the switch
const int switchPin2 = 3; // the other side of the switch
const int pulPin = 11; // Pulse pin for stepper driver
const int dirPin = 12; // Direction pin for stepper driver
// Create an instance of AccelStepper
AccelStepper stepper(AccelStepper::DRIVER, pulPin, dirPin);
void setup() {
// Set switch pins as input with internal pull-up resistors
pinMode(switchPin1, INPUT_PULLUP);
pinMode(switchPin2, INPUT_PULLUP);
// Set up stepper parameters
stepper.setMaxSpeed(1000); // Set max speed
stepper.setAcceleration(500); // Set acceleration
}
void loop() {
// Read the states of the switch pins
int switchState1 = digitalRead(switchPin1);
int switchState2 = digitalRead(switchPin2);
if (switchState1 == LOW && switchState2 == HIGH) { // Switch is on one side
stepper.move(800); // Rotate one revolution clockwise
} else if (switchState1 == HIGH && switchState2 == LOW) { // Switch is on the other side
stepper.move(-800); // Rotate one revolution counter-clockwise
} else { // Switch is in the middle
stepper.stop(); // Stop the motor
stepper.runToPosition(); // Ensure motor halts smoothly
}
// Update the stepper's position
stepper.run();
}