0

I'm obtaining data from an accelerometer and trying to log it to a file. However, I'm a little perplexed by the output I'm getting. I'm only logging one sample to ensure the data is written correctly.

I've created the following struct to group data:

struct AccData
{
    int16_t x;
    int16_t y;
    int16_t z;
    unsigned int time;
};

The above should amount to 10 bytes in total.

I'm writing to stdout and getting the following data from the sensor:

I (15866) Accelerometer: Measurement: X25 Y252 Z48 Time: 10

The data that's stored to the sd card looks like so:

1900FC00300000000A00

Splitting those up gives us:

1900 FC00 3000 00000A00

This is where I'm starting to get confused. The first 3 sectors only make sense if I reverse the order of the bytes such that:

X Y Z Time
1900 -> 0019 = 25 1900 -> 0019 = 25 3000 -> 0030 = 48 00000A00 -> 000A0000 = 655.360

First, this may be due to my limited C knowledge, but is it normal for the output to be swapped like above?

Additionally, I can't get the time to make sense at all. It almost looks like only 3 bytes are being allocated for the unsigned integer, which would give the correct result if you didn't reverse it.

Jazerix
  • 4,729
  • 10
  • 39
  • 71
  • 2
    Have you verified with the `sizeof` operator that the structure is the size you expect? I would actually expect there to be some *padding* before the last member (to make it well-aligned for four-byte integers). Also see [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) – Some programmer dude Nov 26 '22 at 21:09
  • 4
    Also read about [*endianness*](https://en.wikipedia.org/wiki/Endianness), which seems to be the big problem for you. – Some programmer dude Nov 26 '22 at 21:10
  • Thanks, @Someprogrammerdude! The size of the struct is 12 :D I will take a deeper look at endianness :D – Jazerix Nov 26 '22 at 22:32

1 Answers1

1

Like @Someprogrammerdude pointed out in the comments, this had to do with endianess and the fact that my struct was being padded, resulting in the struct being 12 bits instead of 10.

Accounting for the padding the data now looks like so: 1900FC00 30000000 0A000000,

Reading above with little endian made it make sense.

Jazerix
  • 4,729
  • 10
  • 39
  • 71