// https://wokwi.com/projects/410107479776879617
// Built from https://wokwi.com/projects/410063645175244801
// Code from https://github.com/waspinator/AccelStepper/blob/master/examples/Quickstop/Quickstop.pde
// Other example simulations https://forum.arduino.cc/t/wokwi-simulations-for-arduino-built-in-examples/1304754

// Quickstop.pde -- improved with arrays, reporting, and manual button
// -*- mode: C++ -*-
//
// Check stop handling.
// Calls stop() while the stepper is travelling at full speed, causing
// the stepper to stop as quickly as possible, within the constraints of the
// current acceleration.
//
// Copyright (C) 2012 Mike McCauley
// $Id:  $

#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5

const long targets[] = {500, -500, 302, -2, 500, -500};
const long stops[] = {300, 0, 300, 0, 500, -500};
const long accels[] = {100, 100, 10000, 10000, 10000, 10000};
const long NumTargets = sizeof(targets) / sizeof(targets[0]);
uint8_t targetID = 99; // invalid index to invoke a reset to 0

const byte stopButton = 12;
byte stopping = false; // Are we already stopping?

void setup()
{
  stepper.setMaxSpeed(150);
  stepper.setAcceleration(1000);
  Serial.begin(115200);
  pinMode(stopButton, INPUT_PULLUP);
}

void loop()
{
  stepper.run(); // move stepper as needed

  // Check for stop
  if (stepper.currentPosition() == stops[targetID]
      || digitalRead(stopButton) == LOW)
  { //hit stop
    stepper.stop(); // Stop as fast as possible: sets new target
    if (!stopping) {
      stopping = true;
      Serial.print("triggered: ");
      Serial.print(stepper.currentPosition());
    }
  }

  // retarget as needed
  if (stepper.distanceToGo() == 0) {
    stopping = false;
    Serial.print(" Stopped at ");
    Serial.println(stepper.currentPosition());
    ++targetID;
    if (targetID >= NumTargets) {
      targetID = 0;
    }
    Serial.print("Target[");
    Serial.print(targetID);
    Serial.print("] ");
    Serial.print(targets[targetID]);
    Serial.print(" stop@");
    Serial.print(stops[targetID]);
    Serial.print(" at ");
    Serial.print(accels[targetID]);
    Serial.print("step/s2 : ");
    delay(500);
    stepper.setAcceleration(accels[targetID]);
    stepper.moveTo(targets[targetID]);
  }

}