elarduino:
I was looking on the forum as I was struggling with this question, and only found answers that were not satisfactory to me... Since that was an old post without ability to reply, here is my post and how I solved the problem:
First, reading data from serial, to build a String object
if (mySerial.available()) {
command ="";
while(mySerial.available())
{
command += (char)mySerial.read();
}
Then getting the number out of the string (here I have an integer number which I know is 4 characters long:
char delaystr[5]; //create the char array
command.toCharArray(delaystr,5); //convert the String 'command' into the char array
int delayT = atoi(delaytstr); //convert the char array into integer
Voila!
For what it's worth, here is how I get user input from the serial terminal (text or numeric):
First, the basic "line input" code:
// read a line from user into buffer, return char count
int readline(char *buf, int limit)
{
int x;
int ptr = 0;
while(1) {
if(Serial.available()) {
x = Serial.read();
if(x == 0x0D) { // cr == end of line
buf[ptr] = 0; // null terminate string
return ptr; // return char count
}
if(x == 0x08) { // backspace
if(ptr > 0) {
ptr--;
buf[ptr] = 0;
Serial.print((char) 0x08); // backup cursor
Serial.print((char) 0x20); // erase char
Serial.print((char) 0x08); // backup cursor
} else {
Serial.print((char) 0x07); // beep == home limit
}
} else {
if(ptr < (limit - 1)) {
Serial.print((char) x);
buf[ptr] = x;
ptr++;
} else {
Serial.print((char) 0x07); // beep == end limit
}
}
}
}
}
You provide a buffer (i.e. "char buffer[32]"), then call the readline code with "buffer" and a limit as to how many characters to accept (of course, no more than the buffer size!).
If you want a numeric value from the user, then just do this:
// get user input, return as a float value
float get_user_input(void)
{
readline(buffer, 8); // buffer is 256 bytes, but we only allow 8 here which is enough
return atof(buffer);
}
Lastly, if you want to look for text data (such as "Y" or "N" for yes or no), you may want to stick an extra bit of code in there to keep the character case constant (i.e. convert all a-z to A-Z) so you only have to test for uppercase.
Hope this helps.