Go Down

Topic: String or Char Arrays Length Definition (Read 2 times) previous topic - next topic

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.

tavovalencia


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:

Code: [Select]

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?

Erni

#12
Feb 06, 2013, 02:27 pm Last Edit: Feb 06, 2013, 02:29 pm by Erni Reason: 1
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.


Code: [Select]

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
}


}

JosAH

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

kind regards,

Jos

tavovalencia


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


EUREKA!!! jajaja thanks!

Go Up