A problem whit comparison in if

I try to read from Serial and compar it to another variable.

char number=23;
void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  Serial.println("Guess a number");
  while(!Serial.available()){}
  char c = Serial.read();
  if (c == number)
  {
    Serial.println("correct");
  }
  else {Serial.println("try again");}
}

23 ASCII is a non-printing control character.
You're going to have to do more work to input and convert 0x32 and 0x33 into 23, if that's what you're trying to do.

you could also change this:
char number=23 ;

to:
char number=48;

Then the correct number to type in would be a '0', or 49 would be a '1' etc.

TheMemberFormerlyKnownAsAWOL:
23 ASCII is a non-printing control character.
You're going to have to do more work to input and convert 0x32 and 0x33 into 23, if that's what you're trying to do.

Can you give me a source of how to do this?

Start here

Use Serial.parseInt() instead of Serial.read(). WARNING: If you call Serial.parseInt() and no number arrives within the timeout period (default: 1 second) it will return 0. One solution is to empty the input buffer before prompting for an answer and then waiting for a character to arrive:

int number = 23;


void setup()
{
  Serial.begin(9600);
}


void loop()
{
  while (Serial.available()) Serial.read(); // Flush
  
  Serial.println("Guess a number");
  
  while (!Serial.available()) {}  // Wait for response


  int c = Serial.parseInt();
  if (c == number)
  {
    Serial.println("correct");
  }
  else
  {
    Serial.print(c);
    Serial.println(" is not correct, try again");
  }
}

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