#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"

const byte PIN_CLK = 2;
const byte PIN_DIO = 3;
const byte PIN_ON = 4; // define the on button pin
const byte PIN_OFF = 5; // define the off button pin
const byte PIN_BUZZER = 6; // define the buzzer pin
const byte PIN_LED_RED = 7; // define the red LED pin
const byte PIN_LED_GREEN = 8; // define the green LED pin
SevenSegmentExtended display(PIN_CLK, PIN_DIO);

unsigned long previousMillis = 0;
const unsigned long interval = 1000; // interval in milliseconds (1 second)
int remainingTime = 10; // 10 seconds
boolean timerActive = false; // flag to indicate if the timer is active or not
boolean buzzerOn = false; // flag to indicate if the buzzer is on or not

void setup() {
Serial.begin(9600);
display.begin();
display.setBacklight(100);
pinMode(PIN_ON, INPUT_PULLUP); // set the on button as input with pull-up resistor
pinMode(PIN_OFF, INPUT_PULLUP); // set the off button as input with pull-up resistor
pinMode(PIN_BUZZER, OUTPUT); // set the buzzer as output
pinMode(PIN_LED_RED, OUTPUT); // set the red LED as output
digitalWrite(PIN_LED_RED, HIGH);
pinMode(PIN_LED_GREEN, OUTPUT); // set the green LED as output
}

void loop() {
int minutes = remainingTime / 60;
int seconds = remainingTime % 60;

if (digitalRead(PIN_ON) == LOW && !timerActive) { // check if on button is pressed and the timer is not active
timerActive = true; // set the timer as active
digitalWrite(PIN_LED_RED, LOW); // turn off the red LED
digitalWrite(PIN_LED_GREEN, HIGH); // turn on the green LED
buzzerOn = false; // set the buzzer as off
}

if (digitalRead(PIN_OFF) == LOW && timerActive) { // check if off button is pressed and the timer is active
timerActive = false; // set the timer as inactive
digitalWrite(PIN_LED_GREEN, LOW); // turn off the green LED
digitalWrite(PIN_LED_RED, HIGH); // turn on the red LED
buzzerOn = true; // set the buzzer as on
}

if (timerActive) { // check if the timer is active
unsigned long currentMillis = millis(); // get current time
if (currentMillis - previousMillis >= interval) {
  previousMillis = currentMillis;
  remainingTime--;

  if (remainingTime < 0 && digitalRead(PIN_OFF) == HIGH) {
    timerActive = false; // set the timer as inactive
    digitalWrite(PIN_LED_GREEN, LOW); // turn off the green LED
    digitalWrite(PIN_LED_RED, HIGH); // turn on the red LED
    buzzerOn = true; // set the buzzer as on
    remainingTime = 10;
  }else if(remainingTime < 0 && digitalRead(PIN_OFF) == LOW){
    buzzerOn = false; // set the buzzer as on
  }  
}
}

if (buzzerOn) { // check if the buzzer is on
digitalWrite(PIN_BUZZER, HIGH); // turn on the buzzer
} else {
digitalWrite(PIN_BUZZER, LOW); // turn off the buzzer
}

display.print(minutes * 100 + seconds);
}
4-Digit Display