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.
2 Answers 2
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.
Why are you using char array when you can use String. And use Serial.readStringUntil('\r'); instead Serial.read.
Code:
void parseSerial(){
String read = " ";
int count = 0;
if(Serial.available()>0){
while(Serial.available()>0){
if(count != 20){
read = Serial.readStringUntil('\r');
count++;
}
}
}
Serial.println("You said: ");
Serial.print(read);
}