Double  the data, half the fun

Hey guys, Yet another serial coms question. Im feeding the string LF100 to my arduino via the serial monitor. I want to take that string and split it into two chars, cmd = LF and param = 100, and then echo one of them back. so in comes LF100, that gets chopped into command (first two bytes) and params (last 3 bytes) and then I want to echo back cmd. When I run this program though, I end up getting something like LF100LF100Ah
sent back to me. It looks like the data is not split and is double of what I sent via the serial monitor! The code is below, any thoughts?

/*

  • Robots hate me
  • Control a robot's movement via a serial connection
  • Assumes DC motors controlled with PWM

*/
#include <string.h>

//Setup
void setup()
{
Serial.begin(9600); //setup the serial port for 96008N1
}

void GetString(char *buf, int bufsize) //Get the command from the serial port
{

int i;
Serial.flush();
for (i=0; i<bufsize - 1; ++i) //start feeding the buf variable
{
while (Serial.available() == 0); // wait for character to arrive
buf = Serial.read(); //read data into buf
_ if (buf == '\0' ) // is it the terminator byte?_
* break;*
* }*
}
void loop()
{
* char cmd[2];*
* char param[3];*
* char buffer[6]; //serial command buffer*
* GetString(buffer, sizeof(buffer)); //capture the command from the serial port*
* if (strncmp(buffer, "LF", 2) == 0) //If the first two bytes are LF*
* {*
* strncpy (cmd, buffer, 2); //copy the first two bytes into cmd*
* strncpy( param, buffer+2, 3 ); //copy the last 3 bytes into param*
* Serial.println(cmd); //and print it*
* }*
}
[/quote]

GetString(buffer, sizeof(buffer)/sizeof(buffer[0])); ?

PS: I think that what you are trying to do is possible to accomplish by only sending two chars, as opposed to 5. (less that can go wrong)

If, for example, you define several ASCII values as your opcodes you could send two asciis, one opcode, one value.

Just for the fun of it, lets say that instead of LF you could send the ASCII '\n' followed by ASCII d. This would essentialy be the same as LF100. [note that '\n' is not a good choice, I just had to ('\n' is LineFeed)]

Hey, again featherpenguin! :slight_smile:

Your code is not too far from wrong. The problem is that (in most cases) C strings must be terminated by a nul (0) byte, and yours aren't. You copy two characters, "L", and "F", into cmd, but since cmd is only two bytes long, there is no room for the terminator byte. So when you Serial.println() it, it prints cmd followed by whatever's in memory after it (which happens to be param).

To fix your problem, just change

char cmd[2];
char param[3];

to

char cmd[3] = {0};
char param[4] = {0};

That'll make sure that the buffers are long enough (and initialized to 0).

Mikal