Built-in project · Arduino Uno R3

Filament runout sensor

An optical slot sensor on the filament path and an A4988 extruder: a debounced runout, 10 mm more printed from the filament still in the path, then a beeping pause that waits for you. The whole build, an Arduino Uno and 7 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 40 minutes to build and run. Runs in your browser. Free, and no account needed.

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

Filament runout sensor · Arduino Uno R3live0.000 s 0.00x
Press Run, click the card into the sensor, then pull it out
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

What you'll learn

  • Debouncing a sensor with a confirm time
  • Running a stepper through an A4988 with STEP and DIR
  • Writing a state machine with an enum
  • Timing with millis and micros instead of delay
  • Why a runout sensor sits upstream of the extruder
  • Difficulty: Intermediate
  • Time: About 40 minutes
  • Board: Arduino Uno R3
  • Parts: 14

How it works

A slot sensor on pin 4 reads HIGH while filament blocks its beam. When filament appears, the sketch starts printing: it pulses the A4988 STEP pin on pin 2 to turn the extruder at 2 mm of filament a second. The amber lamp on pin 13 follows the sensor.

If the sensor reads empty for 300 ms, the sketch believes it. Short wobbles are ignored. It then keeps extruding another 10 mm, because there is still filament between the sensor and the extruder.

After that it pauses and turns the driver off with the EN pin. The piezo on pin 11 beeps every two seconds. Printing restarts only when filament is back in the sensor and you press the resume button on pin 12.

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
LED, yellow pin AArduino Uno R3 pin 13
Pushbutton pin 1aArduino Uno R3 pin 12
Pushbutton pin 1bArduino Uno R3 pin 12
Piezo speaker pin 1Arduino Uno R3 pin 11
Stepper driver, A4988 pin ENArduino Uno R3 pin 8
Stepper driver, A4988 pin DIRArduino Uno R3 pin 5
Photo interrupter, slot pin SIGArduino Uno R3 pin 4
Stepper driver, A4988 pin STEPArduino Uno R3 pin 2
Photo interrupter, slot pin VCCArduino Uno R3 pin 5V
Photo interrupter, slot pin GNDArduino Uno R3 pin GND
Pushbutton pin 2aArduino Uno R3 pin GND
Pushbutton pin 2bArduino Uno R3 pin GND
Resistor, 220 Ω pin 2Arduino Uno R3 pin GND
Piezo speaker pin 2Arduino Uno R3 pin GND
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
Resistor, 220 Ω pin 1LED, yellow pin C

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
// Filament runout sensor: an optical slot sensor, an extruder stepper and a pause that waits for you.
//
//   pin 4   the sensor's signal (a slot sensor: filament in the slot blocks the beam)
//   pin 2   extruder STEP    pin 5   extruder DIR    pin 8   EN (LOW enables the A4988)
//   pin 12  resume button (to GND)
//   pin 13  amber "filament" lamp      pin 11  the beeper, a piezo
//
// A runout sensor sits on the filament path before the extruder. The filament
// passes through it; when the spool runs dry the tail end goes by and the
// sensor changes state. Three details turn that into a good feature:
//
//   1. Debounce. The reading must stay "empty" for RUNOUT_CONFIRM_MS before the
//      sketch believes it, so a wobble of the filament is not a runout.
//   2. Runout distance. The sensor is upstream of the extruder, so there is still
//      filament between them. The sketch keeps printing for RUNOUT_DISTANCE_MM
//      before pausing, the idea behind Marlin's FILAMENT_RUNOUT_DISTANCE_MM.
//   3. A real pause. The extruder stops, the beeper calls, and nothing resumes
//      until filament is back in the sensor AND you press resume. Marlin runs
//      M600, a filament change, at this point.
//
// This is a sketch, not Marlin. Mokxi has no spool: click the card into the
// sensor's slot to load filament and out again to run out. The extruder turns at
// 2 mm of filament a second, 93 steps a millimeter at 1/16 step.

const int SENSOR_PIN = 4;
const int STEP_PIN = 2;
const int DIR_PIN = 5;
const int ENABLE_PIN = 8;
const int RESUME_PIN = 12;
const int LAMP_PIN = 13;
const int BEEPER_PIN = 11;

const long STEPS_PER_MM = 93;
const long FEED_MM_S = 2;
const unsigned long RUNOUT_CONFIRM_MS = 300;
const long RUNOUT_DISTANCE_MM = 10;

enum State { WAITING, PRINTING, RUNNING_OUT, PAUSED };
State state = WAITING;
long extrudedSteps = 0;      // since printing started
long runoutAtSteps = 0;      // where the runout was confirmed
unsigned long emptySince = 0;
unsigned long lastStep = 0, lastBeep = 0, lastReport = 0;

// The slot sensor's output is HIGH while the beam is blocked: filament present.
bool filamentPresent() { return digitalRead(SENSOR_PIN) == HIGH; }

void say(const char *text) { Serial.println(text); }

void setup() {
  Serial.begin(115200);
  pinMode(SENSOR_PIN, INPUT);
  pinMode(STEP_PIN, OUTPUT);
  pinMode(DIR_PIN, OUTPUT);
  pinMode(ENABLE_PIN, OUTPUT);
  pinMode(RESUME_PIN, INPUT_PULLUP);
  pinMode(LAMP_PIN, OUTPUT);
  digitalWrite(DIR_PIN, HIGH);
  digitalWrite(ENABLE_PIN, HIGH);
  say("Runout demo: load filament (put the card in the slot) to start printing");
}

