#include <AccelStepper.h>
// Konfigurasi pin untuk driver A4988
#define STEP_PIN 2
#define DIR_PIN 3
#define ENABLE_PIN 4
// Konfigurasi pin untuk rotary encoder
#define ENCODER_PIN_A 5
#define ENCODER_PIN_B 6
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
int lastEncoderValue = 0;
void setup() {
pinMode(ENABLE_PIN, OUTPUT);
digitalWrite(ENABLE_PIN, LOW); // Aktifkan driver
pinMode(ENCODER_PIN_A, INPUT_PULLUP);
pinMode(ENCODER_PIN_B, INPUT_PULLUP);
stepper.setMaxSpeed(1000); // Atur kecepatan maksimum stepper motor
stepper.setAcceleration(500); // Atur percepatan stepper motor
}
void loop() {
int encoderValue = readEncoder();
if (encoderValue > lastEncoderValue) {
stepper.move(10); // Atur langkah yang ingin ditempuh ke depan
} else if (encoderValue < lastEncoderValue) {
stepper.move(-10); // Atur langkah yang ingin ditempuh ke belakang
}
lastEncoderValue = encoderValue;
stepper.run(); // Jalankan stepper motor
}
int readEncoder() {
static int oldA = HIGH;
static int oldB = HIGH;
int result = 0;
int newA = digitalRead(ENCODER_PIN_A);
int newB = digitalRead(ENCODER_PIN_B);
if (newA != oldA || newB != oldB) {
if (oldA == HIGH && newA == LOW) {
result = (oldB == HIGH) ? 1 : -1;
}
}
oldA = newA;
oldB = newB;
return result;
}