Comparing Serial inputs to desired inputs

I am trying to get my code to only recognize whole numbers in the range of 0-15 as correct input. However my code will recognize inputs with decimals. I know that they are included in my if statement but I am unable to figure out a good way to sort these numbers out. The code should also only respond once to an input but if I input a 7 then it will print a message for 7 followed by a message for 0. If I was to enter 15.5 it prints one message for 15 and another for the number 5. I have also attached a photo example of the situation of double printing with the input 15 and 15.5.

void loop() {
  long StartTime = 0;
  long EndTime = 0;
  float ReactionTime = 0;
  int input = 0;
  int count = 0;
  while (1) {
    if (count == 0) {
      StartTime = millis();
      count++;
    }
    if (Serial.available() > 0) {
      count = 0;
      wdt_reset();
      EndTime = millis();
      input = Serial.parseInt();
      if (input >= 0 && input <= 15) {
        ReactionTime = (EndTime - StartTime);
        ReactionTime = ReactionTime / 1000;
        Serial.print("Your input was: ");
        Serial.println(input, HEX);
        Serial.print("Your Reaction Time was: ");
        Serial.print(ReactionTime, 3);
        Serial.println("seconds");
        Serial.println("Please enter another number from 0-15 in decimal");
        if (input < 10) {
          Serial.println("Im here");
          sevseg.setNumber(input);
        }
        if (input == 10) {
          sevseg.setChars("A");
        }
        if (input == 11) {
          sevseg.setChars("B");
        }
        if (input == 12) {
          sevseg.setChars("C");
        }
        if (input == 13) {
          sevseg.setChars("D");
        }
        if (input == 14) {
          sevseg.setChars("E");
        }
        if (input == 15) {
          sevseg.setChars("F");
        }
      }
      else {
        wdt_reset();
        Serial.println("Input Invalid please input a number from 0-15 in deciaml");

Capture.PNG

Capture.PNG

This sounds like a class project, see the solution at

bornclucth:
If I was to enter 15.5 it prints one message for 15 and another for the number 5.

If you want the program to work with integer values from 0 to 15 why on earth would you enter 15.5 ?

The Serlai.parseInt() statement treats the parts either side of the period as two separate entries and one of them is read on each iteration through loop().

Try adding these lines after Serial.parseInt() - they will discard any extra characters in the Serial Input buffer

while (Serial.available() > 0) {
   Serial.read();
}

For a more comprehensive approach have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. And have a look at the user input example in Planning and Implementing a Program

...R

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