const int ledPin = 2; // LED connected to digital pin 2
const int buttonPin = 3; // Push button connected to digital pin 3
unsigned long startTime; // Variable to store the start time of LED on
unsigned long endTime; // Variable to store the end time of LED on
unsigned long pressTime; // Variable to store the time button is pressed
unsigned long ledDuration; // Variable to store random LED on duration
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600); // Initialize serial communication
// Seed random number generator
randomSeed(analogRead(0));
}
void loop() {
// Generate random LED on duration
ledDuration = random(1000, 5001);
// Turn on LED
digitalWrite(ledPin, HIGH);
startTime = millis(); // Record start time
// Wait for LED on duration
delay(ledDuration);
// Turn off LED
digitalWrite(ledPin, LOW);
endTime = millis(); // Record end time
// Wait for button press
while (digitalRead(buttonPin) == HIGH) {
// Wait for button press
}
pressTime = millis() - endTime; // Calculate button press time
// Calculate score based on how close press time is to LED duration
int score = map(abs(pressTime - ledDuration), 0, 4000, 100, 0); // Map difference to score range
// Display score on serial monitor
Serial.print("Your score: ");
Serial.println(score);
// Wait before starting the next round
delay(1000);