I have a 16 bit variable data
, ie:
volatile uint16_t data;
I need to populate this value based on the contents of two 8 bit registers on an external sensor. These are accessed over I2C/TWI.
My TWI routine is async*, and has the signature:
bool twi_read_register(uint8_t sla, uint8_t reg, uint8_t *data, void (*callback)(void));
This reads the value of reg
on sla
into *data
, then calls callback()
.
If I knew the uint16_t
was arranged in memory as, say, MSB LSB
, then I could do:
twi_read_register(SLA, REG_MSB, (uint8_t *)&data, NULL);
twi_read_register(SLA, REG_LSB, (uint8_t *)&data + 1, NULL);
However, I don't like baking endian dependence into my code. Is there a way to achieve this in an endian-independent way?
(side note: my actual workaround at the moment involves using a struct, ie:
typedef struct {
uint8_t msb;
uint8_t lsb;
} SensorReading;
but I'm curious if I could do it with a simple uint16_t
)
EDIT
(* by async I mean split-phase, ie *data
will be set at some point in the future, at which point the callee will be notifed via the callback
function if requested)