Hello,
I've written a program where When a 'start' button is pressed, 5 random LEDs should light up in blue. The user then has to select the correct buttons for each LED that is lit up blue. When a button for an LED thats blue is clicked, the LED should them green when clicked. I've run this code and whenever I press the start button, nothing is happening. Would appreciate some help with this. By the way I'm using arduino mega.
Heres my code:
// Pin definitions
const int buttonPin[] = {40, 41, 42, 43, 44, 45, 46, 47, 48, 49}; // Array of button pins
const int ledGreenPin[] = {12, 9, 6, 3, 23, 26, 29, 32, 35, 38}; // Array of green LED pins
const int ledBluePin[] = {13, 10, 7, 4, 22, 25, 28, 31, 34, 37}; // Array of blue LED pins
const int startButtonPin = 50; // Start button pin
// Variables
int blueLEDs[5]; // Array to store indices of LEDs that will light up blue
int selectedButton = -1; // Variable to store the index of the selected button
bool gameStarted = false; // Flag to indicate if the game has started
void setup() {
Serial.begin(9600);
// Initialize LED and button pins
for (int i = 0; i < 10; i++) {
pinMode(ledGreenPin[i], OUTPUT);
pinMode(ledBluePin[i], OUTPUT);
digitalWrite(ledGreenPin[i], LOW);
digitalWrite(ledBluePin[i], LOW);
pinMode(buttonPin[i], INPUT_PULLUP);
}
pinMode(startButtonPin, INPUT_PULLUP);
// Seed random number generator
randomSeed(analogRead(0));
}
void loop() {
if (!gameStarted && digitalRead(startButtonPin) == LOW) {
startGame();
}
if (gameStarted) {
// Check if any button is pressed
for (int i = 0; i < 10; i++) {
if (digitalRead(buttonPin[i]) == LOW) {
selectedButton = i;
break;
}
}
// If a button is pressed, check if it corresponds to a blue LED
if (selectedButton != -1) {
for (int i = 0; i < 5; i++) {
if (selectedButton == blueLEDs[i]) {
// Button corresponds to a blue LED
digitalWrite(ledGreenPin[selectedButton], LOW); // Turn off green LED
digitalWrite(ledBluePin[selectedButton], HIGH); // Turn blue LED on
delay(500); // Delay for visual feedback
digitalWrite(ledBluePin[selectedButton], LOW); // Turn off blue LED
selectedButton = -1; // Reset selected button
break;
}
}
}
}
}
void startGame() {
// Turn off all LEDs
for (int i = 0; i < 10; i++) {
digitalWrite(ledGreenPin[i], LOW);
digitalWrite(ledBluePin[i], LOW);
}
// Generate 5 random blue LEDs
for (int i = 0; i < 5; i++) {
blueLEDs[i] = random(10);
digitalWrite(ledBluePin[blueLEDs[i]], HIGH); // Turn blue LED on
}
gameStarted = true;
}