Hi, this question may be dumb to a professional, but still, I often get confused & mix up & don't remember about Serial stuff.
So today I bumped into this problem - conversion between char, String and int.
Here's the programming code:
char c;
String s;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(6,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
while(Serial.available())
{
c = Serial.read();
s += (String)c;
}
if(s != "")
{
Serial.print(s.toInt());
s = "";
}
}
When I type "255" in the serial monitor, I received "25500", why?
I know char is just ASCII and I can just refer the table to find int, but I am just playing around and found this thing I don't know. If you are kind enough, please leave your knowledge and guidance to help me. Thanks in advanced
Because you print the integer values of each character.
I read this several times, and went WTF. Then, the light went on, so I think that more detail is needed.
OP. What is happening is that serial data arrives very slowly, far slower than the Arduino can read it. So when you send "255", the '2' arrives. The Arduino reads that, adds it to s, and sees that there is no more data available to read. So, it converts "2" to an int, and prints it.
Some (many) iterations of loop() later, the first '5' arrives. You can see what happens. Its a repeat of the above.
Ditto for the second 5.
Then the carriage return arrives, and gets converted to an int. What you would expect that int to be, other than 0?
Because you print the integer values of Strings consisting of a single character for each received character.
would have been better? It sounds convoluted.
Maybe a suggestion that OP print the String between delimiters would have been enough to enable him/her to see why he/she was getting the results that he/she was getting.
Part of the problem is that beginning programmers often don't realize there is a difference between the ASCII character '2' (Ascii code of 50) and the numeric value 2. They see them as the same, but this program shows they are different: