Filling Struct from Byte Array

I am trying to fill a struct with a byte array. I am porting this code over from another MCU, but I can’t seem to get the values to fill properly. The values are incorrect. Has anyone attempted to do this and been successful on spark? Here is a paired down example.

typedef struct packet_t
{
	int16_t temperature;           	    /**< Current Temperature */
	int16_t rampRate;             	    /**< Current Ramp Rate */
};

uint8_t payload[4]; 

//payload filled with 2 16bit integers
packet_t *sp = (packet_t*)payload;

I think you want a union, something like this

union packet_t
{
  struct{
    int16_t temperature;                /**< Current Temperature */
    int16_t rampRate;                   /**< Current Ramp Rate */
  };
  uint8_t payload[4]; 
};

3 Likes

I guess your problem is rooted in the difference in endianness of the two platforms.
The STM32 is big endian.

2 Likes

It’s actually not that. I can control for endianness in the byte array. There is some padding of data going on I think that the compiler does.

You can control the padding via __attribute__((packed)) but using union should do that already.
But care has to be taken when using it :wink:

BTW, excluding potential reasons in the OP would help getting to the real reason quicker.

1 Like

Agreed, I did not consider endianness originally because these were the same hardware, but I get your point.

I appear to have luck with the following:

#pragma pack(push, 1)
typedef struct packet_t
{
	int16_t temperature;           	    /**< Current Temperature */
	int16_t rampRate;             	    /**< Current Ramp Rate */
}
#pragma pack(pop)

Thanks for your help.

1 Like