const int buttonPin = 2;
int minutes1 = 0;
int seconds1 = 2;
int milliseconds1 = 0;
int minutes2 = 0;
int seconds2 = 2;
int milliseconds2 = 0;
int currentState = 0;
unsigned long previousMillis = 0;
const long interval = 100;
unsigned long blinkMillis = 0;
const long blinkInterval = 1000;
bool buttonState = false;
bool lastButtonState = false;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState != lastButtonState) {
    delay(50);
    if (buttonState == HIGH && currentState == 0) {
      currentState = 1;
      Serial.println("Countdown 1 dimulai!");
    }
    lastButtonState = buttonState;
  }

  // Mesin keadaan
  switch (currentState) {
    case 1:
      runCountdown(minutes1, seconds1, milliseconds1, "Countdown 1 selesai!", 2);
      break;
    case 2:
      runCountdown(minutes2, seconds2, milliseconds2, "Countdown 2 selesai!", 0);
      break;
    default:
      break;
  }

  // Tugas lain yang tidak terkait dengan countdown dapat ditempatkan di sini
  // (Contoh: Membaca nilai analog)
  readAnalog();

  // Blink LED atau tugas lain
  blinkLED();
}

void runCountdown(int &minutes, int &seconds, int &milliseconds, const char *message, int nextState) {
  if (minutes > 0 || seconds > 0 || milliseconds > 0) {
    if (millis() - previousMillis >= interval) {
      Serial.print("Countdown: ");
      Serial.print(minutes);
      Serial.print("m ");
      Serial.print(seconds);
      Serial.print("s ");
      Serial.print(milliseconds);
      Serial.println("ms");
      previousMillis = millis();

      if (milliseconds > 0) {
        milliseconds--;
      } else {
        if (seconds > 0) {
          seconds--;
          milliseconds = 9;
        } else {
          minutes--;
          seconds = 59;
        }
      }
    }
  } else {
    Serial.println(message);
    currentState = nextState;
    resetCountdown();
  }
}

void resetCountdown() {
  minutes1 = 0;
  seconds1 = 10;
  milliseconds1 = 0;
  minutes2 = 0;
  seconds2 = 5;
  milliseconds2 = 0;
  Serial.println("Semua countdown direset.");
}

void readAnalog() {
  // Tugas membaca nilai analog tanpa menggunakan delay()
  static unsigned long analogReadMillis = 0;
  const long analogReadInterval = 1000;  // Interval membaca nilai analog dalam milidetik

  if (millis() - analogReadMillis >= analogReadInterval) {
    int analogValue = analogRead(A0);
    Serial.print("Nilai Analog: ");
    Serial.println(analogValue);

    analogReadMillis = millis();  // Perbarui waktu terakhir membaca nilai analog
  }
}

void blinkLED() {
  if (millis() - blinkMillis >= blinkInterval) {
    digitalWrite(13, !digitalRead(13));
    blinkMillis = millis();
  }
}