read just one number from Serial. why does this code work ? :D

hello forum. i want to transmit just One number to the arduino, via serial. i canot have Any delay, on the code i will be using (it has to be done assap)

i found out that the following code works just fine :

int final;
int value;


void setup() {
  Serial.begin(9600); // same as in your c++ script
}

void loop()
{

  while (Serial.available()>0)  {
    char ch = Serial.read();
    if( isDigit(ch) )// is this an ascii digit between 0 and 9?
    {
      value = (value * 10) + (ch - '0'); // yes, accumulate the value
    }
    else {
      final = value;
      value = 0; 

    }

  }



  Serial.println(final) ;

in order for the code to work, the serial should end with a ", " . and i suppose it could be used to read more than one number, with the proper corrections.
the whole conversion takes about 20 -30 microseconds, so it is prety fast.
BUT, i do not understand why it works? :smiley: since its :

value = (value * 10) + (ch - '0');

shoulden't 22 be converted to 2+2 = 4 ??...

also, if i give very big random numbers, like 1273186381726 , then the conversion fails big time...

any explanation??

shoulden't 22 be converted to 2+2 = 4 ??...

No.
The last value is multiplied by ten so if value was two that line will multiply it by two giving twenty and then add to it the value two. Giving 22 as the correct result.

o yes, i see! thanks!!
but the fact that it fails above a number, bugs me... will it work reliable, in the range between 0 and 200 ?

When you send "2" to the Arduino from the serial monitor it is received as the Ascii code 50
The Ascii code for "0" is 48. So "ch - '0'" takes the 50 and subtracts 48 from it to give 2.

In each iteration the previous value is multiplied by 10 to shift it one position to the left and then the new value is added to it.

You have defined final and value as integers so their max positive value is 2^15 or 32768. If you multiply 32768 by 10 (in an integer) you just lose data.

If you want to receive a larger number you could define value and final as "unsigned long" which can hold a value up to 2^32.

...R

naiccccccccccc. thanks allot for the info!! :slight_smile: