This tutorial demonstrates how to control a stepper motor using a driver like the A4988 or DRV8825 and an Arduino. Stepper motors are commonly used in CNC machines, 3D printers, and other projects that require precise control over rotation and movement.
Connect the components as follows:
The following code will rotate the stepper motor in both directions, controlling its speed and steps using the driver.
#define DIR_PIN 4
#define STEP_PIN 3
#define STEPS_PER_REV 200
void setup() {
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
}
void loop() {
// Rotate Clockwise
digitalWrite(DIR_PIN, HIGH);
stepMotor(200);
delay(1000);
// Rotate Counterclockwise
digitalWrite(DIR_PIN, LOW);
stepMotor(200);
delay(1000);
}
void stepMotor(int steps) {
for (int i = 0; i < steps; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000); // Speed adjustment
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(1000);
}
}
In this code, the **DIR_PIN** controls the direction of the motor. A HIGH signal moves the motor in one direction, while a LOW signal moves it in the opposite direction. The **STEP_PIN** sends pulses to the driver to move the motor one step at a time. You can adjust the delay between pulses to control the motor speed.
The function stepMotor()
takes an integer argument for the number of steps the motor should rotate. In the loop, the motor rotates 200 steps clockwise and then 200 steps counterclockwise, with a 1-second delay between movements.
You can control the speed by modifying the delayMicroseconds()
function in the stepMotor()
function. A smaller delay will result in faster rotation. To change the number of steps per revolution, modify the STEPS_PER_REV
constant to match your stepper motor’s specifications.
Upload the code to your Arduino. Once uploaded, the stepper motor should rotate in one direction, stop for a second, and then rotate in the opposite direction. If the motor doesn't move, check the wiring and connections, and ensure the stepper driver is properly configured.
In this project, you learned how to control a stepper motor using a driver and an Arduino. You can expand this project by adding buttons or potentiometers to control speed and direction in real-time. Stepper motors offer precise control, making them suitable for projects that require accurate movements.