1

I am trying to get the string ("Enter an Integer : ") to print to the serial, then have the user enter a string of numbers which is then converted to an array of chars then ints.

The problem is the string will not display on the serial monitor when opened, and when the numbers are entered by the user, and the conversion is done I need the string to be displayed again. So when the user inputs a number and presses enter it should be the end of that conversion, and prompt a new one.

Code below:

int convert(void) {     
  while (Serial.available() > 0) {     
    char ch = Serial.read();
    if (ch >= '0' && ch <= '9' || ch == '-') {
      // Collect digits, only works if minus is first. 
      strValue[index] = ch;
      index++;
    } else {
      strValue[index] = '\0'; 
      blinkRate = atoi(strValue);
      Serial.println(blinkRate);
      Serial.print("Enter integer : ");
      index = 0;
    }
  }        
}
  • What does the serial monitor display when you run this code and type a number? – Dmitry Grigoryev Jan 8 '16 at 9:39
  • 1
    The number does not register until I enter a letter, which is one problem. I would like the number to register when the user presses enter. – DavidBobo Jan 8 '16 at 13:39
  • Why are you checking for '\0' instead of '\n'? – Paul Jan 9 '16 at 8:29
2

The biggest problem I see is that when your convert() function is called, if the user hasn't already typed something, then Serial.available() is going to return 0 (zero) and the while statement will never get executed.

Second, your print statement that prints the prompt to the console will only get called after you have already read a string from the user.

Third, you're trying to reinvent the wheel by writing your own function to read a string from the serial input. I suggest you use ReadStringUntil().

1

The problem is, the Arduino serial monitor is way too crude to understand what you're trying to do. Using a real terminal emulator (Teraterm for example) will probably give you better results (but you will also need to echo back the characters typed so you can see what you're typing) - either that or don't try and do things "in-line" like a prompt, instead print a message including the line feed (i.e., use println() instead of print()) so that the serial monitor can output a new line with the message text in it.

1

It seems likely to me that you have not configured your serial monitor to send a newline. See the bottom line of the Serial Monitor.

Serial monitor configuration

If it is set to "no line ending" then when you send the line, you get the line only and no newline.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.