#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
unsigned long prevMillis = 0;
unsigned long interval = 1000;
int startButton = 2;
int pauseButton = 3;
int stopButton = 4;
int resetButton = 5;
bool isRunning = false;
bool stopButtonPressed = false; // Menandai apakah tombol "Stop" pernah ditekan
int hours = 0;
int minutes = 0;
int seconds = 0;
void setup() {
lcd.init();
lcd.backlight();
pinMode(startButton, INPUT_PULLUP);
pinMode(pauseButton, INPUT_PULLUP);
pinMode(stopButton, INPUT_PULLUP);
pinMode(resetButton, INPUT_PULLUP);
lcd.setCursor(0, 0);
lcd.print("Stopwatch: ");
}
void loop() {
unsigned long currMillis = millis();
bool startPressed = digitalRead(startButton) == LOW;
bool pausePressed = digitalRead(pauseButton) == LOW;
bool stopPressed = digitalRead(stopButton) == LOW;
bool resetPressed = digitalRead(resetButton) == LOW;
if (startPressed) {
if (stopButtonPressed) { // Jika tombol "Stop" telah ditekan sebelumnya
stopButtonPressed = false; // Reset status tombol "Stop"
isRunning = false; // Berhenti dari running
// Reset timer to 00:00:00
lcd.setCursor(0, 1);
lcd.print("00:00:00");
// Reset internal timer variables
prevMillis = 0;
hours = 0;
minutes = 0;
seconds = 0;
} else {
isRunning = !isRunning; // Toggle status running
}
delay(10);
}
if (pausePressed) {
isRunning = false;
delay(10);
}
if (isRunning && currMillis - prevMillis >= interval) {
prevMillis = currMillis;
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
if (hours == 24) {
hours = 0;
}
}
}
lcd.setCursor(0, 1);
lcd.print((hours < 10 ? "0" : "") + String(hours));
lcd.print(":");
lcd.print((minutes < 10 ? "0" : "") + String(minutes));
lcd.print(":");
lcd.print((seconds < 10 ? "0" : "") + String(seconds));
} else if (!isRunning) {
prevMillis = currMillis;
}
if (resetPressed) {
isRunning = false;
stopButtonPressed = false; // Reset status tombol "Stop"
delay(10);
// Reset timer to 00:00:00
lcd.setCursor(0, 1);
lcd.print("00:00:00");
// Reset internal timer variables
prevMillis = 0;
hours = 0;
minutes = 0;
seconds = 0;
}
if (stopPressed) {
stopButtonPressed = true; // Menandai bahwa tombol "Stop" telah ditekan
isRunning = false;
delay(10);
}
}