How to properly use MKS Servo42D/57D

‘COM’ terminal connects to 3.3V Positive on ESP32 DEV

Pulse Mode. The following code for reference to test the motor. VS Code + PlatformIO:

// ESP32-WROOM-32E Dev Board Testing
// MKS Closed Loop Stepper Motor Drive Board
// COM 

#include <Arduino.h>
#include <ESP32Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

const int endstopPin = 25;
const int ENA_PIN = 21;
const int STEP_PIN = 18;
const int DIR_PIN = 19;
const int PULSE_HIGH = 100;
const int PULSE_LOW = 100;
const int REV = 1000;


// LCD address may vary (usually 0x27)
LiquidCrystal_I2C lcd(0x27, 16, 2);

bool running = true;
int pos = 0;
int steps = 3200;   //based on Microstep configured: 1/16;

void setup() {

  pinMode(STEP_PIN,OUTPUT);
  pinMode(DIR_PIN,OUTPUT);
  pinMode(ENA_PIN,OUTPUT);

  digitalWrite(ENA_PIN,LOW);
  digitalWrite(DIR_PIN,HIGH);
  delay(50);

  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Status:");
  lcd.setCursor(0, 1);
  lcd.print("Rev:");

  digitalWrite(DIR_PIN,HIGH);

}


void stepPulses(int pulses) {
  // ensure DIR is stable before stepping
  for (unsigned long i = 0; i < pulses; ++i) {
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(PULSE_HIGH);
    digitalWrite(STEP_PIN, LOW);
    delayMicroseconds(PULSE_LOW);
  }
}


void loop() {
  // --- Clockwise rotation ---
  Serial.println("Moving clockwise...");
  digitalWrite(DIR_PIN, HIGH); // CW
  for (int i = 0; i < steps; i++) {
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(200);
    digitalWrite(STEP_PIN, LOW);
    delayMicroseconds(200);
  }
  delay(500); // short pause

  // --- Counterclockwise rotation ---
  Serial.println("Moving counterclockwise...");
  digitalWrite(DIR_PIN, LOW); // CCW
  for (int i = 0; i < steps; i++) {
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(200);
    digitalWrite(STEP_PIN, LOW);
    delayMicroseconds(200);
  }
  delay(1000); // pause before next cycle
}

// void loop() {

//   stepPulses(steps * REV);
//   delay(1000);
//   // Display motor status

//   digitalWrite(DIR_PIN, !digitalRead(DIR_PIN));

//   lcd.setCursor(8, 0);
//   lcd.print(running ? "RUN " : "STOP");

// }

Leave a Comment