I'm reworking and cleaning up an ex-coworker's code. I created a union to simplify the "parsing" and "construction" of a message by a UART transmission protocol he designed.
Example message: !cx:000:2047
The first character indicates whether the parameter (defined by the second and third character, in this case cx
) should be set (!
) or returned (?
) to the sender of the message. If needed, the address part of the message (000
) defines the index in an array where the value specified (in this case 2047
) should be written to. The Command, the address and the value are separated using the :
character.
I could've used strtok()
to separate the message using the separation characters but the receive buffer's size is fixed to 12 characters, the sender function makes sure that the message's format is right and I found this method to be the easiest to read and understand.
But now, that I've seen this thread, I'm not really sure whether folowing union is legal or not:
typedef union UartMessage
{
char msg[12];
struct
{
char dir; //[0]: set/get
char param[2]; //[1-2]: parameter to set/get
char separator1; //[3]: ':' separator
char addr[3]; //[4-6]: memory array index (used for current and speed arrays)
char separator2; //[7]: ':' separator
char value[4]; //[8-11]: value to set
};
} uartMsg_t;