String or Char Arrays Length Definition

I wanted to add a string or an array of characters after user inputs the text and hits "send"

strcat() does that.

OK, but how can I limit strcat() to 8 chars?

You could overload the function to add in another parameter, or put a null in the source at the position you want it to stop copying at.
If needed, store the 8th character in a temp, replace with null, when done just put the temp char back.

You could read and count the characters until you reach the terminator, while you store the characters in a character array.
The terminator could be Carriage return, or other special you choose
If the count is >8, warn the user, ans start over.

Erni:
You could read and count the characters until you reach the terminator, while you store the characters in a character array.
The terminator could be Carriage return, or other special you choose
If the count is >8, warn the user, ans start over.

This sounds great, though I'm not sure how to implement the If. I have this so far:

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


 if(index < 8){
           inChar = Serial.read(); 
           Name[index] = inChar; // Store it
           index++; // Increment where to write next
           Name[index] = '\r'; // Carriage to terminate the string
       }
else{
           Serial.println("Invalid Input, please enter 3 to 8 characters");
}

Will that work?

That was something like that I was thinking, although I think that the below test Sketch is more likely what you want.
You need to clear the Name array in case of wrong number of entrys, and end the Array with the null terminator.
There might be some errors in the sketch, but it explains better than words what I meant.

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");
           }
   
   if (int(Name[index])==13){  //If Carriage return has been reached
            Serial.println(Name);    
         index=0;
}

index++; // Increment where to write next
}


}

The Stream class has a readBytesUntil( ... ) function; have a look at it.

kind regards,

Jos

JosAH:
The Stream class has a readBytesUntil( ... ) function; have a look at it.

EUREKA!!! jajaja thanks!

Will that work?

No. A string is terminated by a NULL ('\0'), not a line feed ('\r').

EUREKA!!!

Keep in mind that you need to provide a large enough array to hold what the user typed, and that that may be more than 8 bytes.

PaulS:

EUREKA!!!

Keep in mind that you need to provide a large enough array to hold what the user typed, and that that may be more than 8 bytes.

jajaja I found out about this already the hard way, with this code if I enter 123456789 I receive back two lines, 1st: 12345678 and 2nd: 92345678 so it overwrites the array.

char Name[9]; // My Data array

void setup() {
 Serial.begin(9600);
 while (!Serial) {
   ; // wait for serial port to connect. Needed for Leonardo only
 }
 Serial.println("Please Enter your Name: ");
}
 
void loop() {
 while (!Serial.available()); // Wait for characters
 Serial.readBytes(Name, 8);
 Serial.println(Name);
 }

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

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.