#include <AccelStepper.h>
#define ENCODER_CLK 15 // Change this to the desired CLK pin on ESP32
#define ENCODER_DT 27 // Change this to the desired DT pin on ESP32
// Motor configuration
#define MOTOR_STEP_PIN 2
#define MOTOR_DIR_PIN 4
AccelStepper motor(AccelStepper::DRIVER, MOTOR_STEP_PIN, MOTOR_DIR_PIN);
void setup() {
Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
motor.setMaxSpeed(1000.0);
motor.setAcceleration(500.0);
}
int lastClk = HIGH;
int encoderSteps = 0;
void loop() {
int newClk = digitalRead(ENCODER_CLK);
int dtValue = digitalRead(ENCODER_DT);
if (newClk != lastClk) {
lastClk = newClk;
if (newClk == LOW && dtValue == HIGH) {
// Clockwise rotation
encoderSteps++;
if (encoderSteps >= 20) {
encoderSteps = 0; // Reset to 0 after 20 steps
}
}
if (newClk == LOW && dtValue == LOW) {
// Counterclockwise rotation
encoderSteps--;
if (encoderSteps < 0) {
encoderSteps = 19; // Wrap to 19 after -1 step
}
}
Serial.print("Encoder Steps: ");
Serial.println(encoderSteps);
// Control the motor based on encoder steps
if (encoderSteps >= 0 && encoderSteps <= 5) {
// Motor moves clockwise
motor.setSpeed(20);
motor.runSpeed();
Serial.println("Motor: Clockwise");
} else if (encoderSteps >= 6 && encoderSteps <= 10) {
// Motor moves counterclockwise
motor.setSpeed(-20);
motor.runSpeed();
Serial.println("Motor: Counterclockwise");
} else {
// Motor stops
motor.setSpeed(0);
motor.runSpeed();
Serial.println("Motor: Stopped");
}
}
}