String or Char Arrays Length Definition

Is there a way to avoid overwriting?

Yes, and no.

The signature for the readBytes() method is:

  size_t readBytes( char *buffer, size_t length); // read chars from stream into buffer
  // terminates if length characters have been read or timeout (see setTimeout)
  // returns the number of characters placed in the buffer (0 means no valid data found)

So, you know how many bytes were received. You can NULL terminate the array after that number of characters. That would make the output you saw "12345678" and "9".

I think a better approach is to use readBytesUntil() and send an EXPLICIT end of packet marker (the Serial Monitor can do that automatically). Then, simply check the number of bytes received.

tavovalencia:
Is there a way to avoid overwriting? ... not sure if I should go back to the other suggestions.

Some code posted earlier showed how to read characters one by one and append them to the array, incrementing an index variable that held the length of the string received so far.

All you need to do is add a check that the array is not already full, before you append another character to the string.

    if (Serial.available()>0)
    {
        inChar = Serial.read(); 
        if(index < 7)
        {
            Name[index++] = inChar; // Store it
            Name[index] = 0; // append null-terminator
            // ... etc
        }
        else
        {
            // buffer is already full - discard the character
        }
    }
Name[index] = 0; // append null-terminator

Should it not be: ?

Name[index]='\0';

They are equivalent. ASCII for null is 0

To prove it, try this

char myChars[] =  "1234567890";

void setup() 
{
  Serial.begin(9600);
  output();

  myChars[7] = '\0';
  output();

  myChars[5] = 0;
  output();
}

void loop() 
{
}

void output()
{
  Serial.println(myChars);
  for (int i = 0;i <= 10;i++)
  {
    Serial.println(myChars[i],HEX); 
  }
  Serial.println(); 
}

Back to the original problem... I almost got it. I still have a couple of questions (below!);

Here's the code:

char Name[9] = ""; // My Data array
char inChar; // Where to store the character read
byte index = 0; // Index into array; where to store the character


void setup(){

Serial.begin(9600);

}

void loop(){
  if (Serial.available()>0){
     inChar = Serial.read(); 
     Name[index] = inChar; // Store it
     if (index>8){
         Serial.println("Invalid Input, please enter 3 to 8 characters");
         index=-1;
         memset(Name, 0, sizeof(Name));
     }
   else if (int(Name[index])==13){  //If Carriage return has been reached
            Serial.println(Name);    
         index=-1;
         Name[9] = '\0';
         memset(Name, 0, sizeof(Name));         
   }
   index++; // Increment where to write next
  }
}

If I insert any string from 1 to 8 chars it works perfectly, else:

  • 9 chars - println the error message - GREAT!
  • 9 chars - sometimes prints error message twice (more than 20 chars) or error message + modulos 10 (that is the 11th, 12th, 13th... chars) - I don't get why? or how to avoid?

Thanks for your help so far!!

         Name[9] = '\0';

For an array of 9 elements, what are the valid index values? Hint: 9 is not one of them.

PaulS:

         Name[9] = '\0';

For an array of 9 elements, what are the valid index values? Hint: 9 is not one of them.

array of 9 elements = 8 valid values. right? I don't really get what you're suggesting?

tavovalencia:
array of 9 elements = 8 valid values. right?

No. The first element is array[0]. Count up to nine elements and see which index values you used.

PeterH:

tavovalencia:
array of 9 elements = 8 valid values. right?

No. The first element is array[0]. Count up to nine elements and see which index values you used.

According to your explanation, there would be 10. But according to http://arduino.cc/en/Reference/Array

int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = "hello";

so there are 5 values in the first and 5 letters in the second. I still don't get your point?... with my code loaded... press a key and hold until 20 or more chars have appeared in the dialog and then press enter... the error message appears several times and sometimes other chars bellow...

lets look at index vs character position:

