#include <Stepper.h>
#define encoderPinA 12
#define encoderPinB 13
// Motor specifications
const int stepsPerRevolution = 200; // Number of steps per revolution for your stepper motor
// Initialize the stepper library
Stepper stepperMotor(stepsPerRevolution, 2, 3); // Pins connected to step and direction pins of A4988
int encoderPos = 0; // Current position of the rotary encoder
int lastEncoderAState = 0; // Previous state of the encoder A pin
int lastEncoderBState = 0; // Previous state of the encoder B pin
// Desired rotation variables
float targetAngle = 30.0; // Target angle in degrees
int targetSteps = 0; // Target number of steps (calculated from the target angle)
int currentSteps = 0; // Current steps taken by the motor
float currentAngle = 0;
unsigned long previousMillis = 0; // To store last time the motor was stepped
const long interval = 50; // Interval between steps (in milliseconds)
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
stepperMotor.setSpeed(100); // Speed in RPM
pinMode(encoderPinA, INPUT);
pinMode(encoderPinA, INPUT);
// Initialize encoder's previous states
lastEncoderAState = digitalRead(encoderPinA);
lastEncoderBState = digitalRead(encoderPinB);
// Calculating the target steps based on the target angle
targetSteps = angleToSteps(targetAngle);
}
void loop() {
// put your main code here, to run repeatedly:
unsigned long currentMillis = millis();
// Check the encoder to update position
int encoderAState = digitalRead(encoderPinA);
int encoderBState = digitalRead(encoderPinB);
// Detect rotation by comparing the current encoder state with the previous one
if (encoderAState =! lastEncoderAState) {
// Determine the direction of rotation based on the B channel state
if (encoderBState =! encoderAState) {
//Serial.println("Motor rotating clockwise");
encoderPos++;
} else {
//Serial.println()("Motor rotating anti-clockwise");
encoderPos--;
}
}
// Update last states
lastEncoderAState = encoderAState;
lastEncoderBState = encoderBState;
// Move the stepper motor based on the desired angle and stop once the target is reached
while (currentSteps < targetSteps) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
stepperMotor.step(1); // Step forward
currentAngle = (targetSteps*360 / stepsPerRevolution);
Serial.println(currentSteps);
Serial.println(currentAngle);
currentSteps++; // Increment current steps
}
}
}
// Function to convert the desired angle into steps
int angleToSteps(float angle) {
// (stepsPerRevolution / 360) gives the number of steps for 1 degree
return (int)(angle * stepsPerRevolution / 360);
}