#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
const int buttonPin = 2; // Pin for controlling the timer
const int ledPin = 4; // Pin for controlling the LED
volatile bool buttonPressed = false;
volatile unsigned long lastDebounceTime = 0;
volatile unsigned long debounceDelay = 50;
volatile int buttonState = HIGH;
volatile int lastButtonState = HIGH;
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
unsigned long pausedTime = 0;
bool running = false;
int buttonPressCount = 0; // Keeps track of the number of button presses
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("00:00:00");
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT); // Initialize LED pin as output
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonISR, CHANGE);
}
void loop() {
if (buttonPressed) {
debounceButton();
buttonPressed = false;
if (buttonState == LOW) {
buttonPressCount++;
if (buttonPressCount == 1) {
startTimer();
digitalWrite(ledPin, HIGH); // Turn on LED when timer starts
} else if (buttonPressCount == 2) {
stopTimer();
digitalWrite(ledPin, LOW); // Turn off LED when timer stops
} else if (buttonPressCount >= 3) {
resetTimer();
digitalWrite(ledPin, LOW); // Turn off LED when timer resets
}
}
}
if (running) {
updateTimer();
}
}
void buttonISR() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
buttonPressed = true;
delay(50); // Add a small delay to prevent immediate re-triggering
}
}
void debounceButton() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if (millis() - lastDebounceTime > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
}
}
lastButtonState = reading;
}
void startTimer() {
if (!running) {
if (elapsedTime == 0) {
startTime = millis();
} else {
startTime = millis() - pausedTime;
}
running = true;
}
}
void stopTimer() {
if (running) {
elapsedTime = millis() - startTime;
pausedTime = elapsedTime;
running = false;
}
}
void resetTimer() {
elapsedTime = 0;
pausedTime = 0;
lcd.setCursor(0, 0);
lcd.print("00:00:00");
buttonPressCount = 0; // Reset button press count
}
void updateTimer() {
unsigned long currentTime = millis();
elapsedTime = currentTime - startTime;
unsigned long minutes = (elapsedTime / 60000) % 60;
unsigned long seconds = (elapsedTime / 1000) % 60;
unsigned long milliseconds = (elapsedTime % 1000) / 10; // Extracting two digits for milliseconds
lcd.setCursor(0, 0);
if (minutes < 10) {
lcd.print("0");
}
lcd.print(String(minutes, DEC));
lcd.print(":");
if (seconds < 10) {
lcd.print("0");
}
lcd.print(String(seconds, DEC));
lcd.print(":");
if (milliseconds < 10) {
lcd.print("0");
}
lcd.print(String(milliseconds, DEC)); // Display two digits for milliseconds
}