/*  Example for MobaTools
    Moving a stepper back and forth
*/
#include <MobaTools.h>

// Adjust pins, steps and time as needed
const byte stepPin = 9;
const byte dirPin  = 8;
const int stepsPerRev = 800;   // Steps per Revolution ( example with 1/4 microsteps )
const long  targetPos = 6400;         // stepper moves between 0 and targetpos
long nextPos;

const int Buzzer =  10;

myBase.setBasetime( 5000 );

const int Led =  11;
MoToTimebase Buzzerzeit;
MoToTimebase    Ledzeit;
MoToTimebase    LedBlitz;

MoToStepper myStepper ( stepsPerRev, STEPDIR );
MoToTimer stepperPause;                         // Pause between stepper moves
bool stepperRunning;


void setup() {
  Buzzerzeit.setBasetime( -60000 );
  LedBlitz.setBasetime  (   -500 );

  myStepper.attach( stepPin, dirPin );
  myStepper.setSpeed( 700 );                  // 70 Rev/Min ( if stepsPerRev is set correctly )
  myStepper.setRampLen( 1200 );
  stepperRunning = true;

  //pinMode(Buzzer, OUTPUT);

  pinMode(Led, OUTPUT);
  digitalWrite(Led, HIGH);
}


void loop() {
  if ( stepperRunning ) {
    // Wait till stepper has reached target, then set pause time
    if ( !myStepper.moving() ) {
      // stepper has reached target, start pause
      stepperPause.setTime( 1000 );
      stepperRunning = false;
    }
  }
  else { 
    // stepper doesn't move, wait till stepperPause time expires
    if ( stepperPause.expired() ) {
      // stepperPause time expired. Start stepper in opposite direction
      if ( nextPos == 0 ) {
        nextPos = targetPos;
      }
      else {
        nextPos = 0;
      }
      myStepper.moveTo( nextPos );
      stepperRunning = true;
    }
  }

  if ( Buzzerzeit.tick() ) {   // Buzzerzeit abgelaufen
    tone(Buzzer, 440, 500);
    digitalWrite( Led, HIGH ); // LED ein
    LedBlitz.setTime( 500 );   // Blitztimer starten
  }

  // Led ist an und Led On-Zeit vorbei
  if ( digitalRead(Led) == HIGH && LedBlitz.tick() ) {
    digitalWrite( Led, LOW );  // Led aus
    LedBlitz.setTime( -500 );     // timer stoppen
  }

}