#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the LCD address and dimensions
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define the GPIO pins for the buttons
const int buttonStartStopPin = 14;
const int buttonResetPin = 27;
// Variables for debounce logic
unsigned long lastDebounceTimeStartStop = 0;
unsigned long lastDebounceTimeReset = 0;
const unsigned long debounceDelay = 5; // Debounce time in milliseconds
// Variables to keep track of the button states
bool lastButtonStateStartStop = HIGH;
bool lastButtonStateReset = HIGH;
bool currentButtonStateStartStop = HIGH;
bool currentButtonStateReset = HIGH;
bool timerRunning = false;
// Variables for timekeeping
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
void setup() {
// Initialize the LCD
lcd.init();
lcd.setBacklight(HIGH);
lcd.clear();
// Set up the buttons
pinMode(buttonStartStopPin, INPUT_PULLUP);
pinMode(buttonResetPin, INPUT_PULLUP);
// Initial display
lcd.setCursor(0, 0);
lcd.print("Stopwatch");
lcd.setCursor(0, 1);
lcd.print("000:00:00.000");
}
void loop() {
// Read the state of the buttons
bool readingStartStop = digitalRead(buttonStartStopPin);
bool readingReset = digitalRead(buttonResetPin);
// Debounce the start/stop button
if (readingStartStop != lastButtonStateStartStop) {
lastDebounceTimeStartStop = millis();
}
if ((millis() - lastDebounceTimeStartStop) > debounceDelay) {
if (readingStartStop != currentButtonStateStartStop) {
currentButtonStateStartStop = readingStartStop;
if (currentButtonStateStartStop == LOW) {
timerRunning = !timerRunning;
if (timerRunning) {
startTime = millis() - elapsedTime;
} else {
elapsedTime = millis() - startTime;
}
}
}
}
lastButtonStateStartStop = readingStartStop;
// Debounce the reset button
if (readingReset != lastButtonStateReset) {
lastDebounceTimeReset = millis();
}
if ((millis() - lastDebounceTimeReset) > debounceDelay) {
if (readingReset != currentButtonStateReset) {
currentButtonStateReset = readingReset;
if (currentButtonStateReset == LOW) {
elapsedTime = 0;
if (timerRunning) {
startTime = millis();
}
updateDisplay(0);
}
}
}
lastButtonStateReset = readingReset;
// Update the display if the timer is running
if (timerRunning) {
elapsedTime = millis() - startTime;
updateDisplay(elapsedTime);
}
}
// Function to update the LCD display with the current elapsed time
void updateDisplay(unsigned long time) {
unsigned long milliseconds = time % 1000;
unsigned long seconds = (time / 1000) % 60;
unsigned long minutes = (time / (1000 * 60)) % 60;
unsigned long hours = (time / (1000 * 60 * 60));
char buffer[17];
sprintf(buffer, "%03lu:%02lu:%02lu.%03lu", hours, minutes, seconds, milliseconds);
lcd.setCursor(0, 1);
lcd.print(buffer);
}