#include <LiquidCrystal_I2C.h>

//Buttons with internal Pullup, so if they get pressed we get LOW
const int start_button = 4;  //Start the stopwatch
unsigned long start, finished, elapsed;
boolean r = false;

int run;

long lastButtonPressTime = 0; // the last time the button was pressed
long debounceDelay = 50; // the debounce time; keep this as low as possible



LiquidCrystal_I2C lcd(0x27, 20, 4); // RS-Enable-D4-D5-D6-D7 in that digitalPin


void setup() {

  pinMode(start_button, INPUT); //In the schematic from right to left
  lcd.init();
  lcd.backlight();
  lcd.begin(16, 2);
  lcd.print("  RUN FOR START ");


}

void loop() {


  if (digitalRead(start_button) == LOW) //funcitons based off of button pulling input pin LOW
  {
    if (run == 0)
    {
      run = 255;
    }
    else
    {
      run = 0;
    }
  }

  if (run > 0)
  {
    lcd.home();
    CheckStartStop();
    chronometer();//code you only run if button was pressed, stops running when button pressed again, so forth...
  }
}


void chronometer() {  //This function print:   "New: Actual time"
  {
    if (r == true)
    {
      finished = millis(); // saves stop time to calculate the elapsed time
      // declare variables
      float h, m, s, ms;
      unsigned long over;

      // MATH time!!!
      elapsed = finished - start;

      h = int(elapsed / 3600000);
      over = elapsed % 3600000;
      m = int(over / 60000);
      over = over % 60000;
      s = int(over / 1000);
      ms = over % 1000;
      // display the results
      lcd.setCursor(0, 1);
      lcd.print(h, 0); // display variable 'h' - the 0 after it is the number of algorithms after a comma (ex: lcd.print(h, 2); would print 0,00
      lcd.print("h "); // and the letter 'h' after it
      lcd.print(m, 0);
      lcd.print("m ");
      lcd.print(s, 0);
      lcd.print("s ");
      if (h < 10)
      {
        lcd.print(ms, 0);
        lcd.print("ms ");
      }
    }
  }
}

  void CheckStartStop() {
    int x = digitalRead (start_button); // assign 'x' to the Arduino's AnalogueInputs (Shield's buttons)
    if (x == HIGH ) // if the button is SELECT
    {
      if ((millis() - lastButtonPressTime) > debounceDelay)
      {

        if (r == false)
        {
          lcd.clear();
          lcd.setCursor(3, 0); // needed
          lcd.print("START TIME");
          start = millis(); // saves start time to calculate the elapsed time
        }
        else if (r == true)
        {
          lcd.setCursor(2, 0); // needed
          lcd.print("FINISH TIME");
        }
        r = !r;
      }
      lastButtonPressTime = millis();
    }
  }