Hi guys,I am exercise with Serial read char to string.
Here is my problem I meet.
If I don't add two command
Serial.print(F("temp: "));
Serial.println(temp);
my temp_int will be always one number,
For example I send string "100" I want to change to int "100", only if I add
Serial.print(F("temp: "));
Serial.println(temp);.
If I don't , the result will be "1" int.
I am very confused that use Serial print or not , will not effect the result.
but in my code that seems have influence.
void Attenuator_c::Get_string2int(void){
int index=0;
char temp_serial;
while (Serial.available()>0 ) {
if( (temp_serial=Serial.read()) != '\r'){
//char temp_serial=Serial.read();
temp[index]=temp_serial;
index++;
}
temp[index]='\0';
Serial.print(F("temp: "));
Serial.println(temp);
}
temp_int=atoi(temp); //for string to integer
for (int i=0; i < sizeof(temp); i++) { //for clear up temp to 0
temp[i]='0';
}
}
If I don't add
"Serial.print(F("temp: "));
Serial.println(temp); "
Then what?
Think about how long it takes to read serial data (almost no time, since it is copying data from one variable to another) vs. how long it tales to receive serial data (a relatively long time) and how long it takes to send serial data (again, a relatively long time).
You can empty the buffer (by read()ing) far faster than serial data can arrive to fill the buffer. By diddling around printing the data you read, you cause more time to pass, during which more data arrives.
You REALLY need to send some kind of end of packet marker (the \r is fine), and read and store data until that end of packet marker arrives, and print (and use) the data ONLY after the end of packet marker arrives.