I figured out one of my problems with my code. I originally checked if the userSequence string is equal to the showSequence() function. The userSequence should have been checking if it was equal to gameSequence. That was why the LEDs lit up more than I wanted to.
I changed the if statement to:
if (userSequence.equals(gameSequence))
When I try running the code, it says that 'gameSequence' was not declared in this scope.
I set the Serial Monitor's Line Ending to "No line ending."
#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;
}
String 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++)
{
while (Serial.available() == 0) //check to see if something came in the serial port
{
}
char a = Serial.read(); //if so, read it
String led = String(a);
Serial.println(a);
userSequence += led;
}
if (userSequence.equals(gameSequence))
{
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();
}
}
