Serial.parseInt reading a zero

So I am very new to coding in general so sorry if there are formatting issues or bad practices. I am creating a program that allows you to pick two preset units to convert but only one way. Later I'll probably try to make the units not preset but I'm just starting out right now. The Issue that I'm having and am unable to solve is when once you pick which option you want it initially says 0 (unit) is 0.00 (other unit). It also says this after each time you enter a number:

float conversions[] = {1.60934, 3.28084, 2.54};
void setup() {
  Serial.begin(9600);
}

void loop() {

  Serial.println("What do you want to convert? ");
  Serial.println("1. miles to kilometers");
  Serial.println("2. feet to meters");
  Serial.println("3. in to cm");
  
  while (!Serial.available());
  
  int choiceNum = Serial.parseInt();


  if (choiceNum == 1) {
    Serial.println("Now converting miles to kilometers enter a value for miles, type -111 to exit: ");
  }
   
while (choiceNum == 1) {
    
    while (!Serial.parseInt() == 0);
    
    int mi = Serial.parseInt();
    
    if (mi == -111) {
      return;
    }
    
    float km = mi * conversions[0];
    
    Serial.print(mi);
    Serial.print(" miles is: ");
    Serial.print(km, 2);
    Serial.println(" kilometers");
  }

  
  if (choiceNum == 2) {
    Serial.println("Now converting feet to meters. Enter a value for feet, type -111 to exit: ");
  }
  
  while (choiceNum == 2) {
    
    while (!Serial.available());
    
    int feet = Serial.parseInt();
    
    if (feet == -111) {
      return;
    }
    
    float meter = feet * conversions[1];
    
    Serial.print(feet);
    Serial.print(" feet is: ");
    Serial.print(meter, 2);
    Serial.println(" meters");
  }


    if (choiceNum == 3) {
    Serial.println("Now converting inches to centimeters. Enter a value for inches, type -111 to exit: ");
  }
  
  while (choiceNum == 3) {
    
    while (!Serial.available());
    
    int in = Serial.parseInt();
    
    if (in == -111) {
      return;
    }
    
    float cm = in * conversions[2];
    
    Serial.print(in);
    Serial.print(" inches is: ");
    Serial.print(cm, 2);
    Serial.println(" centimeters");
    
  }
}

Thank you!! (I've been trying to solve this on my own for a while, I didn't come here the second something went wrong.)

Shouldn't:

  while (choiceNum == 1) {
    while (!Serial.parseInt() == 0);

be:

  while (choiceNum == 1) {
    while (!Serial.available());

?

See my Arduino Software Solutions for how to read text from serial.
The sketch ReadToInt_String.ino reads and parse integer inputs.

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