#include <TaskScheduler.h>
// TaskScheduler instance
Scheduler ts;
// Variables
bool ledActive = false; // State of the LED
unsigned long ledOnTime = 0; // Time when LED is turned on
int reactionTime = 0; // Player's reaction time
// Task functions
void activateLED() {
// Task to activate the LED
ledActive = true;
digitalWrite(LED_BUILTIN, HIGH); // Turn on LED
ledOnTime = millis(); // Record activation time
Serial.println("LED is ON! Press the button...");
}
void monitorButtonPress() {
// Task to monitor button press
if (ledActive && digitalRead(2) == LOW) { // Button pressed
unsigned long buttonPressTime = millis();
reactionTime = buttonPressTime - ledOnTime; // Calculate reaction time
ledActive = false;
digitalWrite(LED_BUILTIN, LOW); // Turn off LED
Serial.print("Reaction Time: ");
Serial.print(reactionTime);
Serial.println(" ms");
tActivateLED.enableDelayed(random(2000, 5000)); // Restart after a random delay
tMonitorButton.disable(); // Stop button monitoring until next game
}
}
void resetGame() {
// Task to reset the game by enabling button monitoring
tMonitorButton.enable(); // Enable button monitoring
}
// Define tasks
Task tActivateLED(0, 1, &activateLED, &ts); // Task to activate LED
Task tMonitorButton(50, TASK_FOREVER, &monitorButtonPress, &ts, false); // Task to monitor button presses
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // LED pin
pinMode(2, INPUT_PULLUP); // Button pin with pull-up resistor
Serial.begin(9600);
randomSeed(analogRead(A0)); // Seed random generator with analog noise
// Start the game
Serial.println("Reaction-Time Game Starting!");
tActivateLED.enableDelayed(random(2000, 5000)); // Start LED task with random delay
}
void loop() {
// Execute scheduled tasks
ts.execute();
}