Welcome! Share code as fast as possible.

// Stepper Motor Control with TB6600 Driver & Arduino Mega 2560
// Moves gantry in one dimension based on user input (position in mm).

// Pin Definitions
const int STEP_PIN = 5;
const int DIR_PIN = 2;
const int EN_PIN = 8;

// Stepper Motor & Belt System Parameters
const int MOTOR_STEPS_PER_REV = 200;    // Motor full steps per revolution
const int MICROSTEP_SETTING = 16;       // Microstepping level (1, 2, 4, 8, 16, etc.)
const float BELT_PITCH = 2.0;           // Belt pitch in mm (distance between two teeth)
const int PULLEY_TEETH = 20;            // Pulley teeth count

// Derived Parameters
const float MM_PER_REV = BELT_PITCH * PULLEY_TEETH;  // Linear distance per full motor rev
const int STEPS_PER_REV = MOTOR_STEPS_PER_REV * MICROSTEP_SETTING;
const float STEPS_PER_MM = STEPS_PER_REV / MM_PER_REV;

float currentPosition = 0.0;  // Track current position in mm

// Function Prototypes
void moveToPosition(float targetPosition);
void printMotorInfo();

void setup() {
    // Initialize pins
    pinMode(STEP_PIN, OUTPUT);
    pinMode(DIR_PIN, OUTPUT);
    pinMode(EN_PIN, OUTPUT);
    
    // Enable stepper driver
    digitalWrite(EN_PIN, LOW);

    // Start serial communication
    Serial.begin(9600);
    delay(500);

    // Print startup information
    Serial.println("\n=== Stepper Motor Controller ===");
    printMotorInfo();
    Serial.println("\nEnter a position in mm (e.g., 100) to move the piece.");
}

void loop() {
    // Check for user input
    if (Serial.available()) {
        String input = Serial.readStringUntil('\n'); // Read input line
        input.trim();  // Remove any extra spaces or newlines

        // Convert input to float
        float targetPosition = input.toFloat();

        // Validate input
        if (!isnan(targetPosition)) {
            moveToPosition(targetPosition);
        } else {
            Serial.println("Invalid input! Please enter a valid number.");
        }
    }
}

// Function to move the stepper motor to a given position in mm
void moveToPosition(float targetPosition) {
    // Calculate movement parameters
    float distance = targetPosition - currentPosition;
    int stepCount = abs(distance * STEPS_PER_MM);
    int direction = (distance >= 0) ? HIGH : LOW;

    // Print movement info
    Serial.print("Moving to ");
    Serial.print(targetPosition);
    Serial.print(" mm (");
    Serial.print(stepCount);
    Serial.println(" steps)...");

    // Set direction
    digitalWrite(DIR_PIN, direction);

    // Move stepper motor
    for (int i = 0; i < stepCount; i++) {
        digitalWrite(STEP_PIN, HIGH);
        delayMicroseconds(500);
        digitalWrite(STEP_PIN, LOW);
        delayMicroseconds(500);
    }

    // Update current position
    currentPosition = targetPosition;

    // Confirm movement completion
    Serial.print("Reached position: ");
    Serial.print(currentPosition);
    Serial.println(" mm");
}