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.

TMAG5273: 2's Complement conversion

Part Number: TMAG5273

Had a question about the 2's complement conversion and the calculation described in equation 10 of the TMAG5273 datasheet and the implementation. I have a hard time verifying from the data itself whether the implementation is correct, but what I have is

//Holds bytes read over I2C
  uint8_t temp[2]; // should be uint8_t or int8_t?

// 16 bit result
  int16_t temp_mt;

//read out the data
  temp[0] = I2C.readByte(); //MSB
  temp[1] = I2C.readByte(); //LSB

// combine to make the 2's complement
  temp_mt = ((temp[0] << 8) | temp[1]);

// equation 10
const uint8_t range = 40; // assuming for now range is 40
const float divisor = 32768; // 2^16 / 2
float B = temp_mt * range / divisor; // not sure if this is correct

I have a hard time verifying:
- whether the temp array should be uint or int.
- whether the 2's complement combination is correct
- how to implement the negative sign only on bit 15 of the data

  • Hi Morten,

    Thank you for posting to the Sensors forum!

    As the temp array is being used to store the MSB and LSB is 8-bits, I would recommend storing it as an unsigned value to prevent inaccurate 2's complement conversion for these two values. 2's complement for the result registers should be considered on a 16-bit basis, so if you wanted to store the temp array as a signed value, I would recommend doing so as an int16_t. 

    Your 2's complement combination looks correct, just keep in mind it may be necessary to cast the temp[0]/temp[1] variables to signed 16-bit int value.

    float B = temp_mt * range / divisor; // not sure if this is correct

    The equation above looks correct to me.

    Additionally, we do provide code examples, linked below, that you may find useful as you are developing your firmware for your project.

    Best,

    ~Alicia

  • So in conclusion it should be good, also aren't temp[0] and temp[1] implicitly upgraded/casted from the bit shift and then addition?

    Furthermore, using an int8_t temp[2] array would be incorrect then right?

  • Hi Morten,

    also aren't temp[0] and temp[1] implicitly upgraded/casted from the bit shift and then addition

    Technically, yes. However, I have had some experience in the past where with certain compilers/processors an explicit cast was needed as it wouldn't cast correctly without one. So it may be the case that an explicit cast is not needed with your system.

    Furthermore, using an int8_t temp[2] array would be incorrect then right?

    Yes.

    Best,

    ~Alicia