Working on a simple ADXL345 driver (i.e. two's complement)

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
Lornioiz
Posts: 36
Joined: Wed Aug 03, 2016 11:39 am
Location: Florence, Italy

Working on a simple ADXL345 driver (i.e. two's complement)

Post by Lornioiz » Sat Oct 29, 2016 4:25 pm

Hello everyone,

As a beginner in the mcu world and after getting my feet wet with my first i2c device driver (a rtc mp3231) I got to work with an ADXL345 accelerometer.
I saw here and there some post about it, but my problem is not specific to the device itself (or the ESP8266 for that matter).
I'm able to extract legit values as long as the acceleration is positive, but I cannot make it with a negative one.
In the datasheet is made clear that the output data is two's complement... and here is my problem. How can correctly convert a negative value to decimal?
I printed the value of an axis and while transitioning from a positive value to a negative this is what I got:
Positive: 0b11
Negative: 0b1111111111111110
I (think to) understand theoretically how this work, but how do I convert it to a decimal value? I thought that the complement (~) was the way to go, but seems that it's not the case or, more probably, I don't know how to use it.

Thanks!
Last edited by Lornioiz on Sun Oct 30, 2016 9:10 am, edited 1 time in total.

Turbinenreiter
Posts: 288
Joined: Sun May 04, 2014 8:54 am

Re: Working on a simple ADXL345 driver (i.e. two's complement)

Post by Turbinenreiter » Sat Oct 29, 2016 4:38 pm

Code: Select all

# from stackoverflow J.F. Sebastian
def _twos_comp(val, bits=8):
    """compute the 2's complement of int val with bits"""
    if (val & (1 << (bits - 1))) != 0: # if sign bit is set
        val = val - (1 << bits)          # compute negative value
    return val                               # return positive value as is
I stole this from Stackoverflow once, not sure if there isn't a better way to do it.

Lysenko
Posts: 62
Joined: Wed Aug 17, 2016 1:21 pm

Re: Working on a simple ADXL345 driver (i.e. two's complement)

Post by Lysenko » Sat Oct 29, 2016 4:56 pm

Just convert the number to decimal and subtract 2 to the power bit_count. e.g:

int('1111111111111110',2) - (2**16) = -3

There might be some function or other in the stdlib for this, but it's easier to remember the basic math than library functions for one liners.

Lornioiz
Posts: 36
Joined: Wed Aug 03, 2016 11:39 am
Location: Florence, Italy

Re: Working on a simple ADXL345 driver (i.e. two's complement)

Post by Lornioiz » Sun Oct 30, 2016 9:33 am

Thanks to both!!

Post Reply