0

I have a project where I use a software serial connection to read serial data from a barcode scanner.

All is good. However from time to time I have some problems with the data that I'm receiving.

You said : 123456789��?�: @���?���?���?���?���?

You said : 123456789

You said : 123456789123456

You said : 987654321789456123

My code is something similar to the one below

int count = 0; 
void parseSerial() {
  char ser[20];
  while (Serial.available() > 0) {
    char c = Serial.read();
    if ( c != '\r' && count <= sizeof(ser)) {
      ser[count] = c;
      count++;
    } else {
      Serial.print("You said : ");
      Serial.println(ser);
      for(int i=0; i < sizeof(ser); i++) {
        ser[i] = '\0';
      }
      count = 0;
    }
  }
}

Any idea on how I can get rid of "��?�: @���?���?���?���?���?"?

Thanks.

3

The problem is that the buffer is not initialized to start with. When you call parseSerial(), it contains garbage, which is what you see on the serial monitor. In order to avoid printing out that garbage, you have to properly terminate the string, i.e. add a \0 after the last valid character.

You did that after printing the string (you filled the whole buffer with \0, which is overkill), but that's too late. The subsequent printouts are OK though.

The recommended way to handle incoming serial data is to look for a terminating character (\r seems to be what you expect), and buffer all the incoming bytes until you see it. Don't forget to save 1 byte of buffer space for the terminating \0:

void parseSerial() {
    static char buffer[20];
    static int count = 0;

    while (Serial.available()) {
        int c = Serial.read();
        if (c == '\r') {           // received complete line
            buffer[count] = '\0';  // terminate the string
            Serial.print(F("You said: "));
            Serial.println(buffer);
            count = 0;
        }
        else if (count < sizeof buffer - 1) {
            buffer[count++] = c;
        }
    }
}

Notice that the buffer here being static, you can accumulate partial messages through successive calls to parseSerial(). Only when the message is complete will it print it back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.