Pages

Saturday 14 June 2014

Why 2’s compliment?

posted 15 Jul 2011 03:29 by David Taylor

Why would chip manufacturers decide to provide output data in 2’s compliment? I’ve been having loads of issues with reading data from the ADXL345 and the ITF-3200.
At least the ITG-3200 has 16bit resolution so getting a 2’s complement value from it is as simple as using BitConverter.ToInt16().
The ADXL345 however provides only a maximum of 13bit resolution. Sending 13Bit data into BitConverter simply returns a positive number between 0 and 8191 instead of the correct 2’s compliment value of +-4095
Luckily I found StackExchange’s Electronics forum and some people in the know could set me straight. See 13-bit 2's Complement on .Net MF.
Why would they even do this? Surely it would be simpler to just output a UInt value between 0 and the Max Resolution. Surely it’s simpler to just apply an offset than to go through all the bit shifting. To make it worse it seems that different processors seem to deal with BitConverting differently. From example code that I’ve seen, the Arduino boards handle the Byte to Decimal conversion much easier than the .Net boards.
If the ADXL345 simply output data between 0 and 8191 I could just take that data and subtract 4095 and have my value.
In any event, I think I have made some progress again. I suspect I might also have my Most Significant Byte and my Least Significant Byte reversed when using BitConverter on either my Gyro's or the Accelerometers which is why I am getting very unstable data from my IMU for very small physical changes. Anyway, I hope to test this theory and also implement my new 2’s complement understanding tonight.
Beware of .Net Garbage Collector Debug Messages
Another issue I have resolved is with the .Net Garbage collector debug message. To date I have been running my code on my FEZmini board in debug mode. When you run the code via Visual Studio the output window shows the garbage collector output every couple of seconds.
I assumed that this processing would be suppressed if a debugger is not attached to the board (I.E. running it without Visual Studio). Alas, this is not the case. My IMU (while seemingly approaching some level of stability) would twitch every couple of seconds. This seems to be due to the Garbage collector debug code executing from time to time. 2 options here: Either disable the debug GC messages and/or run in Release mode.
Debug.EnableGCMessages(false);
The twitch is now gone, so hopefully once I have the 2’s compliment issue sorted out, everything should be working [better].

No comments:

Post a Comment