Using Serial.read() w/ Character Array

I am trying to store constantly updated variables into a character array and I am not getting the consistency that I need.
Here is the code:

char str[4];

if(Serial.available())
{
      for(int i=0;i<3;i++)
        {
              str[i] = Serial.read();
         }
}

Is this the best way to read in the variables that I need? I am reading multiple variables at a time which could be two to three digits in length each and are sent next to each other as a whole number. Any help would be greatly appreciated. Thanks.

Try the almost identical:

char str[4] = {'\0'};

if (Serial.available()>=3){
  for (byte i=0; i<3; i++){
    str[i] = Serial.read();
  }
}

:slight_smile:

Since Serial.available() returns an int indicating the number of bytes available, I think your original test

if(Serial.available())

will only be true when there are an odd number of bytes waiting to be read.

Since Serial.available() returns an int indicating the number of bytes available, I think your original test

if(Serial.available())

will only be true when there are an odd number of bytes waiting to be read.

if will evaluate anything other than zero ( 0, NULL, '\0', false ) as true.

Be it 2, -3, &variable [if adress != 0] or 'a' :)

Thanks for the code. At first everything works great but upon drastic change in variables, the character arrays start reading random parts of the variables.

Here is the code I am using:

if(Serial.available()>=8)
 {
   char cogX[4] = {'\0'};
char cogY[4] = {'\0'};
char cog_box[4] = {'\0'};
  
   for(byte i=0;i<3;i++)
   {
     cogX[i] = Serial.read();
   }
   for(byte j=0;j<2;j++)
   {
     cog_box[j] = Serial.read();
   }
   for(byte k=0;k<3;k++)
   {
     cogY[k] = Serial.read();
   }
}

The main problem is that the first array starts reading the last digit of the previous line of variables and then continues on with the present line.