const int buttonPin = 2;
const int ledPin = 13;
bool waitingForReaction = false;
unsigned long startTime;
unsigned long reactionTime;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
randomSeed(analogRead(0)); // for more randomness
}
void loop() {
if (!waitingForReaction) {
// Wait for user to start the game
if (digitalRead(buttonPin) == LOW) {
delay(500); // debounce
int delayTime = random(1000, 5000);
delay(delayTime);
digitalWrite(ledPin, HIGH);
startTime = millis();
waitingForReaction = true;
}
} else {
// Wait for user to react
if (digitalRead(buttonPin) == LOW) {
delay(500); // debounce
reactionTime = millis() - startTime;
digitalWrite(ledPin, LOW);
Serial.print("Reaction time: ");
Serial.print(reactionTime);
Serial.println(" ms");
waitingForReaction = false;
}
}
}