Problem with user input

Hi,

I'm trying to make a quiz where Arduino will output the question and the answers and then the user needs to input the number of the correct answer, for the first question the code waits for the user input the answer but for the 2nd question I can't input the answers.

int Answer1;
int Answer2;
int Answer3;
void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.println("1er Michanism authentication");
  delay(1000);
  Serial.println("Welcome agent, we would like to confirm your identity, please answer the following questions");
  delay(1000);
  Serial.println("question 1 : Quel est le numero de serie du lecteur d'empreinte digital du QG de MI7 ? ");
  Serial.println("1) 830023805326");
  Serial.println("2) 390423566734");
  Serial.println("3) 409213494563");
  while (Serial.available() == 0) {}
  Answer1 = Serial.parseInt();
  if (Answer1 == 2) {
    Serial.println("question 2 : Quelle est la frequence de transmission utilisee pour la communication entre agents de MI7 ?");
    delay(1000);
    Serial.println("1) 33 kHZ");
    Serial.println("2) 3,3 MHZ");
    Serial.println("3) 800 kHz");
    delay(1000);
  } while (Serial.available() == 0) {

  }
  Answer2 = Serial.parseInt();
  if (Answer2 == 3) {
    Serial.println("Correct next question");
  } else {
    Serial.println("system shutdown door closing don't try to move if you move you die agents will be here in 10 secondes");
  }
}

I suspect that there is some data left in the buffer (e.g., a line ending) that needs to be removed before the second variable is read. Perhaps you can try the following:

while (Serial.available() == 0) {}
Answer1 = Serial.parseInt();
while (Serial.available()) { Serial.read(); }

And the same for Answer2 of course.

Yes, it worked thank you.

Better to do something more like this:

// Print the prompt for the next question, and wait for it to all be sent
Serial.print("Print next question here");
Serial.flush();
// Flush the Rx buffer, and also ensure any extra characters from previous questions have arrived
while (Serial.available())
    Serial.read();
// NOW that the Rx buffer is empty, read response
Answer1 = Serial.parseint();

Using Serial.parseint() to flush the buffer will add a ~1 second delay, which is not needed, and not desirable.

The better approach, overall, is do not use ParseInt or other canned functions. Simply parse the characters yourself, discard any you don't need, like line endings. Read charactes as they arrive, and copy them to a message buffer. When you accumulate a full message, only then do you process it. This allows you to disallow invalid characters, make sure all messages are properly formatted an valid, and discard invalid one.

Can you explain more in details please, I'm new to all of this and I don't know everything yet.

You may want to have a look at this tutorial:

Thank you.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.