Index Char position
0 1 (first character)
1 2
2 3
3 4
4 5
6 7
7 8 (last character)
8 9 (nul goes here at arry[8]

  • INPUT: "1" ; OUTPUT: "1"
  • INPUT: "12345" ; OUTPUT: "12345"
  • INPUT: "12345678" ; OUTPUT: "12345678"
  • INPUT: "123456789" ; OUTPUT: "Invalid Input, please enter 3 to 8 characters"
  • INPUT: "12345678901" ; OUTPUT: Blank line, "Invalid Input, please enter 3 to 8 characters" & line with "1"
  • INPUT: "123456789012" ; OUTPUT: Blank line, "Invalid Input, please enter 3 to 8 characters" & line with "12"
  • INPUT: "012345678901234567890123" ; OUTPUT: "Invalid Input, please enter 3 to 8 characters" twice& line with "0123"

I would love to have just the ERROR ONCE. Any ideas, please!!!!

tavovalencia:

PeterH:

tavovalencia:
array of 9 elements = 8 valid values. right?

No. The first element is array[0]. Count up to nine elements and see which index values you used.

According to your explanation, there would be 10.

No it wouldn't. Actually do the experiment I suggested. Write down the array index values for an array with nine elements. The first element is array[0]. The second element is array[1]. Keep going until you have listed nine elements, and see what range of numbers you have used within the square brackets.

I would love to have just the ERROR ONCE. Any ideas, please!!!!

Just the usual one. Post the code that generated that output.

Define what is sending the data, with what end of packet marker.

I thought it was clear from before:

char Name[9] = ""; // My Data array
char inChar; // Where to store the character read
byte index = 0; // Index into array; where to store the character


void setup(){

Serial.begin(9600);

}

void loop(){
  if (Serial.available()>0){
     inChar = Serial.read(); 
     Name[index] = inChar; // Store it
     if (index>8){
         Serial.println("Invalid Input, please enter 3 to 8 characters");
         index = -1;
         Name[9] = '\0';
         memset(Name, 0, sizeof(Name));
     }
     else if (int(Name[index])==13){  //If Carriage return has been reached
         Serial.println(Name);    
         index = -1;  
         Name[9] = '\0';
         memset(Name, 0, sizeof(Name));         
     }
   index++; // Increment where to write next
  }
}

The inputs are introduced via Serial Monitor. The Outputs are printed lines in the Serial Monitor as well.

That code is doing exactly what it should, rather than what you want. You need to answer all the questions if you expect us to help you. Especially the "and with what end of packet marker".

That is important because you should stop reading and storing when it arrives. If that happens with less than 8 characters before it (and more than 2), great. If not, then print the error message, but keep reading and discarding data until that happens.

I'm trying to do so, English is my second language and I'm not fluent in C++ either.

I don't know what to do with this phrase:

"and with what end of packet marker"

I understand the logic of stopping reading but don't know how... I tried using a Serial Reset as soon as it enters the if(index>8) [Serial.end() & Serial.begin()] with no luck. I just changed in the Serial Monitor the option beside the baud rate from 'No line ending' to 'Carriage return'.

I'm not being lazy I sometimes don't get everything 'I'm supposed to'...

I don't know what to do with this phrase:

You are using the Serial Monitor to send data. At the bottom of the panel, there is a drop down list with options for appending data to what is in the Send box. What option do you have selected? Anything other than none causes the Serial Monitor application to append something to what you enter.

That something can be detected on the Arduino, and used as the end of packet marker. We need to know what that something is.

If you are using "Carriage return" as the option, try something like this:

char inData[9];
byte index = 0;
bool errorPrinted = false;

void loop()
{
   while(Serial.available() > 0)
   {
       char c = Serial.read();
       if(char == '\n')
       {
          // Got the carriage return
          // Use the data in inData, if index in range

          index = 0;
          inData[index] = '\0';
          errorPrinted = false;
       }
       else
       {
          if(index < 8)
          {
             inData[index++] = c;
             inData[index] = '\0';
          }
          else
          {
             if(!errorPrinted)
             {
                 // Print an error

                 errorPrinted = true;
             }
          }
       }
   }
}