// Stepper motor control using A4988 module and Arduino Mega
// Define connections to the A4988 module
const int stepPin = 2; // Step pin
const int dirPin = 3; // Direction pin
const int enPin = 4; // Enable pin (set to LOW to enable)
// Define some constants for motor control
const int stepsPerRevolution = 200; // 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(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enPin, OUTPUT);
// Set initial direction and enable the motor
digitalWrite(dirPin, HIGH); // Set direction to clockwise
digitalWrite(enPin, LOW); // Enable the motor
}
void loop() {
// Rotate the motor in one direction
digitalWrite(dirPin, HIGH); // Set direction to clockwise
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(delayTime);
digitalWrite(stepPin, LOW);
delayMicroseconds(delayTime);
}
delay(1000); // Wait for a second
// Rotate the motor in the other direction
digitalWrite(dirPin, LOW); // Set direction to counterclockwise
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(delayTime);
digitalWrite(stepPin, LOW);
delayMicroseconds(delayTime);
}
delay(1000); // Wait for a second
}