Built-in project · Arduino Uno R3

Stepper homing on an Arduino Uno

An A4988 and a NEMA 17 home against a microswitch endstop the way a 3D printer does, fast and then a slow second touch, then move to typed positions inside software limits. The whole build, an Arduino Uno and 3 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Intermediate About 35 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $41. On Mokxi they're free.

The circuit runs here once the page has loaded.

What you'll learn

  • Why a stepper needs a home position
  • Driving an A4988 with STEP, DIR and EN
  • Fast then slow endstop homing
  • Converting millimeters per second to a step delay
  • Software limits on an axis
  • Difficulty: Intermediate
  • Time: About 35 minutes
  • Board: Arduino Uno R3
  • Parts: 9

How it works

A stepper only knows how many steps it has taken, not where it is. So at power-up the sketch homes the axis. Type H in the Serial Monitor and the A4988 driver steps the NEMA 17 toward the endstop switch on pin 9 at 20 mm a second.

When the switch closes, it backs off 5 mm, then approaches again at 2 mm a second. The slow touch is the repeatable one. That switch position becomes X = 0. In Mokxi you click the switch lever yourself, since there is no carriage.

After homing, type a position such as 120 and press Enter. The axis moves there at 40 mm a second. At 80 steps per millimeter, positions outside 0 to 200 mm are refused.

Parts list

9 parts, plus the jumper wires. They retail for about $41; on Mokxi they're free.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Arduino Uno R3 pin GNDGround
Limit switch, lever microswitch pin NOArduino Uno R3 pin 9
Stepper driver, A4988 pin ENArduino Uno R3 pin 8
Stepper driver, A4988 pin DIRArduino Uno R3 pin 5
Stepper driver, A4988 pin STEPArduino Uno R3 pin 2
Stepper driver, A4988 pin MS1Supply
Stepper driver, A4988 pin MS2Supply
Stepper driver, A4988 pin MS3Supply
Stepper driver, A4988 pin SLPStepper driver, A4988 pin RST
Stepper driver, A4988 pin VMOT12 V
Stepper motor, NEMA 17 pin A1Stepper driver, A4988 pin 2B
Stepper motor, NEMA 17 pin A2Stepper driver, A4988 pin 2A
Stepper motor, NEMA 17 pin B1Stepper driver, A4988 pin 1A
Stepper motor, NEMA 17 pin B2Stepper driver, A4988 pin 1B
Stepper driver, A4988 pin VDDSupply
Stepper driver, A4988 pin GNDGround
Limit switch, lever microswitch pin COMGround

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · Arduino Uno R3
// Stepper homing: an A4988, a NEMA 17 and an endstop, the way a 3D printer finds zero.
//
//   pin 2   STEP      pin 5   DIR      pin 8   EN (LOW enables the driver)
//   pin 9   the X endstop, a microswitch to GND (internal pull-up, LOW when pressed)
//
// These are the pins a GRBL CNC shield uses for X. This is not GRBL or Marlin;
// it is a small sketch that does one thing they both do, and does it the same way.
//
// A stepper knows how many steps it has taken, not where it is. At power-up the
// carriage could be anywhere, so the machine homes: it creeps toward the endstop
// until the switch closes, backs off a few millimeters, and comes in again
// slowly, because the slow touch is the repeatable one (Marlin calls it the
// bump). That switch position becomes 0, and every move after is counted from it.
//
// Mokxi has no carriage, so YOU are the carriage: when the Serial Monitor says
// "seeking", click and hold the endstop's lever, let go when it backs off, and
// press it again for the slow touch. Then type a position, such as 120, and the
// axis moves there. Positions outside 0 to 200 mm are refused, like a printer's
// software endstops.
//
// The axis is a GT2 belt on a 20 tooth pulley: 40 mm per turn. At 1/16 step a
// 200 step motor takes 3200 microsteps a turn, so 80 steps per millimeter.

const int STEP_PIN = 2;
const int DIR_PIN = 5;
const int ENABLE_PIN = 8;
const int ENDSTOP_PIN = 9;

const long STEPS_PER_MM = 80;
const long MAX_TRAVEL_MM = 200;
const long SEEK_MM_S = 20;    // the fast approach
const long BUMP_MM_S = 2;     // the slow, repeatable touch
const long BACKOFF_MM = 5;
const long MOVE_MM_S = 40;

