Sub topic 13
Using the Stepper and AccelStepper Libraries
This chapter assumes you know setup(), loop(), and basic Arduino output. It also assumes your motor is connected to a suitable driver or H-bridge. Do not connect a motor directly to Arduino pins.
The `Stepper` library
The built-in Stepper library is simple. You give it the number of motor steps per revolution, set a speed in revolutions per minute (RPM), and request a number of steps.
#include <Stepper.h>
const int STEPS_PER_REV = 200;
Stepper motor(STEPS_PER_REV, 8, 9, 10, 11);
void setup() {
motor.setSpeed(60); // 60 revolutions per minute
}
void loop() {
motor.step(STEPS_PER_REV);
delay(500);
motor.step(-STEPS_PER_REV);
delay(500);
}For a bipolar motor, the four constructor pins control the H-bridge inputs. The correct pin order depends on the driver board. The step() function blocks, which means the Arduino waits until the requested movement finishes. Other code cannot run during that movement.
This library is useful for short, simple movements. It does not provide acceleration ramps, position limits, or non-blocking motion.
The `AccelStepper` library
AccelStepper is an external library that supports acceleration and several driver types. Install it through the Arduino IDE Library Manager.
With a STEP/DIR driver, create the object using AccelStepper::DRIVER. Speed is measured in steps per second, not RPM.
#include <AccelStepper.h>
const int STEP_PIN = 3;
const int DIR_PIN = 4;
AccelStepper motor(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
void setup() {
motor.setMaxSpeed(1000); // maximum steps per second
motor.setAcceleration(500); // steps per second squared
motor.moveTo(800); // absolute target position
}
void loop() {
static bool forward = true;
if (motor.distanceToGo() == 0) {
forward = !forward;
motor.moveTo(forward ? 800 : 0);
}
motor.run();
}moveTo() sets an absolute target. move() instead requests a relative distance. run() must be called repeatedly. Each call may generate a pulse or update the acceleration ramp. Do not put a long delay() in the loop, or the motor may stop between pulses.
The driver still needs its current limit set correctly. The library controls timing, but it cannot protect a motor or driver from excessive current.
Choosing between the libraries
| Need | Recommended library |
|---|---|
| One blocking move with minimal code | `Stepper` |
| Smooth acceleration and responsive control | `AccelStepper` |
| STEP/DIR driver control | `AccelStepper` |
Exercise
Why can an AccelStepper motor appear not to move when the program calls moveTo() but never calls run()?
Show answer
moveTo() only changes the target position. run() must be called repeatedly to generate the step pulses.