i want to send commands to my arduino mega2560 in patterns like this, using the serial connection:
"DM 100 150 "
the code to process these commands looks like this:
parseInput()
{
//when a byte has beed received
if (Serial.available() > 0)
{
// read the incoming byte:
byte command = Serial.read();
//position query received
else if (command == 'Q')
{
printData();
}
//new destination received
if (command == 'D')
{
readNewDestination();
}
//.....
}
void readNewDestination()
{
//(very) short delay needed
delay(1);
//read device
byte device = Serial.read();
//new destination for M
if (device == 'M')
{
//destination
float x = Serial.parseFloat();
float y = Serial.parseFloat();
M.setNewDestination(x, y);
}
//new destination for F
else if (device == 'F')
{
float x = Serial.parseFloat();
F.setNewDestination(x);
}
//....
}
when i try to read a byte B with Serial.read() immediately after i have read a byte A with Serial.read(), byte B always ends up being 255. i have to put a short delay (like above, at the beginning of readNewDestination()) or some code between the two calls to Serial.read() to correctly read the second byte.
putting sensible code between the two calls is not always possible, and i would like to not block / delay my code if i can avoid it.
Another (and better) solution is to put start- and end-markers before and after the data so the Arduino knows when it has all the data. This demo illustrates the technique.
One thing you can do is in the main loop you can read all the message, and then, knowing you have the message complete you can process it. In the main loop you can store the message in a buffer. You have to know when the message ends, throw the length of the message or throw some special character.
Says if one byte is in the buffer read two, now isn't that silly. Still it is a common mistake.
So wait until all the expected bytes are in or do a
while( Serial.available() == 0){ } // hold until serial byte is available
In front of each read.
could have thought about that myself. thanks
Robin2:
Another (and better) solution is to put start- and end-markers before and after the data so the Arduino knows when it has all the data. This demo illustrates the technique.