Unwanted delay when restarting motion with AccelStepper.h

I want to oscillate a stepper between limits and and be able to return it to a center position with a selector switch. When the selector switch is flipped back it should start oscillating again as before.
The code below works, but after flipping the switch to home and back to run, there’s a 18 to 19 second delay before the motion starts again.
Does anybody know what might be causing this delay or a different way to do this?

int PulPin = 12;
int DirPin = 13;
int HomePin = 5;

#include <AccelStepper.h> //Import stepper library
AccelStepper stepper(AccelStepper::DRIVER, PulPin, DirPin);

void setup() {
  // put your setup code here, to run once:
  pinMode(HomePin, INPUT);

void loop() {
  // put your main code here, to run repeatedly:

  if (digitalRead(HomePin) == LOW)
    if (stepper.distanceToGo() == 0)

  if (digitalRead(HomePin) == HIGH)

  if (digitalRead(HomePin) == LOW && stepper.targetPosition() == 0)



How is your HomePin switch wired - do you have an external pull-up or pull-down resistor? If not I suspect the input is unstable.

If you don't have an external resistor then use pinMode(pin, INPUT_PULLUP) and wire your switch so that pressing it connects the pin to GND. The switch will then read LOW when pressed.

Separately, although the compiler does not need them, it is much easier to read IF statements with {} - like this

    if (digitalRead(HomePin) == LOW) {
        if (stepper.distanceToGo() == 0) {


That was it, thanks!

I had the 5v pin going to the HomePin with a switch breaking the line. I wired a 10k resistor between the switch and ground. Now it works.