gpvidal / adxl355-python

Python 3 library to connect ADXL355 PMDZ accelerometer on Raspberry Pi
15 stars 7 forks source link

Incorrect results #3

Open jaminturner opened 5 years ago

jaminturner commented 5 years ago

I think there is a problem with the two's complement implementation in this library. It is correct for positive numbers, but for negative numbers, it is incorrect. The math used to catch and convert negative numbers is:

if x_data & 0x80000 == 0x80000:
    x_data = ~x_data + 1

However, this just gives a negative version of x_data, it doesn't truly take it out of 2s complement form. For example, if the number received from the sensor is "1001 0110 0000 0010 1101", the correct decimal integer of that is -434131. However, the above code gives -614445, which is incorrect.

I think it could be corrected as follows:

if x_data & 0x80000 == 0x80000:
    x_data = x_data - 2**20

Am I wrong/confused on this?

AlekseyFedorovich commented 3 years ago

My setup (that works) for converting bits to g units is:

twentybits         = 1048576  # max int for 20 bits
scale_factor       = 1.95E-6
g_range = 2  # can be 2, 4, 8
# join 3 bytes and remove last four bits (data is 20 bits)
x = (buf[0] << 16 | buf[1] << 8 | buf[2]) >> 4
# twos complements
if x >= (twentybits / 2): 
    x = x - twentybits
# conversion in g units
x = x * g_range * scale_factor