void loop() {
  unsigned long now = millis();
  bool present = filamentPresent();
  digitalWrite(LAMP_PIN, present ? HIGH : LOW);

  // Debounce: "empty" has to last before it counts.
  if (present) emptySince = 0;
  else if (emptySince == 0) emptySince = now;
  bool confirmedEmpty = !present && emptySince != 0 && now - emptySince >= RUNOUT_CONFIRM_MS;

  switch (state) {
    case WAITING:
      if (present) {
        state = PRINTING;
        digitalWrite(ENABLE_PIN, LOW);
        say("filament loaded: printing");
      }
      break;
    case PRINTING:
      if (confirmedEmpty) {
        state = RUNNING_OUT;
        runoutAtSteps = extrudedSteps;
        say("runout detected: using the filament still in the path");
      }
      break;
    case RUNNING_OUT:
      if (extrudedSteps - runoutAtSteps >= RUNOUT_DISTANCE_MM * STEPS_PER_MM) {
        state = PAUSED;
        digitalWrite(ENABLE_PIN, HIGH);
        say("PAUSED: load new filament, then press resume");
      }
      break;
    case PAUSED:
      if (now - lastBeep >= 2000) {
        lastBeep = now;
        tone(BEEPER_PIN, 2000, 150);
      }
      if (digitalRead(RESUME_PIN) == LOW) {
        if (present) {
          state = PRINTING;
          digitalWrite(ENABLE_PIN, LOW);
          say("resumed: printing");
        } else if (now - lastReport >= 1000) {
          lastReport = now;
          say("still no filament in the sensor: load it first");
        }
      }
      break;
  }

  // The extruder: one step every 1 / (2 mm/s x 93 steps/mm), about 5.4 ms, while printing.
  bool extruding = state == PRINTING || state == RUNNING_OUT;
  if (extruding && micros() - lastStep >= 1000000UL / (FEED_MM_S * STEPS_PER_MM)) {
    lastStep = micros();
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(4);
    digitalWrite(STEP_PIN, LOW);
    extrudedSteps++;
    if (extrudedSteps % (10 * STEPS_PER_MM) == 0) {
      Serial.print("extruded ");
      Serial.print(extrudedSteps / STEPS_PER_MM);
      Serial.println(" mm");
    }
  }
}

Code walkthrough

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

loop sketch.ino

Reads the sensor, drives the lamp, and tracks how long it has read empty. A switch on state moves through WAITING, PRINTING, RUNNING_OUT and PAUSED. At the end it steps the extruder on a timer while printing or running out.

void loop() {
  unsigned long now = millis();
  bool present = filamentPresent();
  digitalWrite(LAMP_PIN, present ? HIGH : LOW);

  // Debounce: "empty" has to last before it counts.
  if (present) emptySince = 0;
  else if (emptySince == 0) emptySince = now;
  bool confirmedEmpty = !present && emptySince != 0 && now - emptySince >= RUNOUT_CONFIRM_MS;

  switch (state) {
    case WAITING:
      if (present) {
        state = PRINTING;
        digitalWrite(ENABLE_PIN, LOW);
        say("filament loaded: printing");
      }
      break;
    case PRINTING:
      if (confirmedEmpty) {
        state = RUNNING_OUT;
        runoutAtSteps = extrudedSteps;
        say("runout detected: using the filament still in the path");
      }
      break;
    case RUNNING_OUT:
      if (extrudedSteps - runoutAtSteps >= RUNOUT_DISTANCE_MM * STEPS_PER_MM) {
        state = PAUSED;
  // ... 37 more lines in the editor

filamentPresent sketch.ino

Returns true when pin 4 reads HIGH. The slot sensor outputs HIGH while the beam is blocked, so HIGH means filament is in the slot. Putting this in a function keeps that detail in one place.

// The slot sensor's output is HIGH while the beam is blocked: filament present.
bool filamentPresent() { return digitalRead(SENSOR_PIN) == HIGH; }

setup sketch.ino

Sets every pin's mode, with the resume button on INPUT_PULLUP. It sets DIR HIGH and EN HIGH, which leaves the A4988 disabled. Then it prints a message telling you to load filament.

void setup() {
  Serial.begin(115200);
  pinMode(SENSOR_PIN, INPUT);
  pinMode(STEP_PIN, OUTPUT);
  pinMode(DIR_PIN, OUTPUT);
  pinMode(ENABLE_PIN, OUTPUT);
  pinMode(RESUME_PIN, INPUT_PULLUP);
  pinMode(LAMP_PIN, OUTPUT);
  digitalWrite(DIR_PIN, HIGH);
  digitalWrite(ENABLE_PIN, HIGH);
  say("Runout demo: load filament (put the card in the slot) to start printing");
}

Troubleshooting

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

  • The motor never turns, even with filament loaded. This project
    The A4988 is enabled by pulling EN (pin 8) LOW. Check that pin and that the 12 V supply reaches VMOT.
  • Resume does nothing. This project
    Resume works only if the sensor sees filament. Load it first, then press the button on pin 12.
  • The pause comes later than you expected. This project
    That is RUNOUT_DISTANCE_MM, 10 mm at 2 mm a second. Lower it to pause sooner.
  • 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 output never changes, or is always the same. The LED side needs a series resistor, and the phototransistor side needs a pull-up. Photo interrupter
    Put about 220 ohms in series with the LED from 5 V. Pull the output up with about 10k, or use INPUT_PULLUP. Output goes low when the beam is clear and high when blocked, or the reverse on some modules.

Change it and keep it

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