#include <LiquidCrystal.h>
// Set up the LCD: (RS, E, D4, D5, D6, D7)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int buttonPin = 7; // Button input pin
const int backlightPin = 9; // LCD backlight control pin (PWM)
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
pinMode(backlightPin, OUTPUT); // Backlight pin as output
analogWrite(backlightPin, 255); // Full brightness
lcd.begin(16, 2); // Initialize LCD size
lcd.print("Reaction Timer!"); // Welcome message
delay(2000); // Show it for 2 seconds
lcd.clear(); // Clear screen
}
void loop() {
// Wait until the button is released
while (digitalRead(buttonPin) == LOW) {
// Wait for release (button held down)
}
lcd.print("Get Ready...");
// Wait a random time before showing "NOW!"
unsigned long waitTime = random(3000, 6000); // 3-6 seconds
unsigned long startWait = millis();
while (millis() - startWait < waitTime) {
if (digitalRead(buttonPin) == LOW) {
// Player pressed too early!
lcd.clear();
lcd.print("Too early!");
delay(2000);
lcd.clear();
return; // Restart the loop
}
}
lcd.clear();
lcd.print("NOW!");
// Record the time when signal was shown
unsigned long startTime = millis();
// Wait for the button to be pressed
while (digitalRead(buttonPin) == HIGH) {
// Waiting for button press
}
// Measure reaction time
unsigned long reactionTime = millis() - startTime;
// Show result
lcd.clear();
lcd.print("Reaction time:");
lcd.setCursor(0, 1);
lcd.print(reactionTime);
lcd.print(" ms");
// Wait until button is released before restarting
while (digitalRead(buttonPin) == LOW) {
// Waiting for button release
}
delay(1000);
lcd.clear(); // Clear before next round
}