serial comm problem with pointers

Hi,
I still can not figure out a strange problem in data sending over serial communcation of wrt54gl router with Arduino.

First of all, with a very straight forward and simple code you see here, I expect to run it, type "this" and get it back, but I receive some white space, then the characters of the word "this" but not in the order!

first the code:

void setup()
{
  Serial.begin(9600);
  Serial.flush();
  cmdbuf = (char*)malloc(sizeof(char) * MAXCMDLEN);
}

void loop()
{
  if(Serial.available()>0)
  {
    //char *cmdbuf = (char*)malloc(sizeof(char) * MAXCMDLEN);

    sriBufCounter = 0;
    while( Serial.available() && c != '\n' && sriBufCounter < MAXCMDLEN)  //MAXCMDLEN 128
    {
       c = Serial.read();
       cmdbuf[sriBufCounter++] = c;
    }
    analyzeCommand(cmdbuf, sriBufCounter);
  }
}

void analyzeCommand(char* cmd, int BufCounter)
{
    Serial.println(cmd);
}

now the screen shot:

the next very strange behavior I can't understand is that if I comment the pointer allocation in the setup, and uncomment the one (currently commented) in the loop function, then even the unordered "this" won't appear when I type it!

Please help to reveal the secret! :slight_smile:

Looks about right. Your arduino is processing the serial data faster than it arrives. And cmdbuf is unitialized.

So Arduino starts and cmdbuf garbage gets printed by analyzeCommand.
Then "t" arrives, repeat.
Then "h" arrives, repeat.
Etc.

You only want analyzeCommand to be called when you have received a full terminated command (i.e. when c = '\n' perhaps?).

I see! And how can I try to send a "this\n" by typing in the console of Arduino?

Even more interesting: in reference of Arduino, the null-termination is done with '\0', is this a problem with my code or '\0' and '\n' are the same?

Anyway I tried to type both "this\n" and "this\0" and I got them back the same, i.e. the escape character is not working. Any suggestion please?

Some serial softwares will automatically send a terminating character (cr or lf or both), but it varies on software and settings.

What I tend to do with my Arduino serial comms is use an explicit dlimeter like '|', and then discard/swallow any whitespace characters.

I tried with the router itself which sends '\n' automatically. Now what I get after:

echo 'this' > /dev/tts/1

is a an endless loop sending "is" to the console:

is
is
is
is
is
...

how do you comment this please?!

Also the second question is remained: why when i uncomment the pointer allocation in the loop and comment it in all other places, the "this" sent brings back white space! I.e. the code stops functioning at all!

I can't explain it why, but as I removed sriBufCounter = 0; I started to get "this" when I type "this". Even though, having it seems to be logical too!