1

I am designing simple "Simon Says game" using Arduino. Simon says is a game in which a LED pattern is played and user has to mimic the pattern. There are 10 Rounds. First Round = 1 led, second round = 2 leds and so on. When the first round is played, one led blinks and player has to press the corresponding button. Then if it presses the right button, next round plays in which two LEDs glow and player has to press 2 buttons in sequence. I am having problem in detecting the button press in a loop for more than 1 round. Here is snippet of the code:

void loop() {
  for (int i = 1; i <= ROUNDS; i++)
  {
    digitalWriteGeneric(i);
    bool wait = 1;
    int expected = Sequence[i - 1];
    while (wait)
    {
      int value = digitalReadGeneric();
      if (expected == value)
      {
        Serial.print("Right");
        wait = 0;
        break;
      }
    }
  }
}
int digitalReadGeneric()
{
  for (int i = 0; i < NUM_LIGHTS; i++)
  {
    Readings[i] = digitalRead(buttonPin[i]);
    if (Readings[i] == 1)
    {
      return i;
    }
  }

}

Here, ROUNDS = 10 digitalwritegeneric is working fine, it plays the pattern for corresponding pattern. For round more than one how can i detect button press in sequence?. Kindly tell, what I am doing wrong.

1
  • This is a question more suited for stackoverflow actually.
    – Swedgin
    Jun 25 '21 at 7:51
1

Looking into your for-loop:

for (int i = 1; i <= ROUNDS; i++)
  {

    // Write sequence
    digitalWriteGeneric(i);

    // Read sequence
    bool wait = 1;
    int expected = Sequence[i - 1];
    while (wait)
      {
        int value = digitalReadGeneric();
        if (expected == value)
          {
            Serial.print("Right");
            wait = 0;
            break;

            // Setting vlag to false will exit the while loop
            // break will also exit the while loop
            // so only need to do 1 of the 2
            // but then you won't be able to read anymore, it exited the while-loop
          }
      }
  }

You only check the first button, and if this one is correct you go out of the while loop, ending the reading.

You can change the type of variable wait to an uint8_t (init to 0) and if the value is right, increment wait. The while-loop becomes: while (wait < i) {}. You can use break to stop reading when the player clicked a wrong button.

To see if the player did the sequence correctly: if (wait == i) {"GOOD";} else {"BAD";}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.