Serial. readBytesUntil() Gives Garbage Value and Cause Setup() Function Act Like Loop.
I'am Trying to Read String Using Serial. readBytesUntil() Function. My Code Is Here: Char *Name_Arr; Char *Test = "Serial. Begin Is Ready"; Void Setup(){...
I'am trying to read string using Serial.readBytesUntil() function. My code is here :
char *name_arr;
char *test = "Serial.begin is Ready";
void setup(){
Serial.begin(9600);
Serial.println(test);
}
void loop(){
if (Serial.readBytesUntil('\r', name_arr, 10)){
Serial.println(name_arr);
Serial.println();
}
}
When I give only one digit as serial input , nothing happens.Serial.println() function prints nothing.
But when I give input more then two numerical digit like 15,12 etc , it started to print garbage values in infinite loop.
If I give character inputs like "asd" or use this code for loop() instead of previous one :
void loop(){
while (Serial.available()>0){
Serial.readBytesUntil('\r', name_arr, 10);
Serial.println(name_arr);
Serial.println();
}
Then it prints the whole string "test" except first two characters.But test is printed only in the setup function:
It seems like setup() function run again and again .
How can I save a string input in a character array (not in string class) ?
How could a function can rerun the setup function and why initial two digits are not printed?
1 Answer
readBytesUntil will store bytes in the second argument (see here), but you have declared only a pointer, not an array. A pointer defaults to address zero, so readBytesUntil was storing characters at address 0. Bad, very bad. This caused the reset, which looks like setup keeps running over and over.
You need to change the declaration to:
char name_array[11];
Also, don't forget that C-style strings (i.e., char arrays) need to be NUL-terminated. readBytesUntil returns the number of characters it read, and you can use that return value to terminate the string:
size_t num_read = Serial.readBytesUntil('\r', name_arr, sizeof(name_arr)-1 ));
name_arr[ num_read ] = '\0'; // a zero byte, ASCII NUL
This is why it didn't print properly. Notice that the declaration has an extra byte for the NUL ("11", not "10"), and the 3rd argument to readBytesUntil is the array size minus 1.
The total sketch:
char name_arr[11];
char *test = "Serial.begin is Ready";
void setup(){
Serial.begin(9600);
Serial.println(test);
}
void loop(){
while (Serial.available()) {
size_t num_read = Serial.readBytesUntil('\r', name_arr, sizeof(name_arr)-1 );
name_arr[num_read] = '\0';
Serial.println(name_arr);
Serial.println();
}
}