#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns, 2 rows
const int buttonPin = 2;
const int MAX_TIMES = 10; // Maximum number of times to store
unsigned long times[MAX_TIMES]; // Array to store elapsed times
int numTimes = 0; // Number of times stored
int buttonState = 0;
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.clear();
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
printTimes();
} else if (buttonState == HIGH) {
if (numTimes < MAX_TIMES) {
if (startTime == 0) {
startTime = millis();
Serial.println("Stopwatch started.");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Stopwatch started.");
} else {
unsigned long currentTime = millis();
elapsedTime = currentTime - startTime;
times[numTimes++] = elapsedTime;
Serial.print("Time ");
Serial.print(numTimes);
Serial.print(": ");
Serial.print(elapsedTime / 1000.0); // Convert milliseconds to seconds
Serial.println(" seconds");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time ");
lcd.print(numTimes);
lcd.print(": ");
lcd.print(elapsedTime / 1000.0); // Convert milliseconds to seconds
lcd.print(" sec");
startTime = 0;
}
} else {
Serial.println("Maximum number of times reached.");
}
}
}
void printTimes() {
Serial.println("All times:");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("All times:");
for (int i = 0; i < numTimes; i++) {
Serial.print("Time ");
Serial.print(i + 1);
Serial.print(": ");
Serial.print(times[i] / 1000.0); // Convert milliseconds to seconds
Serial.println(" seconds");
lcd.setCursor(0, i + 1);
lcd.print("Time ");
lcd.print(i + 1);
lcd.print(": ");
lcd.print(times[i] / 1000.0); // Convert milliseconds to seconds
lcd.print(" sec");
}
}