In java I have the code

public void readAccel() 
  int l, h;

  l = i2c.read(0x28);
  h = i2c.read(0x29);

  int x = ((h) << 8) | (l);

in java. The accelerometer I have connected is working and communicating over i2c, the problem being that the two's complement number that is generated only seems to work in one direction; when I turn he device to one side the values scale from 0-256, but past zero the value jumps to 4096-3840. What Am I doing wrong?

  • \$\begingroup\$ Is it a 12-bit device? Are you sign-extending the high bits properly? \$\endgroup\$ – Brian Drummond Mar 8 '14 at 22:23

Are you sure it jumps to 4096 and not 4095?

In any case, the problem is that you're not properly converting the 12-bit result to the native Java int type. Try this:

int x = ((h) << 8) | (l);
if (x > 2047) {
    x = x - 4096;

Any values that have the high bit (bit 11) set will be properly converted to negative integers. 4095 becomes -1, 4094 becomes -2, etc.

  • \$\begingroup\$ Interestingly enough my accelerometer now says about 65,536 (2^16) when turned to the right. I scaled the numbers accordingly and it works great. \$\endgroup\$ – AlexG Mar 8 '14 at 23:02

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.