This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

union splitting



Hi,

I work with unions, to send some float data over serial port.

Now I made these unions:

typedef union {
  uint8_t cmd_u8[2]; 
  unsigned int cmd_u16;
}tProtocolCmd;

typedef union {
  uint8_t u8[4];
  unsigned int u16[2];
  float f;
}tProtocolData;

typedef struct{
  uint8_t start;
  tProtocolCmd command;
  tProtocolData data;
  uint8_t crc;
  uint8_t end;
}tProtocol;

tProtocol* UART0Protocol;

As I fill these parameters:

UART0Protocol->command.cmd_u8[0] = 0x01;
UART0Protocol->command.cmd_u8[1] = 0x02;
UART0Protocol->data.u8[0] = 0x01;
UART0Protocol->data.u8[1] = 0x02;
UART0Protocol->data.u8[2] = 0x03;
UART0Protocol->data.u8[3] = 0x04;

On the UART I get the next:

6F 22 53 0F 00 00

As I put these values in a simple variables, these are works fine.

Best regards, 

Sandor

  • I have no expertise in using a UART.  But I will point out that this structure ...

    Sandor Bedo48 said:
    typedef struct{
      uint8_t start;
      tProtocolCmd command;
      tProtocolData data;
      uint8_t crc;
      uint8_t end;
    }tProtocol;

    has holes in it for alignment of the data types.  Between start and command, for instance, there will be a one byte hole.  Could these alignment holes cause the problem?

    Thanks and regards,

    -George

  • Another possibility is that you're sending the value of the pointer (UART0Protocol) rather than the data it points to (*UART0Protocol).

    EDIT: Or perhaps the "simple variables" version works because you pass the address of the variable (eg &commandChar), but when you try to send the struct you're using &UART0Protocol, rather than just UART0Protocol.

    It would be good if you would post the part of your source code that sends the data over UART, both when using the tProtocol struct and plain variables.

    Please use the SyntaxHighlighter to insert the code. You can do this by clicking the "Use rich formatting" link under the reply box, and then clicking on this icon:

    Also, what MCU are you writing your code for?