// // Include the AccelStepper library:
// #include <AccelStepper.h>
// // Define stepper motor connections and motor interface type.
// // Motor interface type must be set to 1 when using a driver
// #define dirPin 2
// #define stepPin 3
// #define motorInterfaceType 1
// // Create a new instance of the AccelStepper class:
// AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);
// void setup() {
// pinMode(8, INPUT_PULLUP);
// Serial.begin(9600);
// // Set the maximum speed in steps per second:
// stepper.setMaxSpeed(1000);
// stepper.setAcceleration(100.0);
// Serial.println(digitalRead(8));
// while (digitalRead(8)) {
// stepper.setSpeed(-200);
// stepper.runSpeed();
// }
// }
// void loop() {
// // while (digitalRead(8)) {
// stepper.setSpeed(200);
// stepper.runSpeed();
// // }
// // Set the speed in steps per second:
// // stepper.setSpeed(400);
// // // Step the motor with a constant speed as set by setSpeed():
// // stepper.runSpeed();
// }
#include <AccelStepper.h>
// Define stepper motor connections and motor interface type.
// Motor interface type must be set to 1 when using a driver
#define dirPin 5
#define stepPin 6
#define motorInterfaceType 1
// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);
// Define the pins for the rotary encoder
#define ENCODER_PIN_A 2
#define ENCODER_PIN_B 3
// Variables to track encoder state
// Variables to track encoder state
int lastStateA;
int lastStateB;
void setup() {
Serial.begin(9600);
// Set up the stepper motor
stepper.setMaxSpeed(1000); // Adjust as needed
stepper.setAcceleration(500); // Adjust as needed
stepper.setCurrentPosition(0);
// Initialize the last state of encoder pins
lastStateA = digitalRead(ENCODER_PIN_A);
lastStateB = digitalRead(ENCODER_PIN_B);
}
void loop() {
// Read the current state of encoder pins
int currentStateA = digitalRead(ENCODER_PIN_A);
int currentStateB = digitalRead(ENCODER_PIN_B);
// Check for changes in encoder state
if (currentStateA != lastStateA || currentStateB != lastStateB) {
// Determine the direction of rotation
if (currentStateA != lastStateA) {
int direction = (currentStateA == currentStateB) ? 1 : -1;
Serial.println(direction);
// Move the stepper motor one step in the appropriate direction
stepper.move(direction);
stepper.runToPosition();
}
// Update the last state of encoder pins
lastStateA = currentStateA;
lastStateB = currentStateB;
}
}