// Define the pins for controlling the stepper motor
const int stepPin = 2; // Step pin
const int dirPin = 3; // Direction pin
// Define the ratio for your motor driver
const float ratio = 16.0; // 16:1 reduction ratio
// Define a variable to store the current position of the motor
int currentPosition = 0;
// Define a variable to store the target position
int targetPosition = 0;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the motor control pins as outputs
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
Serial.println("Start");
}
void loop() {
// Check if there's data available on the serial port
if (Serial.available() > 0) {
// Read the available data
int target = Serial.parseInt();
// Check if the data is valid
if (Serial.read() == '\n') {
// Store the target position
targetPosition = target;
// Calculate the distance between positions and move the motor accordingly
int distanceToMove = targetPosition - currentPosition;
if (distanceToMove != 0) {
moveStepper(distanceToMove);
// Update the current position
currentPosition = targetPosition;
}
}
}
}
// Function to move the stepper motor
void moveStepper(int steps) {
// Set the direction of movement based on the sign of steps
if (steps > 0) {
digitalWrite(dirPin, HIGH); // Clockwise direction
} else {
digitalWrite(dirPin, LOW); // Counter-clockwise direction
}
// Take the absolute value of steps
steps = abs(steps);
// Calculate the actual number of steps to move based on the ratio
int actualSteps = steps * ratio;
// Pulse the step pin to move the motor
for (int i = 0; i < actualSteps; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(500); // Adjust this delay as needed for your motor
digitalWrite(stepPin, LOW);
delayMicroseconds(500); // Adjust this delay as needed for your motor
}
}