#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int buttonPin1 = 7;
const int buttonPin2 = 8;
// Highscore Array (Top 3); Große Startwerte = noch kein Score vorhanden
long highScores[3] = {1000000, 1000000, 1000000};
void updateHighScores(long t) {
if (t < highScores[0]) {
// Neuer 1. Platz
highScores[2] = highScores[1];
highScores[1] = highScores[0];
highScores[0] = t;
} else if (t < highScores[1]) {
// Neuer 2. Platz
highScores[2] = highScores[1];
highScores[1] = t;
} else if (t < highScores[2]) {
// Neuer 3. Platz
highScores[2] = t;
}
}
void displayHighScores() {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("1:");
if (highScores[0] < 1000000){
lcd.print(highScores[0] / 1000.0, 3);
lcd.print("s");}
else {
lcd.print("***");}
lcd.print(" 2:");
if (highScores[1] < 1000000){
lcd.print(highScores[1] / 1000.0, 3);
lcd.print("s");}
else{
lcd.print("***");}
// Zweite Zeile: Platz 3
lcd.setCursor(0,1);
lcd.print("3:");
if (highScores[2] < 1000000){
lcd.print(highScores[2] / 1000.0, 3);
lcd.print("s");}
else{
lcd.print("***");}
delay(3000);
lcd.clear();
}
void setup() {
pinMode(buttonPin1, INPUT_PULLUP);
pinMode(buttonPin2, INPUT_PULLUP);
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Reaction Timer!");
delay(2000);
lcd.clear();
}
void loop() {
// Warten bis beide Buttons losgelassen
while (digitalRead(buttonPin1) == LOW || digitalRead(buttonPin2) == LOW) {}
lcd.setCursor(0,0);
lcd.print("Get Ready...");
delay(random(3000,6000));
lcd.clear();
// Sicherheit: nochmal warten
while (digitalRead(buttonPin1) == LOW || digitalRead(buttonPin2) == LOW) {}
lcd.print("NOW!");
long startTime = millis();
long reactionTime = 100000;
int winner = 0;
// Warten auf ersten Tastendruck
while (true) {
if (digitalRead(buttonPin1) == LOW) {
winner = 1;
break;
}
if (digitalRead(buttonPin2) == LOW) {
winner = 2;
break;
}
}
reactionTime = millis() - startTime;
//Highscore aktualisieren
updateHighScores(reactionTime);
// Gewinner anzeigen
lcd.clear();
lcd.print("P");
lcd.print(winner);
lcd.print(" wins!");
lcd.setCursor(0,1);
lcd.print("Time:");
lcd.print(reactionTime / 1000.0, 3);
lcd.print(" s");
delay(2000);
// Highscores anzeigen
displayHighScores();
}