There are several reasons to have a protocol, even a very simple one.
- Reduce risk of errors, perhaps when the device is connected, started, stopped
- Allow for future expansion: perhaps the device sends two kinds of data in the future
- Make sure you're reading from the right device and not something different.
- Helps debugging if you can see a stream you can recognise.
There are some advantages in using ASCII chars, if you want to debug. I'll do it in binary, and include a length byte.
I would suggest a simple protocol of 6 bytes. Say:
Serial.write(0xc5); // start
Serial.write(0x06); // total length of packet
Serial.write(0x01); // 1=temperature data
Serial.write(data & 0xff); // low byte of data
Serial.write((data >> 8) & 0xff)); // high byte of data
Serial.write(0x5c); // end
Simple, easy to code, expandable. That would be my recommendation.
Here are some notes on my choices for these items.
- The start byte (0xc5) is a distinctive bit pattern, relatively unlikely to occur by chance, in which half the bits are off and half on. That makes it relatively easy to find with debugging tools including an oscilloscope.
- The end byte is the same reversed, for similar reasons.
- Including the length is the simplest kind of check for framing errors or dropped bytes. If the start byte, end byte and length match the packet is probably valid.
- The command byte of 0x01 allows room for expansion with future packet types. All packets should take the form
- The data is sent in little-endian format, which may be easier for some servers to read. Please note the correct use of shift-mask.
As suggested in a comment, the additional of a simple checksum would improve the likelihood of detecting errors over a noisy line. A simple rotating XOR should be sufficient, and easy to code.