Convert String To Int
In my post for Raspberry Pi Arduino Communication I wrote a function that will take a string value and convert it to the Pin Number, i.e. Converting a string to Integer.
Therefore,I wanted to take the time and explain how that function works and why, just in case someone needs that explanation.
Here is the code from that function:
{
while(Serial.available()>0)
{
Serial.println(val);
pinNumber*=10;
pinNumber+= (val-'0');
delay(25);
return pinNumber;
So what is going on here? loops, multiplication conversion of numbers, the character '0'...?
Really it is simple.
First thing we need to know couple of things:
-
Serial.available() - this will return a number greater than 0 as long as there are character in the Serial buffer.
We will need this in case we have a number that is bigger than single digit (i.e. 10 and above) - Serial.read() - this will read one byte (hence why we need the Serial.available function) from the serial buffer
- ASCII Table - a character is represent in the computer as ASCII value. Each keyboard character is ranged between 0-127 (or 0-255 for extended keyboard) here is a link to the ASCII table you will notice that the characters for numbers (0-9) runs from 48 - 57 ('0' = 48,'1'=49,...,'9'=57)
Knowing the ASCII table and its value now this line, (val-'0'), should make sense what it does. Because we assume that the string is a valid integer, we know that it can only contains the numbers 0-9.
and because we know that each ASCII has a number (for 0-9 it ranges from 48 - 57) we know that if we take the number's ASCII value minus the ASCII value of '0' we will get the real number.
For example lets take the number 8:
'8' = 56
'0' = 48
Therefore if we do '8'-'0' => 56-48 we get... you guessed it right 8
so now the question you might ask yourself (and maybe not, but I will answer it anyway :D) why do we do pinNumber *=10;
Well, first pinNumber *= 10 is a short hand for pinNumber = pinNumber * 10. Now, to understand what is going on and why we multiple by 10, lets look at an example.
Let say we have the number '123' coming in here is a table where the values will be after we do pinNumber += (val -'0')
Loop Number | Incoming Number | Val | pinNumber*=10 | pinNumber+=(val-'0') |
---|---|---|---|---|
Start | 123 | '' | 0 | 0 |
1 | 123 | '1' | 0 | 1 |
2 | 123 | '2' | 10 | 12 |
Last Iteration | 123 | '3' | 120 | 123 |
So that basically it, that is why we have the GetPinNumber function, and that is how we convert a string to Integer.