1

I need to pass a 16-bit long address (for an external EEPROM) to a function (twi_writeTo) in a buffer. I am currently doing this

byte buffer[2];
buffer[0] = (byte)(eeaddress >> 8);
buffer[1] = (byte)(eeaddress & 0xFF);

where eeaddress is an unsigned int with the address.

I then do

int8_t ret = twi_writeTo(eeprom_i2c_addr, buffer, 2, 1);

Before I tried

int8_t ret = twi_writeTo(eeprom_i2c_addr, (uint8_t*)&eeaddress, 2, 1);

but that returns garbage. Probably the byte order is swapped. Is that the case? And if so, is there a better way than copying the two bytes to a buffer?

5
  • If you think endianness is the problem, just change buffer[0] to buffer[1] and vice versa, and check if that fixes your problem.
    – Gerben
    May 10, 2015 at 11:30
  • The use of (uint8_t*)&eeaddress and buffer is mutually exclusive, so I don't understand your comment. May 10, 2015 at 12:49
  • 1
    Swap the buffer[] bytes over and see if that creates the same garbage that (uint8_t*)&eeaddress does. If so, then yes it is an endian problem.
    – Majenko
    May 10, 2015 at 13:05
  • What do you mean exactly by it returns garbage? Please give some examples with hex numbers.
    – rslite
    May 10, 2015 at 23:06
  • Garbage as in it reads "arbitrary" addresses so that the result doesn't make sense. I checked and indeed the first approach swaps the bytes w.r.t. the second. So, yes, it's the byte order. May 11, 2015 at 16:16

1 Answer 1

2

If it's the byte order that causes a problem that's likely compiler specific and I don't think one can change it. Even if it were possible, changing the global endianness might break libraries that depend on it, so you likely can't escape using a function to swap the variable.

If you know you only need one value at a time you could write something like the following code, with a global buffer (untested but in principle should work (and I know global variables are evil, but should work for an Arduino project)):

byte buf[2];

byte* reverse(int val) {
    buf[0] = (byte)(val >> 8);
    but[1] = (byte)val;
    return buf;
}

So you could use it like:

int8_t ret = twi_writeTo(eeprom_i2c_addr, reverse(eeaddress), 2, 1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.