Getting two digit numbers

Hello everyone! I just have a small question to you all. I am not able to receive double digit numbers using Serial.read(). Does anyone know how to receive then and put them in an int variable? Thanks.

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

...R

Serial.parseInt() will return an integer. If it doesn't see any digits within a second it returns zero so it's usually best to use "while (Serial.available()== 0){}" first to make sure the value is starting to arrive before calling Serial.parseInt(). If there might be any characters AFTER the number that you don't want mistaken for the next number, "while (Serial.read() != -1){}" before the "while (Serial.available()== 0){}" will flush those out.

Ok Thank you all! I actually figured out a good method to receive multiple digits. Hope this will be of help in the future -

int getMultiple()
{
   String s;
   int i;

   s = Serial.readString();

   i = s.toInt();
   
   return i;
}

void loop()
{
    while ( !Serial.available() );
     a = Serial.read(); // a is a declared  integer 

     Serial.println ( a );
}

But thank you for all your replies! I will check all of them and see which is most efficient!

Take care using the String class with Arduino boards with small memory. Memory corruption is possible if String are used improperly. See the Evils of Strings page for explanation.

I recommend Robin2’s tutorial.

TheUNOGuy:
Ok Thank you all! I actually figured out a good method to receive multiple digits. Hope this will be of help in the future :-

int getMultiple()

{
  String s;
  int i;

s = Serial.readString();

i = s.toInt();
 
  return i;
}



But thank you for all your replies! I will check all of them and see which is most efficient!

I think this will work just as well and doesn’t use String.

int getMultiple()
{
  int i = Serial.parseInt();


  // Like Serial.readString().toInt(), throw out any 
  // extra characters that arrive after the number
  // and before the timeout.
  unsigned long startTime = millis();
  while (millis() - startTime < 1000)
    Serial.read();


  return i;
}

Hi,
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
OR
http://forum.arduino.cc/index.php/topic,148850.0.html.
Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Thanks.. Tom... :slight_smile:

johnwasser:
Serial.parseInt() will return an integer. If it doesn't see any digits within a second it returns zero [...].

Is it within a second or within an adjustable "timeout period" preset by this code: Serial.setTimeout(arg);?

GolamMostafa:
Is it within a second or within an adjustable "timeout period" preset by this code: Serial.setTimeout(arg);?

The default value is 1000ms, setTimeout() is optional.

johnwasser:
[...] to make sure the value is starting to arrive before calling Serial.parseInt().

Why is "starting to arrive" and not "has arrived"?

1. The characters/data bytes that have arrived at the Serial Port (the hardware UART Port) are being collected and saved into "Serial FIFO Buffer" on interrupt basis at the end of sketch uploading.

2. When uploading is done, the Serial.parseIn() also begins to work.

3. The above two processes are asynchronous; there is no way to tell which one has started first.

4. As the parseIn() method looks for charcaters/data bytes into the Serial Buffer, the user must be sure that the Serial Buffer has accumulated at least one character/data byte (edit) data bytes in order to ensure that parseInt() method works correctly. This is done, as you have shown, by the following code:

while(Serial.available() == 0)
{
    //wait
}

//----------------------------------------------------------------------------------------------------------------
5. The parseInt() method will terminate with zero return value if it does not find a character in the Serial Buffer within the "timeout period" since it has started.

6. The parseInt() method will terminate with a non zero return value if it does not find a character in the Serial Buffer within next "timeout period" since it has finished reading one or more valid charcaters (0 to 9).

7. The parseInt() method will also terminate if it finds a non-digit character (outside 0 to 9). The return value will be 0 if the very first character so read is a non-digit character. The return value will be non-zero if a non-digit character is encountered after reading one or more valid charcaters (0 to 9).(Edit)
//----------------------------------------------------------------------------------------------------------------

In scenario #4, ‘while(Serial.available() == 0)’ does not ensure that all the characters are available, it only ensures that at least one character is available. It’s possible that the rest haven’t arrived yet, and may or may not arrive before the time out period is exceeded.

For this reason, it can be blocking code.

IMHO it would be much better to have

if (Serial.available() >= X) {
   myVal = Serial.parseInt();
}

where X is the smallest number of characters that you propose to send. If you always send 2-digit numbers then X should be 2

...R

I would suggest @TheUNOGuy to use char arrays instead of strings.

…Arnav

ArnavPawarAA:
I would suggest @TheUNOGuy to use char arrays instead of strings.

…Arnav

? :o

ArnavPawarAA:
I would suggest @TheUNOGuy to use char arrays instead of strings.

1. "char array" is an array whose all elements are ASCII coded values. For example:

char myArray[ = {'A', 'B', 'C'};
==> char myArray[] = {0x41, 0x42, 0x43, 0x00};

2. "string" (and not String with Capital S) is a "set of printable characters of the English Language"; these characters could be members of a char-type array.

3. (So,) "char array" and "string' are the same things at conceptual/physical level.

4. "String" (with Capital S) is a user-defined "data type" which has been created using "class" keyword. An object (variable) could be declared using the said "String" data type. For example:

String myString;

5. The object/variable "myString" contains conglomerate of data items along with methods and functions for the processing of data items; whereas, "myArray' variable contains only one type of data items and no methods/functions.

GolamMostafa:

char myArray[] = {'A', 'B', 'C'};

==> char myArray = {0x41, 0x42, 0x43, 0x00};

That's wrong.

No NUL is added if you use character constants...

char myArray[] = {'A', 'B', 'C'};
==> char myArray[] = {0x41, 0x42, 0x43 };

You'd have to add your own if you wanted a terminating NUL...

char myArray[] = {'A', 'B', 'C', 0 };
==> char myArray[] = {0x41, 0x42, 0x43, 0x00 };

Or..

char myArray[] = "ABC";
==> char myArray[] = {0x41, 0x42, 0x43, 0x00 };

Hello, it is actually good to use Serial.parseInt() and because I have come from a C++ background I know abut Char Arrays and I will definitely use them. Thank you so much for your support!

Robin2:
IMHO it would be much better to have

if (Serial.available() >= X) {

myVal = Serial.parseInt();
}




where X is the smallest number of characters that you propose to send. If you always send 2-digit numbers then X should be 2

...R

just in case CR/LF can come in too and be a left over from the previous communication, you could wait for the first character (peek) to be either a +, - or a digit so that you know parseInt() will get work done and ignore other characters

@pcbbc

1. From your Post#15, it appears that the following two declarations are not equivalent.

char myArray[] = {'A', 'B', 'C'};
char myArray2[] = "ABC";

According to your Post#15, a NULL byte (0x00) is not inserted (during compilation) in the TOP declaration; but, it (the NULL byte) is inserted for the BOTTOM declaration.

2. As I know (form my DOS/int programming) that a NULL byte is needed at the end of a string so that the "output to console" (equivalent to print()?) command knows the end of the string.

3. When print() method is applied for both declarations of Step-1, ABC appears on the Serial Monitor in both cases.

4. Moreover, the execution of Serial.print(myArray[3]) for the TOP declaration of Step-1 shows 0 which is essentially a NULL byte.

I am still at the side to accept that the declarations of Step-1 are equivalent.

GolamMostafa:
I am still at the side to accept that the declarations of Step-1 are equivalent.

Why not write a short program to investigate rather than confusing the OP's Thread?

...R