Sub topic 13
Using the Stepper and AccelStepper libraries
This chapter assumes you can already wire a motor to a driver, set its current limit, and compute a step rate from an RPM target. It covers two Arduino libraries that generate the pulses for you. They differ in what hardware they drive, whether they block, and how they handle speed changes.
Two libraries, two jobs
The Stepper library ships with the Arduino IDE. It energizes the motor coils directly through two or four pins, so it suits an H-bridge board or a ULN2003 board. It does not produce STEP and DIR signals. AccelStepper is a separate library you install from the Library Manager. It supports STEP/DIR drivers and 4-wire H-bridges, and it adds acceleration and non-blocking motion.
| Feature | Stepper | AccelStepper |
|---|---|---|
| Install | Bundled | Library Manager |
| STEP/DIR drivers (A4988, DRV8825, TMC) | No | Yes (`DRIVER` mode) |
| Direct coil drive | 2 or 4 pins | `FULL2WIRE`, `FULL4WIRE`, `HALF4WIRE` and others |
| Blocking calls | `step()` blocks | `run()` does not block |
| Acceleration | None | Yes |
| Speed unit | Whole RPM | Steps per second (float) |
| Multiple motors at once | Awkward | Easy, call `run()` on each |
The Stepper library
Stepper takes the steps per revolution and the control pins. setSpeed() takes whole RPM and only stores a delay. Nothing moves until you call step(), and step() returns only after the last step is done.
#include <Stepper.h>
const int STEPS_PER_REV = 200;
Stepper stepper(STEPS_PER_REV, 8, 9, 10, 11);
void setup() {
stepper.setSpeed(60); // RPM, integer
}
void loop() {
stepper.step(STEPS_PER_REV); // blocks about 1 s at 60 RPM
delay(500);
stepper.step(-STEPS_PER_REV); // negative means reverse
delay(500);
}At 60 RPM and 200 steps per revolution, the library waits 60,000,000 / (200 × 60) = 5000 µs between steps. A 200-step call therefore holds the processor for one second. Nothing else in loop() runs during that time, including button reads and serial parsing.
The main limits of Stepper:
- No ramp. The motor jumps straight to the set speed, so high speeds under load will stall it.
- Integer RPM.
setSpeed(0.5)is not possible. The argument is along. - Pin order matters. For a 28BYJ-48 on a ULN2003 board, the usual order is
Stepper(2048, 8, 10, 9, 11). A wrong order makes the motor shake without turning. - Not for STEP/DIR drivers. If you pass a driver's STEP and DIR pins in two-pin mode, the library treats them as coil-phase outputs, and the result is not what you want.
AccelStepper basics
With a STEP/DIR driver, you create the object in DRIVER mode. The argument order is the interface, then STEP, then DIR.
AccelStepper stepper(AccelStepper::DRIVER, 3, 4);You then work in steps, not revolutions. Convert RPM yourself, using the microstepped steps per revolution:
steps_per_second = rpm × steps_per_rev × microstep_factor / 60Four calls define a move:
setMaxSpeed(s)sets the cruising speed in steps per second. It has no default, so a missing call means the motor will not move.setAcceleration(a)sets the ramp in steps per second squared.moveTo(p)sets an absolute target position.move(n)sets a target relative to the current position.run()advances the motor if a step is due. It returnstruewhile the motor still has work to do.
run() does at most one step per call. It compares micros() against the time of the next step. The motor therefore only reaches its set speed if loop() calls run() often enough. A delay() or a long Serial.print between calls causes uneven steps, which you hear as a stutter.
A complete non-blocking example
This sketch sweeps a microstepped motor back and forth with a ramp. It also blinks the built-in LED from millis() to show that the motion does not block. The driver is set to 1/16 microstepping, so one revolution is 3200 steps. The enable pin is active low, as on an A4988 or DRV8825.
#include <AccelStepper.h>
const int STEP_PIN = 3;
const int DIR_PIN = 4;
const int ENABLE_PIN = 5;
const int STEPS_PER_REV = 200 * 16; // 1/16 microstepping
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
unsigned long lastBlink = 0;
float rpmToStepsPerSec(float rpm) {
return rpm * STEPS_PER_REV / 60.0f;
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
stepper.setEnablePin(ENABLE_PIN);
stepper.setPinsInverted(false, false, true); // dir, step, enable
stepper.setMaxSpeed(rpmToStepsPerSec(60)); // 3200 steps/s
stepper.setAcceleration(rpmToStepsPerSec(120)); // 6400 steps/s^2
stepper.enableOutputs();
stepper.moveTo(2 * STEPS_PER_REV); // two revolutions
}
void loop() {
if (stepper.distanceToGo() == 0) {
stepper.moveTo(-stepper.currentPosition()); // reverse the target
}
stepper.run();
if (millis() - lastBlink >= 500) {
lastBlink = millis();
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
}The ramp numbers can be checked. Accelerating from rest to 3200 steps/s at 6400 steps/s² takes 0.5 s and covers v² / 2a = 3200² / 12800 = 800 steps. The move is 6400 steps, so the motor reaches full speed, cruises, and then decelerates over the final 800 steps. If a move is shorter than 1600 steps, the motor never reaches setMaxSpeed(). It uses a triangular profile instead.
Choosing blocking or non-blocking calls
AccelStepper also has blocking helpers: runToPosition() and runToNewPosition(p). They are handy for a homing routine or a quick test, but they bring back the problem of a frozen loop(). For anything with inputs, use run() in the main loop.
runSpeed() is the constant-speed variant. It ignores acceleration, uses setSpeed(), and does not stop at a target. It is useful for something like a turntable that spins until told to stop.
stepper.setSpeed(1600); // steps per second, negative reverses
// in loop():
stepper.runSpeed();Do not mix these calls casually. setSpeed() and runSpeed() belong to the constant-speed mode. moveTo() and run() belong to the ramped mode, which recomputes the speed itself.
Limits and gotchas
- Step rate ceiling. On a 16 MHz AVR board such as an Uno, AccelStepper manages roughly 4000 steps per second for one motor, fewer with several motors. At 1/16 microstepping, 4000 steps/s is only 75 RPM. A request for 300 RPM at 3200 steps per revolution needs 16,000 steps/s, which
run()cannot deliver. The motor then runs at the achievable rate, not the one you asked for. Use a lower microstep setting, a faster board (ESP32, Teensy, RP2040), or a hardware-timer-based library. run()starvation. Serial prints,delay(), display updates andpulseIn()all stretch the gap between calls. Keep them short or rate-limit them withmillis().- Pulse width. The default minimum pulse is very short on fast boards. If a driver misses steps, call
setMinPulseWidth(2)to meet drivers such as the A4988 or DRV8825. Check your driver's datasheet. - Position is a counter, not a measurement.
currentPosition()counts steps you commanded. If the motor stalled, the counter is wrong. UsesetCurrentPosition(0)after homing against a limit switch. - Stopping.
stop()sets a new target that decelerates at the current rate. It does not halt instantly. Keep callingrun()until it returnsfalse. - Power-down.
disableOutputs()removes holding torque and cuts heat. The load may then move freely.
Choosing between them
Use Stepper for a simple fixed-speed demo with a ULN2003 or H-bridge and a small motor. Use AccelStepper for a STEP/DIR driver, for any load that needs a ramp, or whenever the sketch must do other work. For most projects in this tutorial, AccelStepper is the correct default.
Exercise
A driver is set to 1/8 microstepping on a 200-step motor. You want a maximum of 120 RPM and a ramp from rest to full speed in 0.4 s. What values do you pass to setMaxSpeed() and setAcceleration()?
Show answer
Steps per revolution = 200 × 8 = 1600. Maximum speed = 120 × 1600 / 60 = 3200 steps/s, so setMaxSpeed(3200). Acceleration = 3200 / 0.4 = 8000 steps/s², so setAcceleration(8000).
Exercise
Your AccelStepper sketch moves smoothly until you add Serial.println() of the position on every pass through loop(), and the motor then stutters. Why does this happen, and how do you fix it?
Show answer
Serial.println() takes long enough that run() is called too late for some steps, so step intervals become uneven. Print only every 100 to 250 ms by checking millis(), or print only when the motion ends.