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– Dmitry Grigoryev2016年01月08日 09:39:39 +00:00Commented Jan 8, 2016 at 9:39
-
1The 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– DavidBobo2016年01月08日 13:39:27 +00:00Commented Jan 8, 2016 at 13:39
-
Why are you checking for '0円' instead of '\n'?aaa– aaa2016年01月09日 08:29:51 +00:00Commented Jan 9, 2016 at 8:29
3 Answers 3
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()
.
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.
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.
If it is set to "no line ending" then when you send the line, you get the line only and no newline.