johnwasser:
It looks like you are sending 13 characters when the line ending is included. The first 12 characters display correctly and the remaining one becomes the first of the next 12. Since you don't wait for all 12 to arrive before reading, most of what you get from .read() is -1 (0xFFFF) meaning "No character in buffer".
Do you ever want to receive a message that was not exactly 12 characters long?
Try this. It waits for 12 characters to arrive and then shows them in HEX and ascii.
char _command[13]; // You need room for the mandatory NULL terminator.
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 11) // Wait for at least 12 characters to arrive
{
Serial.println("Starting printing");
for (int i = 0; i < 12; i++)
{
_command[i] = Serial.read();
Serial.print("0x");
Serial.print((int) ((byte) _command[i]), HEX);
Serial.print(": ");
Serial.println(_command[i]);
// delay(100); // Not needed since we know al 12 have arrived.
}
Serial.println("finished printing");
delay(1000);
_command[12] = '\0'; // Mandatory NULL to treat the array as a string.
Serial.println(_command);
}
Serial.println("waiting");
delay(5000);
Serial.println("done waiting");
}
Hi, thanks for the descriptive reply.
I'm receiving a different, pre-set commands lengths. To handle this, I can switch-case on Serial.available() so I'm not worried, and can send the data to different parsers functions.
I tried your code, and tried to notice what @UKHeliBob said about inserting the data
only after all 12 characters have arrived, yet if I send the same command twice I get a weird result:
waiting
done waiting
09:28:01.652 -> Starting printing
09:28:01.652 -> 0x40: @
09:28:01.687 -> 0x30: 0
09:28:01.687 -> 0x41: A
09:28:01.687 -> 0x20:
09:28:01.687 -> 0x35: 5
09:28:01.722 -> 0x30: 0
09:28:01.722 -> 0x30: 0
09:28:01.722 -> 0x30: 0
09:28:01.722 -> 0x2C: ,
09:28:01.757 -> 0x39: 9
09:28:01.757 -> 0x30: 0
09:28:01.757 -> 0x30: 0
09:28:01.757 -> finished printing
@0A 5000,900
09:28:02.730 -> waiting
done waiting
09:28:07.738 -> Starting printing
09:28:07.773 -> 0xD:
09:28:07.773 -> 0xA:
09:28:07.773 ->
09:28:07.773 -> 0x40: @
09:28:07.773 -> 0x30: 0
09:28:07.807 -> 0x41: A
09:28:07.807 -> 0x20:
09:28:07.807 -> 0x35: 5
09:28:07.842 -> 0x30: 0
09:28:07.842 -> 0x30: 0
09:28:07.842 -> 0x30: 0
09:28:07.842 -> 0x2C: ,
09:28:07.877 -> 0x39: 9
09:28:07.877 -> finished printing
09:28:08.817 -> @0A 5000,9
09:28:08.852 -> waiting
As you can see, the output comes wrong after sending it twice in a row (meaning, sending 1 time, receiving 1 time, then sending again - not to confuse with sending '@0A 5000,900@0A 5000,900')
Does the arduino reset the buffer after all of the data arrived? or is there a command to reset it?
Thanks.