// Import required library
#include <LiquidCrystal_I2C.h>
// Setup the LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
int startTime = 0;
#define START_BUTTON_PIN 26
#define STOP_BUTTON_PIN 27
// Declare the falg variables for buttons
bool startButtonPressed = false;
bool stopButtonPressed = false;
void setup() {
Serial.begin(9600);
// Intialize the LCD and trun on the backlight
lcd.init();
lcd.backlight();
// Print the Welcome message
lcd.setCursor(3, 0);
lcd.print("Welcome to ");
lcd.setCursor(3, 1);
lcd.print("Stopwatch");
pinMode(START_BUTTON_PIN, INPUT_PULLUP);
pinMode(STOP_BUTTON_PIN, INPUT_PULLUP);
// Set the dealy of 1 seconds
delay(1000);
// Recording the starting time
startTime = millis();
}
void loop() {
// Get the button states for start and stop
int startButtonState = digitalRead(START_BUTTON_PIN);
int stopButtonState = digitalRead(STOP_BUTTON_PIN);
if(startButtonState == LOW && !startButtonPressed){
startButtonPressed = true;
stopButtonPressed = false;
startTime = millis();
}
if(stopButtonState == LOW && !stopButtonPressed) {
stopButtonPressed = true;
startButtonPressed = false;
}
if(startButtonPressed){
// Set the LCD cursor to initial position
lcd.setCursor(0,0);
// Getting the elapsed time
int currentTime = millis() - startTime;
// Converting milliseconds to seconds, minutes, and hours
int seconds = currentTime / 1000;
int minutes = seconds / 60;
int hours = minutes / 60;
// Display the simulated time in the LCD
lcd.print("Time: ");
lcd.print(hours);
lcd.print(":");
lcd.print(minutes % 60);
lcd.print(":");
lcd.print(seconds % 60);
lcd.print(":");
lcd.print(currentTime %1000);
}
}