bool homed = false;
long position = 0;  // in steps, from the endstop

bool endstopPressed() { return digitalRead(ENDSTOP_PIN) == LOW; }

// The wait between steps that gives a speed in millimeters a second.
unsigned int stepWait(long mmPerSecond) { return 1000000L / (mmPerSecond * STEPS_PER_MM) - 4; }

// One step in the direction already set, then the wait that sets the speed.
void stepOnce(unsigned int waitUs) __attribute__((noinline));
void stepOnce(unsigned int waitUs) {
  digitalWrite(STEP_PIN, HIGH);
  delayMicroseconds(4);
  digitalWrite(STEP_PIN, LOW);
  delayMicroseconds(waitUs);
}

// Move toward the endstop until it closes, giving up after `limitMm`.
bool seek(long mmPerSecond, long limitMm) {
  digitalWrite(DIR_PIN, LOW);  // LOW is toward the endstop on this axis
  unsigned int wait = stepWait(mmPerSecond);
  long left = limitMm * STEPS_PER_MM;
  while (!endstopPressed()) {
    if (left-- <= 0) return false;
    stepOnce(wait);
  }
  return true;
}

void fail(const char *why) {
  homed = false;
  digitalWrite(ENABLE_PIN, HIGH);  // let the motor go, as a firmware does on an error
  Serial.print("homing failed: ");
  Serial.println(why);
}

void home() {
  Serial.println("homing X: seeking the endstop");
  digitalWrite(ENABLE_PIN, LOW);
  if (!seek(SEEK_MM_S, MAX_TRAVEL_MM + 20)) {
    fail("no endstop within the axis length, check the switch and its wire");
    return;
  }
  Serial.println("endstop hit: backing off");
  digitalWrite(DIR_PIN, HIGH);
  for (long s = 0; s < BACKOFF_MM * STEPS_PER_MM; s++) stepOnce(stepWait(SEEK_MM_S));
  delay(300);  // give the switch time to open
  if (endstopPressed()) {
    fail("the endstop is still pressed after backing off");
    return;
  }
  Serial.println("bump: approaching slowly");
  if (!seek(BUMP_MM_S, BACKOFF_MM * 2)) {
    fail("the endstop did not close on the slow approach");
    return;
  }
  position = 0;
  homed = true;
  Serial.println("homed: X = 0.0");
}

void moveTo(long mm) {
  if (!homed) {
    Serial.println("refused: home the axis first (type H)");
    return;
  }
  if (mm < 0 || mm > MAX_TRAVEL_MM) {
    Serial.println("refused: outside 0 to 200 mm (software endstop)");
    return;
  }
  long target = mm * STEPS_PER_MM;
  digitalWrite(DIR_PIN, target > position ? HIGH : LOW);
  Serial.print("moving to X = ");
  Serial.println(mm);
  unsigned int wait = stepWait(MOVE_MM_S);
  while (position != target) {
    stepOnce(wait);
    position += target > position ? 1 : -1;
  }
  Serial.print("X = ");
  Serial.println(position / STEPS_PER_MM);
}

void setup() {
  Serial.begin(115200);
  pinMode(STEP_PIN, OUTPUT);
  pinMode(DIR_PIN, OUTPUT);
  pinMode(ENABLE_PIN, OUTPUT);
  pinMode(ENDSTOP_PIN, INPUT_PULLUP);
  digitalWrite(ENABLE_PIN, HIGH);  // driver off until there is something to do
  Serial.println("X axis ready, position unknown: type H to home");
}

void loop() {
  static long typed = 0;
  static bool haveDigits = false;
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c == 'H' || c == 'h') {
      home();
    } else if (c >= '0' && c <= '9') {
      typed = typed * 10 + (c - '0');
      haveDigits = true;
    } else if (c == '\n' || c == '\r') {
      if (haveDigits) moveTo(typed);
      typed = 0;
      haveDigits = false;
    }
  }
}

Code walkthrough

The key functions of the sketch, and what each one does.

home sketch.ino

Enables the driver and seeks the endstop fast. It backs off BACKOFF_MM, checks the switch has released, then seeks again slowly. If any step fails, it calls fail. On success it sets position to 0 and homed to true.

