I'm trying to recreate the game Simon in Arduino without using any push buttons, and I'm having issues with my readSequence() function. Although the showSequence() function works the way I want it to.
The showSequence() function will randomly light up some LEDs and create a string of letters that will match the order that the LEDs light up in.
After showSequence(), I'm trying to determine if the user correctly repeats the sequence. The user will enter letters to create a string called userSequence to compare to the gameSequence string.
When largestIndex is equal to zero, and I run the code, the LEDs light up more than once (only one LED should light up), it doesn't wait for the user to enter anything in the serial port and then goes through the if else statement and ends the void loop(). When I try printing showSequence(), it works the way I want it to. For some reason, readSequence() lights up more LEDs that I want to and ends the program early.
How can I fix my code so that the code will continue until the user fails to enter the sequence correctly?
#define A3 220 //Red tone
#define G4 392 //Yellow tone
#define C4 262 //Green tone
int sequence[100];
int largestIndex = 0;
int score = 0;
boolean gameOver = false;
void setup() {
// put your setup code here, to run once:
pinMode(16, OUTPUT); //Red LED
pinMode(14, OUTPUT); //Yellow LED
pinMode(13, OUTPUT); //Green LED
pinMode(12, OUTPUT); //Speaker
Serial.begin(115200);
}
String showSequence()
{
String gameSequence = "";
sequence[largestIndex] = random(0, 3);
largestIndex++;
for (int index = 0; index < largestIndex; index++)
{
if (sequence[index] == 0)
{
delay(300);
digitalWrite(16, HIGH);
delay(650);
tone(12, A3);
delay(50);
noTone(12);
digitalWrite(16, LOW);
gameSequence += "r";
}
if (sequence[index] == 1)
{
delay(300);
digitalWrite(14, HIGH);
delay(650);
tone(12, G4);
delay(50);
noTone(12);
digitalWrite(14, LOW);
gameSequence += "y";
}
if (sequence[index] == 2)
{
delay(300);
digitalWrite(13, HIGH);
delay(650);
tone(12, C4);
delay(50);
noTone(12);
digitalWrite(13, LOW);
gameSequence += "g";
}
}
return gameSequence;
}
void readSequence()
{
String userSequence = "";
Serial.println("Repeat the sequence. Enter one char at a time (r for red, y for yellow, and g for green)");
for (int index = 0; index < largestIndex; index++)
{
if (Serial.available() > 0) //check to see if something came in the serial port
{
char a = Serial.read(); //if so, read it
Serial.println(a);
switch (a)
{
case 'r' :
userSequence += "r";
break;
case 'y' :
userSequence += "y";
break;
case 'g' :
userSequence += "g";
break;
}
}
}
if (userSequence == showSequence())
{
Serial.println("Correct!");
score++;
}
else
{
String totalScore = String(score);
Serial.println("Incorrect!");
Serial.println("Your score is " + totalScore);
gameOver = true;
}
}
void loop() {
// put your main code here, to run repeatedly:
while (!gameOver)
{
showSequence();
readSequence();
}
}