Somethings Serially Wrong - Bug ? or me ?

This is driving me nuts…

Its supposed to read the 1st 3 chars from the Serial line… if its “led” then it is supposed to turn the led on or off - whatever is the opposite of what it was… It then clears the input, resets dataIn to blank

The problem is in the if stmt where I check for “led” - the 1st time through it works as expected… but from that point on, every character I type in the console is concatenated with a NULL (space in the console)… but if I take the ledState = !ledState out, my input is normal…

// led control

int ledPin = 13;
int ledState = LOW;
char dataIn[4] = "\0";
const char ledStr[4] = "led";
char tmpChar;

void setup() 
{ 
  Serial.begin(14400); 
  Serial.println("Ready for commands");
  delay(100);
  pinMode(ledPin, OUTPUT);
} 

void loop() 
{
  while ((Serial.available() > 0) && (strlen(dataIn) < 3))
  {
    tmpChar = Serial.read();
    strcat(dataIn, &tmpChar);
    Serial.print(":");
    Serial.print(dataIn);
    Serial.println(":");
    delay(100);
  }
  if (strncmp(dataIn, ledStr, 3) == 0)
  {
    ledState = !ledState;
    digitalWrite(ledPin, ledState);
    Serial.println("led");
  }
  if (strlen(dataIn) != 0)
  {
    dataIn[0] = 0x00;
    Serial.print(":");
    Serial.print(dataIn);
    Serial.println(":");
    Serial.flush();
  }
  delay(100);
}

This is what the output of the code above looks like on the console…

Ready for commands
:l:
:le:
:led:
led
::
:l :
:l e :
::

Don’t know if it matters… but I am on a Mac… so if someone tries this on a windows machine and it doesn’t do the same thing, please post that

strcat() operates on null terminate strings. I don't think you can count on the byte following tmpchr being null, so that &tmpchr ends up pointing to a null-terminated string.

Hmm. I don't think C includes a standard function for appending a single character to a string. the easiest solution is probably something like:

char tmpChar[2] = {0,0};
    :
tmpChar[0] = Serial.read();
strcat(dataIn, tmpChar);

Yep..... the bug was me ! That fixed the problem...... Thanks a bunch ! :slight_smile: