#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define TRIG_PIN 9
#define ECHO_PIN 10
#define LED_PIN 12
#define TIME_LIMIT 5000
LiquidCrystal_I2C lcd(0x27, 16, 2);
int targetDistance;
unsigned long startTime;
bool gameActive = false;
int score = 0;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
lcd.init();
lcd.backlight();
randomSeed(analogRead(0));
newTarget();
}
void loop() {
if (score <= -5) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("You lost!");
lcd.setCursor(0, 1);
lcd.print("Shutting down...");
delay(3000);
shutdownGame();
while (true);
} else if (score >= 5) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("You won!");
lcd.setCursor(0, 1);
lcd.print("BYE! BYE!");
delay(3000);
shutdownGame();
}
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2;
displayStatus();
if (gameActive && (millis() - startTime > TIME_LIMIT)) {
gameActive = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time's up!");
lcd.setCursor(0, 1);
lcd.print("Score -1 point");
score -= 1;
delay(2000);
newTarget();
}
if (gameActive && distance >= targetDistance - 1 && distance <= targetDistance + 1) {
unsigned long reactionTime = millis() - startTime;
digitalWrite(LED_PIN, HIGH);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Great Job!");
lcd.setCursor(0, 1);
lcd.print("Time:");
lcd.print(reactionTime);
lcd.print("ms");
score += 2;
delay(3000);
digitalWrite(LED_PIN, LOW);
newTarget();
}
delay(100);
}
void newTarget() {
targetDistance = random(10, 51);
startTime = millis();
gameActive = true;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("New Target: ");
lcd.print(targetDistance);
lcd.print("cm");
}
void displayStatus() {
lcd.setCursor(0, 1);
lcd.print("Time: ");
lcd.print((TIME_LIMIT - (millis() - startTime)) / 1000);
lcd.print("s Score: ");
lcd.print(score);
}
void resetGame() {
score = 0;
newTarget();
}
void shutdownGame() {
gameActive = false;
digitalWrite(LED_PIN, LOW);
lcd.noBacklight();
lcd.clear();
}