//https://forum.arduino.cc/t/how-to-run-for-loop-for-given-amount-of-time/1284182/

/*
  Sweep Servo1 from 40 to 90 over three minutes and stop.
  Sweep Servo2 from 90 to 140 over two minutes and stop.
*/

#include <Servo.h>
Servo servo1;
Servo servo2;

int pos1 = 40, pos2 = 90, pos3 = 140, servoDegree1 = pos1, servoDegree2 = pos2;

int sweepDegree1 = 90 - 40; // 50 degrees
unsigned long timer1;
unsigned long sweepTime1 = 3 * 60 * 1000UL; // 3 minutes
unsigned long interval1 = sweepTime1 / sweepDegree1; // 3600ms per degree

int sweepDegree2 = 140 - 90; // 50 degrees
unsigned long timer2;
unsigned long sweepTime2 = 2 * 60 * 1000UL; // 2 minutes
unsigned long interval2 = sweepTime2 / sweepDegree2; // time / degree = 2400ms per degree

void setup() {
  Serial.begin(115200);
  servo1.attach(3);
  servo2.attach(5);
  servo1.write(pos1); // start position
  servo2.write(pos2); // start position
  printout(pos1, pos2);
}

void loop() {
  // servo1 time window
  if (millis() >= 0 && millis() < 180000) { // 0 to 3 minutes
    // move servo1
    if (millis() - timer1 > interval1) { // check time between servo movement
      timer1 = millis(); // reset timer
      servoDegree1++; // increase servo degrees
      printout(servoDegree1, servoDegree2); // display current positions
      if (servoDegree1 > pos2) // verify servo is not beyond max position
        servoDegree1 = pos1; // limit servo to max position
      servo1.write(servoDegree1); // move servo
    }
  }

  // servo2 time window
  if (millis() > 180000 && millis() < 300000) // 3 to 5 minutes
    // move servo2
    if (millis() - timer2 > interval2) {
      timer2 = millis();
      servoDegree2++;
      printout(servoDegree1, servoDegree2);
      if (servoDegree2 > pos3)
        servoDegree2 = pos2;
      servo2.write(servoDegree2);
    }
}

// Serial Monitor display: time, servo1, servo2
void printout(int sd1, int sd2) {
  Serial.print("Time: ");

  unsigned long seconds = millis() / 1000UL;
  if (seconds < 100) Serial.print(" ");
  if (seconds < 10) Serial.print(" ");

  Serial.print(seconds);
  Serial.print("s Servo1 ");
  if (sd1 < 100) Serial.print(" ");
  if (sd1 < 10) Serial.print(" ");
  Serial.print(sd1);
  Serial.print("°");

  Serial.print(" Servo2 ");
  if (sd2 < 100) Serial.print(" ");
  if (sd2 < 10) Serial.print(" ");
  Serial.print(sd2);
  Serial.println("°");
}