#include // Define the number of steps per revolution for the stepper motor const int stepsPerRevolution = 16000; // Define motor pins using #define #define STEP_PIN D1 #define DIR_PIN D0 #define ENABLE_PIN D5 // Define encoder pins #define CLK D9 // GPIO 9 #define DT D8 // GPIO 8 #define SW 0 // GPIO 0 (assuming this is your button pin) AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN); int lastStateCLK; // Last state of CLK unsigned long lastButtonPress = 0; // Time of last button press void setup() { // Set motor pins as outputs pinMode(STEP_PIN, OUTPUT); pinMode(DIR_PIN, OUTPUT); pinMode(ENABLE_PIN, OUTPUT); // Setup encoder pins as inputs with internal pull-up resistors pinMode(CLK, INPUT_PULLUP); pinMode(DT, INPUT_PULLUP); pinMode(SW, INPUT_PULLUP); // Setup Serial Monitor Serial.begin(115200); // Set motor properties stepper.setMaxSpeed(8000); // Adjust this value for desired speed stepper.setAcceleration(6000); // Adjust this value for desired smoothness // Read the initial state of CLK lastStateCLK = digitalRead(CLK); } void loop() { // Read the current state of CLK int currentStateCLK = digitalRead(CLK); // If last and current state of CLK are different, then pulse occurred // React to only 1 state change to avoid double count if (currentStateCLK != lastStateCLK && currentStateCLK == 1) { // If the DT state is different than the CLK state then // the encoder is rotating CCW so decrement the motor position if (digitalRead(DT) != currentStateCLK) { stepper.move(-stepsPerRevolution); // Move motor one step CCW } else { // Encoder is rotating CW so increment the motor position stepper.move(stepsPerRevolution); // Move motor one step CW } } // Remember last CLK state lastStateCLK = currentStateCLK; // Read the button state int btnState = digitalRead(SW); // If we detect LOW signal, button is pressed if (btnState == LOW) { // If 50ms have passed since last LOW pulse, it means that the // button has been pressed, released, and pressed again if (millis() - lastButtonPress > 50) { // Toggle motor enable pin to start/stop motor movement digitalWrite(ENABLE_PIN, !digitalRead(ENABLE_PIN)); if (digitalRead(ENABLE_PIN)) { Serial.println("Motor Enabled"); } else { Serial.println("Motor Disabled"); } } // Remember last button press event lastButtonPress = millis(); } // Continuously update the motor state (important for movement) stepper.run(); }