Trying to use char arrays for receiving serial data

I'm trying to use char arrays for receiving serial data, and there is something I don't understand.

This code gives only a one as result (it's the last character of the incoming line)

char page;
char data;
long value;

void setup(){
    Serial.begin(9600);
    Serial1.begin(115200);
}

void loop(){
  SerialCommunication();
}

void SerialCommunication(){
    char recieved;
    char currentLine[30];
    char valueString[20];
    char response[255];
    byte charPos = 0;
    while (Serial1.available()) {
        recieved = Serial1.read();
        if (recieved == '\n') {
            Serial.println(currentLine);
            charPos = 0;}     // set char position of string to the beginning
        else if (recieved!= '\r') {    // if you got anything else but a carriage return character,
            currentLine[charPos] = recieved;      // add it to the end of the currentLine
            charPos++;     // and go to the next char posistion 
           // Serial.print("charPos = ");
           // Serial.println(charPos);
            currentLine[charPos] = '\0';     // null terminate the string
        }
    }
}

But when I uncomment the lines

   Serial.print("charPos = ");
   Serial.println(charPos);

I get the full line

charPos = 1
charPos = 2
charPos = 3
charPos = 4
charPos = 5
charPos = 6
charPos = 7
charPos = 8
charPos = 9
charPos = 10
charPos = 11
charPos = 12
charPos = 13
charPos = 14
charPos = 15
charPos = 16
charPos = 17
GET /AZ: HTTP/1.1

I hope someone can tell me what I might be doing wrong.

When you uncomment the Serial.print() statements, it significantly slows down your program. When it is not there, your while() statement

while (Serial1.available())

will no be true and your function will exit. The Arduino can operate way faster than incoming serial data. You need to wait until you receive a '\n' to know you got the whole input string (or whatever marks an entire line)

Ok, thanks. Adding a delay of 5 milliseconds seems to be working. But is this the best way to do this? or are there better ways? I'm still a beginner with all of this...

Serial comms is slow. When you call SerialCommunication() think what will happen if only 1 character is available at that time, which is quite likely. What will charPos be set to the next time that you call the function ?

Ok, thanks. Adding a delay of 5 milliseconds seems to be working. But is this the best way to do this? or are there better ways? I'm still a beginner with all of this...

I recommend that you study Robin2's excellent tutorial on reading and parsing serial input.

http://forum.arduino.cc/index.php?topic=396450

In the function SerialCommunication(), you are declaring several local variables that are not necessarily retained from one call to the next.

Try adding the keyword "static" to their declarations, so that the values are retained from call to call.

Thanks guys.
That tutorial helped a lot.
Using static did the trick.