#define LED_PINES {2,3,4,5}
#define NUM_OF_LED 4
#define BUTTON_PINES{A1,A2,A3,A4}
#define NUM_OF_BUTTON 4
int ledPins[] = LED_PINES ;
int buttonPins[] =BUTTON_PINES ;
int currentLED = -1; // Variable to store the current LED index
unsigned long startTime; // Variable to store the start time of LED display
bool ledDisplayed = false; // Flag to check if LED is displayed
bool buttonPressed = false; // Flag to check if button is pressed
void setup() {
Serial.begin(9600); // Initialize serial communication for displaying score
// randomSeed(analogRead(0)); // Seed random number generator
for (int i = 0; i < NUM_OF_LED; i++) {
pinMode(ledPins[i], OUTPUT); // Set LED pins as output
pinMode(buttonPins[i], INPUT_PULLUP); // Set button pins as input with internal pull-up resistors
}
}
void loop() {
if (!ledDisplayed) {
// If LED is not displayed, display a new LED and record start time
displayRandomLED();
startTime = millis();
ledDisplayed = true;
}
// Check if any button is pressed
for (int i = 0; i < NUM_OF_BUTTON; i++) {
if(i==displayRandomLED()){
if (digitalRead(buttonPins[i]) == LOW) {
buttonPressed = true;
displayScore(i);
break;
}}
}
// If a button is pressed, reset the LED display
if (buttonPressed) {
ledDisplayed = false;
buttonPressed = false;
}
}
// Function to randomly display an LED
int displayRandomLED() {
int randomLED = random()%NUM_OF_LED;
currentLED = randomLED;
for (int i = 0; i < NUM_OF_LED; i++) {
digitalWrite(ledPins[i], LOW);
}
digitalWrite(ledPins[randomLED], HIGH);
return currentLED;
}
// Function to calculate and display the score
void displayScore(int buttonIndex) {
unsigned long endTime = millis(); // Get the time when the button was pressed
unsigned long elapsedTime = endTime - startTime; // Calculate elapsed time
Serial.print("LED ");
Serial.print(currentLED + 1); // Add 1 to currentLED because it's zero-based index
Serial.print(" displayed for ");
Serial.print(elapsedTime);
Serial.println(" ms");
}