#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Pin definitions for 4 buttons
const int buttonPins[] = {2, 3, 4, 5}; // 4 push buttons on pins 2, 3, 4, 5
const int ledPin = 13; // LED pin
// LCD setup (Address, Columns, Rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Game variables
unsigned long startTime;
unsigned long reactionTime;
bool gameStarted = false;
int correctButton = -1; // Will hold the index of the correct button
bool buttonPressed = false;
void setup() {
// Initialize button pins as input with internal pull-up resistors
for (int i = 0; i < 4; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
// Initialize LED pin as output
pinMode(ledPin, OUTPUT);
// Initialize LCD
lcd.begin(16, 2);
lcd.backlight(); // Turn on the backlight of the LCD
lcd.clear();
lcd.print("Fastest Finger First!");
delay(2000); // Wait for 2 seconds before starting the game
// Seed random number generator
randomSeed(analogRead(0));
}
void loop() {
if (!gameStarted) {
// Random delay between 3 and 6 seconds before the game starts
int delayTime = random(3000, 6000);
lcd.clear();
lcd.print("Wait for GO!");
delay(delayTime); // Wait for the random time
// Choose a random button to be the "correct" one
correctButton = random(0, 4); // Random index between 0 and 3 (for 4 buttons)
// Start the game
lcd.clear();
lcd.print("GO!");
digitalWrite(ledPin, HIGH); // Turn on LED to indicate the game is on
startTime = millis(); // Record the start time
gameStarted = true;
} else {
// Check if any of the 4 buttons are pressed
for (int i = 0; i < 4; i++) {
if (digitalRead(buttonPins[i]) == LOW && !buttonPressed) { // LOW means button pressed
buttonPressed = true;
unsigned long currentTime = millis();
// Record the reaction time if the correct button was pressed
reactionTime = currentTime - startTime;
// Display the result on the LCD
lcd.clear();
lcd.print("Button ");
lcd.print(i + 1); // Display the button number (1-4)
lcd.setCursor(0, 1);
if (i == correctButton) {
lcd.print("Correct! ");
lcd.print(reactionTime);
lcd.print(" ms");
} else {
lcd.print("Wrong! ");
}
digitalWrite(ledPin, LOW); // Turn off LED after a button press
delay(3000); // Wait for 3 seconds before resetting
// Reset the game for the next round
gameStarted = false;
buttonPressed = false;
}
}
}
}