Try Embedded

Stepper motor with an A4988

Drive a NEMA stepper motor with STEP and DIR through an A4988 driver, accelerating with AccelStepper.

Motors · Intermediate

In a real product: 3D printer (Consumer electronics): Each axis is a stepper on a driver like this, accelerated smoothly so no steps are lost.

A stepper motor turns in exact steps (200 a turn, 1.8° each, for this one), so you can position it precisely without a sensor: 3D printers and CNC machines use them. It needs a driver to switch its coils. The A4988 does that from just two signals: STEP and DIR.

What you'll learn

  • How a STEP/DIR driver works: one pulse, one step
  • Acceleration: why steppers need to speed up gradually
  • Using AccelStepper in DRIVER mode

How it works

Each rising edge on STEP (pin 3) moves the motor one step; DIR (pin 4) sets the direction. The driver works out which coil to energise and in which direction, and switches the motor current, which can be far more than a pin could give. VDD and GND power its logic. VMOT takes the motor supply, 8–35 V: here a 12 V supply, its V− joined to GND. On real hardware add a 100 µF capacitor across VMOT and GND, and set the current limit with the trimmer.

MS1–MS3 (left unconnected here) choose microstepping. Unconnected, they read low: full steps.

AccelStepper makes the pulses. moveTo(200) sets a target one turn away, and run(), called as often as possible, sends the next pulse when it is due, speeding up and slowing down at the acceleration you set. When it arrives, the loop sends it back the other way.

Try this

  • Wire MS1 to 5V for half steps: the same motion now takes 400 steps a turn.
  • Move to an angle typed into the Serial Monitor.
  • Add a limit switch and "home" the motor at start-up, as 3D printers do.

sketch.ino

// A stepper motor on an A4988 driver (STEP pin 3, DIR pin 4), moved back and forth one turn with acceleration.
#include <AccelStepper.h>

AccelStepper stepper(AccelStepper::DRIVER, 3, 4);  // STEP, DIR

void setup() {
  stepper.setMaxSpeed(400);      // steps per second
  stepper.setAcceleration(300);  // steps per second per second
  stepper.moveTo(200);           // one turn of a 200-step motor
}

void loop() {
  if (stepper.distanceToGo() == 0) stepper.moveTo(-stepper.currentPosition());
  stepper.run();
}

Lessons behind it