void home() {
  Serial.println("homing X: seeking the endstop");
  digitalWrite(ENABLE_PIN, LOW);
  if (!seek(SEEK_MM_S, MAX_TRAVEL_MM + 20)) {
    fail("no endstop within the axis length, check the switch and its wire");
    return;
  }
  Serial.println("endstop hit: backing off");
  digitalWrite(DIR_PIN, HIGH);
  for (long s = 0; s < BACKOFF_MM * STEPS_PER_MM; s++) stepOnce(stepWait(SEEK_MM_S));
  delay(300);  // give the switch time to open
  if (endstopPressed()) {
    fail("the endstop is still pressed after backing off");
    return;
  }
  Serial.println("bump: approaching slowly");
  if (!seek(BUMP_MM_S, BACKOFF_MM * 2)) {
    fail("the endstop did not close on the slow approach");
    return;
  }
  position = 0;
  homed = true;
  Serial.println("homed: X = 0.0");
}

seek sketch.ino

Sets the direction toward the endstop and steps until the switch closes. It gives up after a limit in millimeters and returns false, so a broken switch or wire cannot make the motor run forever.

// Move toward the endstop until it closes, giving up after `limitMm`.
bool seek(long mmPerSecond, long limitMm) {
  digitalWrite(DIR_PIN, LOW);  // LOW is toward the endstop on this axis
  unsigned int wait = stepWait(mmPerSecond);
  long left = limitMm * STEPS_PER_MM;
  while (!endstopPressed()) {
    if (left-- <= 0) return false;
    stepOnce(wait);
  }
  return true;
}

stepWait sketch.ino

Turns a speed in millimeters a second into the wait between steps in microseconds, using STEPS_PER_MM. It subtracts the 4 microsecond step pulse so the speed stays right.

// The wait between steps that gives a speed in millimeters a second.
unsigned int stepWait(long mmPerSecond) { return 1000000L / (mmPerSecond * STEPS_PER_MM) - 4; }

moveTo sketch.ino

Refuses to move until homed or if the target is outside 0 to 200 mm. Otherwise it sets the direction and steps until position equals the target.

void moveTo(long mm) {
  if (!homed) {
    Serial.println("refused: home the axis first (type H)");
    return;
  }
  if (mm < 0 || mm > MAX_TRAVEL_MM) {
    Serial.println("refused: outside 0 to 200 mm (software endstop)");
    return;
  }
  long target = mm * STEPS_PER_MM;
  digitalWrite(DIR_PIN, target > position ? HIGH : LOW);
  Serial.print("moving to X = ");
  Serial.println(mm);
  unsigned int wait = stepWait(MOVE_MM_S);
  while (position != target) {
    stepOnce(wait);
    position += target > position ? 1 : -1;
  }
  Serial.print("X = ");
  Serial.println(position / STEPS_PER_MM);
}

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • It says homing failed: no endstop within the axis length. This project
    The switch never closed. Press and hold the lever while it says seeking, and check the switch is wired from pin 9 to ground.
  • It says refused: home the axis first. This project
    Type H and finish homing before you type a position.
  • The motor does not move at all. This project
    The A4988 needs EN (pin 8) LOW to run. Also check 12 V on VMOT and the STEP and DIR wires on pins 2 and 5.
  • The motor does nothing and the driver stays dead. Stepper driver
    Tie RST to SLP with a jumper, or drive both HIGH. Those two pins float on many boards. Also connect the logic VDD to 5 V and ground, and the motor VMOT to its own supply.
  • The driver or the chip dies when you power up. Stepper driver
    Put a 100 uF capacitor across VMOT and GND, close to the driver. Never connect or unplug the motor while powered, because the voltage spike can kill the chip.
  • The motor buzzes, shudders, or only vibrates instead of turning. Stepper motor
    Coils are swapped. Find the two coil pairs by measuring resistance with a meter (a few ohms between wires of one coil). Connect each pair to one driver coil output, A to A and B to B.
  • The motor stalls or loses steps when you speed up. Stepper motor
    A stepper cannot jump to a high speed. Start with slow step pulses and ramp up gradually. Check the driver current limit (Vref) and give the supply enough voltage, such as 12 V.
  • The input reads the wrong level, or floats when released. Limit switch
    Use COM and one contact. NC is closed at rest, NO closes when pressed. Add a pull-up or INPUT_PULLUP so the pin never floats.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.