#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize the I2C LCD (address 0x27, 16 columns, 2 rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int startButton = 8;
const int stopButton = 9;
const int resetButton = 10;
bool running = false;
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
void setup() {
pinMode(startButton, INPUT);
pinMode(stopButton, INPUT);
pinMode(resetButton, INPUT);
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.print("Micro Timer");
delay(2000);
lcd.clear();
}
void loop() {
// Check if the Start button is pressed
if (digitalRead(startButton) == HIGH && !running) {
running = true;
startTime = micros(); // Record start time in microseconds
}
// Check if the Stop button is pressed
if (digitalRead(stopButton) == HIGH && running) {
running = false;
elapsedTime += micros() - startTime; // Add elapsed time to total
}
// Check if the Reset button is pressed
if (digitalRead(resetButton) == HIGH) {
running = false;
elapsedTime = 0;
}
// Display elapsed time
lcd.setCursor(0, 0);
lcd.print("Elapsed:");
if (running) {
unsigned long currentTime = micros();
displayTime(elapsedTime + currentTime - startTime);
} else {
displayTime(elapsedTime);
}
delay(100); // Small delay to avoid bouncing
}
// Function to display time in seconds and microseconds
void displayTime(unsigned long time) {
lcd.setCursor(0, 1);
lcd.print(time / 1000000); // Print seconds
lcd.print(".");
lcd.print((time / 1000) % 1000); // Print milliseconds
lcd.print("s "); // Clear extra chars
}