MRL runs on a JVM and can communication to the Arduino micro-controller through a serial port. MRL controls the Arduino through a serial protocol.
MRL to Arduino uses a 3 byte command set
msg = METHOD
msg = PARAM1
msg = PARAM2
The Arduino can send information back to the MRL. It has a 4 byte protocol
msg = PIN
msg = METHOD
msg = HIGHBYTE
msg = LOWBYTE
When the Arduino is reading data from an analog pin, it will send analogRead value back in this return message. Since analogReads can be a value between 0 - 1023 the data will need 2 bytes (HIGHBYTE & LOWBYTE)
All of this works very well, until the serial messages get out of sync. Typically this error is caused by electrical noise on the system. The really bad part, is that once the data stream becomes out of sync, it (rarely) gets back in sync.
There are a couple of strategies in order to correct this issue. There is the CRC (cyclical redundancy check) - where a number is computed from the data bytes and sent in another byte. The other side does the same calculation and if the calculated value equals the byte sent, all is good. If not, then we know we have garbage.
I chose a simpler implementation. At the beginning of each message I send a MAGIC_NUMBER. I chose the value 170 ( 10101010 in binary) which I thought would be one of the most fragile (electrically) to start each message. Now if MRL or the Arduino do not get the MAGIC_NUMBER at the beginning they throw the message away. This will not guarantee your data is not corrupted, however, when there is corruption it will attempt to recover by throwing everything out, until it finds the MAGIC_NUMBER again.