What is the best way to collect data?
One character at a time.
while(Serial.available() >0) { //only when serial active
header = Serial.read(); // header gets 1st byte
if(header == 65) { // if header is 65 (A), bytes 1 and 2 are next two serial reads
byte1 = Serial.read();
byte2 = Serial.read();
If there is at least one byte to read, read it, and then possibly two more. Can you see why this is a bad idea?
When you use Serial.print() on the sender, it converts the value to a string, and sends several characters. You are not sending binary data (and there would need to be FOUR reads if you were, since a long is 4 bytes).
Change your sender to send something like "<123456, 654321>".
Then use code like this:
#define SOP '<'
#define EOP '>'
bool started = false;
bool ended = false;
char inData[80];
byte index;
void setup()
{
Serial.begin(57600);
// Other stuff...
}
void loop()
{
// Read all serial data available, as fast as possible
while(Serial.available() > 0)
{
char inChar = Serial.read();
if(inChar == SOP)
{
index = 0;
inData[index] = '\0';
started = true;
ended = false;
}
else if(inChar == EOP)
{
ended = true;
break;
}
else
{
if(index < 79)
{
inData[index] = inChar;
index++;
inData[index] = '\0';
}
}
}
// We are here either because all pending serial
// data has been read OR because an end of
// packet marker arrived. Which is it?
if(started && ended)
{
// The end of packet marker arrived. Process the packet
// Reset for the next packet
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
}
To read the data sent. Where it says "Process the packet", use strtok() and atol() to get the tokens ("123456" and "654321") and convert them to values.