Serial Port Communication

Hi all,

i am fairly new to arduino, and i am having a great time learning all the new and exciting things you can do with it, however i am having a great deal
of trouble communicating with my serial port via my code.

I would like to write a code that will present the following in the serial port
" Please enter the number of cars you have"
" Please enter your age"
“Please enter a random number”

After each statement, the user inputs a number
I have set up my code , so that i am using arduinos string to int function. However for some reason, when i run the code it prints the first question, allows me to anser it, then prints the second question, allows me to answers it, then prints the second question again and again each time i press enter. It is not printing the 3rd question at all.

Please see attached code
i cannot seem to find the error…

Serial__port_example.ino (801 Bytes)

I put your code through the IDE's auto format tool, and edited out some of the whitespace. Does this make it any clearer?

String inString = "";    

void setup() 
{
  Serial.begin(9600);
  Serial.println("Please enter the number of cars you have ");

  // Read serial input:
  while (Serial.available() >=0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      inString += (char)inChar; 
    }

    if (inChar == '\n') {          
      Serial.println(inString.toInt());
      inString = "";
      Serial.print("Please enter your age");
    }
  }

  while (Serial.available() >= 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      inString += (char)inChar; 
    }
    if (inChar == '\n') {
      Serial.println(inString.toInt());
      inString = "";
      Serial.print("Please enter a random number");
    }
  }
}


void loop() 
{
}

Hi,

Thanks for your reply, i still cannot seem to find the error in the code . it doesnt seem to be reading the last while loop, nor printing the last question. I have taken the perspective that if i have serial.available to be >0, then any number i enter should be displayed for each of the 3 questions ...

Can you see how you would ever leave this while() loop?

  while (Serial.available() >=0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      inString += (char)inChar; 
    }

    if (inChar == '\n') {          
      Serial.println(inString.toInt());
      inString = "";
      Serial.print("Please enter your age");
    }
  }

yes !. Thats much clearer. I have uploaded the correct code.

Now that the code is running, i am not sure how best i can store the answers for each question , back into my arduino code . Im thinking maybe
i use the line

val_1 = inString
val_2=inString
val_3=instring

Within each of the if loops . Does that sound correct ?
Thanks for your help.

Serial__port_example.ino (805 Bytes)