## ADXL345 range setting on micropython

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
davidbogatec
Posts: 5
Joined: Tue Feb 04, 2020 3:23 pm

### ADXL345 range setting on micropython

I want to set the 16g range of the accelerometer. The default range is 2G. Where I need to specify this in the below code?

Code: Select all

``````from machine import Pin,I2C
import math
import time

device = const(0x53)
buff = bytearray(6)
self.i2c = i2c
b = bytearray(1)
b[0] = 0
b[0] = 16
b[0] = 8

@property
def xValue(self):
x = (int(buff[1]) << 8) | buff[0]
if x > 32767:
x -= 65536
return x

@property
def yValue(self):
y = (int(buff[3]) << 8) | buff[2]
if y > 32767:
y -= 65536
return y

@property
def zValue(self):
z = (int(buff[5]) << 8) | buff[4]
if z > 32767:
z -= 65536
return z

def RP_calculate(self,x,y,z):
roll = math.atan2(y , z) * 57.3
pitch = math.atan2((- x) , math.sqrt(y * y + z * z)) * 57.3
return roll,pitch
``````

cgglzpy
Posts: 32
Joined: Thu Jul 18, 2019 4:20 pm

### Re: ADXL345 range setting on micropython

Hi,

You can see this in the data sheet: ADXL345
[Page 26-27] Register 0x31—DATA_FORMAT (Read/Write) --> Range Bits D1-D0

So you need to write to register 0x31 the byte 0x03 which is 0b00000011 (see Table 21) setting bits D1-D0 to 1.

In code should be something like:

Code: Select all

``````reg_DATA_FORMAT = const(0x31)
``````
and inside 'def __init__' method add:

Code: Select all

``````b[0] = 3
``````
I can't test this but I think this is the way.

davidbogatec
Posts: 5
Joined: Tue Feb 04, 2020 3:23 pm

### Re: ADXL345 range setting on micropython

i've insert the suggested lines in the code but nothing happens.
Where is the error?

from machine import Pin,I2C
import math
import time

device = const(0x53)
buff = bytearray(6)
reg_DATA_FORMAT = const(0x31)

self.i2c = i2c
b = bytearray(1)
b[0] = 0
b[0] = 16
b[0] = 8
b[0] = 3
b)

@property
def xValue(self):
x = (int(buff[1]) << 8) | buff[0]
if x > 32767:
x -= 65536
return x

@property
def yValue(self):
y = (int(buff[3]) << 8) | buff[2]
if y > 32767:
y -= 65536
return y

@property
def zValue(self):
z = (int(buff[5]) << 8) | buff[4]
if z > 32767:
z -= 65536
return z

def RP_calculate(self,x,y,z):
roll = math.atan2(y , z) * 57.3
pitch = math.atan2((- x) , math.sqrt(y * y + z * z)) * 57.3
return roll,pitch

cgglzpy
Posts: 32
Joined: Thu Jul 18, 2019 4:20 pm

### Re: ADXL345 range setting on micropython

i've insert the suggested lines in the code but nothing happens.
Hmm, maybe because of this
From the data sheet Page 26:
All data, except that for the ±16 g range, must be clipped to avoid rollover
So I think you have to comment or erase the "if x > 32767" lines.
Something like this:

Code: Select all

``````def xValue(self):