// Define stepper motor connections and steps per revolution:
#define dirPin 4
#define stepPin 2
#define stepsPerRevolution 6  // 10 degrees per step (360 degrees / 10 degrees)

// Define rotary encoder pins
#define encoderPinA 15
#define encoderPinB 17

volatile int encoderPos = 0;
volatile int lastEncoderPos = 0;

void setup() {
  // Declare pins as output:
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);

  // Declare rotary encoder pins as input with internal pull-up resistors:
  pinMode(encoderPinA, INPUT_PULLUP);
  pinMode(encoderPinB, INPUT_PULLUP);

  // Attach interrupt to handle rotary encoder input
  attachInterrupt(digitalPinToInterrupt(encoderPinA), handleEncoder, CHANGE);
}

void loop() {
  // Check if the encoder position has changed
  if (encoderPos != lastEncoderPos) {
    // Move the stepper motor by one step in the clockwise direction
    digitalWrite(dirPin, HIGH);
    for (int i = 0; i < stepsPerRevolution; i++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(2000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(2000);
    }

    // Update the last encoder position
    lastEncoderPos = encoderPos;
  }

  // Add any other non-blocking tasks or delays as needed
}

void handleEncoder() {
  // Read the rotary encoder state
  int encoderAState = digitalRead(encoderPinA);

  // Increment or decrement position based on the direction of rotation
  encoderPos += (encoderAState == HIGH) ? 1 : -1;
}
A4988
A4988