// Stepper motor control using A4988 module and Arduino Mega
// Define connections to the A4988 module
const int stepPin1 = 2; // Step pin
const int dirPin1 = 3; // Direction pin
const int enPin1 = 4; // Enable pin (set to LOW to enable)
const int stepPin2 = 5; // Step pin
const int dirPin2 = 6; // Direction pin
const int enPin2 = 7; // Enable pin (set to LOW to enable)
// Define some constants for motor control
const int stepsPerRevolution = 2000; // Number of steps for a full revolution
const int delayTime = 5; // Delay time between steps (in milliseconds)
void setup() {
// Set up the pins as outputs
pinMode(stepPin1, OUTPUT);
pinMode(dirPin1, OUTPUT);
pinMode(enPin1, OUTPUT);
pinMode(stepPin2, OUTPUT);
pinMode(dirPin2, OUTPUT);
pinMode(enPin2, OUTPUT);
// Set initial direction and enable the motor
digitalWrite(dirPin1, HIGH); // Set direction to clockwise
digitalWrite(enPin1, LOW); // Enable the motor
digitalWrite(dirPin2, HIGH); // Set direction to clockwise
digitalWrite(enPin2, LOW); // Enable the motor
}
void loop() {
// Rotate the motor in one direction
digitalWrite(dirPin1, HIGH); // Set direction to clockwise
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin1, HIGH);
delayMicroseconds(delayTime);
digitalWrite(stepPin1, LOW);
delayMicroseconds(delayTime);
}
delay(1000); // Wait for a second
// Rotate the motor in the other direction
digitalWrite(dirPin1, LOW); // Set direction to counterclockwise
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin1, HIGH);
delayMicroseconds(delayTime);
digitalWrite(stepPin1, LOW);
delayMicroseconds(delayTime);
}
delay(1000); // Wait for a second
// Rotate the motor in one direction
digitalWrite(dirPin2, HIGH); // Set direction to clockwise
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin2, HIGH);
delayMicroseconds(delayTime);
digitalWrite(stepPin2, LOW);
delayMicroseconds(delayTime);
}
delay(1000); // Wait for a second
// Rotate the motor in the other direction
digitalWrite(dirPin2, LOW); // Set direction to counterclockwise
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin2, HIGH);
delayMicroseconds(delayTime);
digitalWrite(stepPin2, LOW);
delayMicroseconds(delayTime);
}
delay(1000); // Wait for a second
}