You could encode with a special start character, and a checksum, ended with a CR/LF
(All values in hexadecimal)
- Start with a special character (ex, a column)
- Send the command (register number, +80 for read, ex: 01 = write register 1, 81 = read register 1)
- Send the length
- if a write, send the value to write (in hex for example)
- Finally, substract all the bytes sent, and send this, as a checksum.
Ex: To set value of register 1 to 5, set register 2 to '55 FF 02', and retrieve register 3.
:010105F9
:020355FF02A5
:82017D
Description of first line above:
:010105F9
':' is the start of line
'01' is a write to register 1
'01' is the length (1 byte)
'05' is the value
'F9' is 0 - '01' - '01' - '05'
CR/LF
Second line:
:020355FF02A5
':' is the start of line
'02' is a write to register 2
'03' is the length (3 bytes)
'55FF02' is the value (the 3 bytes 55 FF 02)
'A5' is 0 - '02' - '03' - '55' - 'FF' - '02' (equal A5, truncated to 1 byte)
CR/LF
Idem for the other lines. When reading back a value, something similar could be used for the device->PC reply.
So, this way, the device will know when a line start (with a column), it will know when it end (CR/LF) and will also know if the data is valid (check to see if it received 'length' bytes plus one byte for the command, one byte for the length and one byte for the checksum. Plus, by *adding* all the bytes it receive together, it will know that this is valid if and only if the sum equal zero.
When you receive a column, reset the checsum to zero, and start over. When you receive a CR, check the result.