# ADXL345 – The Universal Accelerometer – Part 1

In my last two posts I had reported on the 6-axis sensor MPU6050 and the rather simple accelerometer MMA7361 with analog output. In this post I will cover the 3-axis, digital ADXL345 accelerometer. With its many features, it is for me the Swiss army knife among the accelerometers.

I found a lot of libraries for the ADXL345. But I felt they were all either not complete or written in such a way that you still have to go deep into the data sheet to use them. This motivated me to write a library myself, which – at least from my point of view – is convenient to use. To make it easy for you to use the more complex features such as FIFO, I have added 14 (!) example sketches to the library. Because of this large size, I had to divide the post in two parts (Link to part 2).

## Features / Technical specifications of the ADXL345

I had already described the operating principle of accelerometers in detail in my post about the MPU6050.

As with other sensors, I did not use the bare ADXL345 IC for simplicity, but a module. These usually have:

• Pull-up resistors for the I2C lines.
• A capacitor for voltage stabilization.
• A voltage converter so that you can operate the module with 3-5 volts.

The disadvantage of the module compared to the IC is that the power consumption is slightly higher. In the normal operating mode at measuring frequencies below 10 Hz, the consumption of the actual IC should be at 30 µA. I measured 100 µA at 5 V supply voltage, and at 3.3 V it was 50 µA.

### The most important data at a glance

• Measuring ranges: +/-2, +/-4, +/-8, +/-16 g.
• Resolution: 13 bits in the maximum measuring range (typically 4 mg / LSB)
• Adjustable to 10 bits for all measuring ranges.
• Communication via I2C or SPI.
• Single and double tap detection, i.e. detection of short accelerations, e.g. due to vibrations.
• FIFO (first in, first out) buffer memory for 32 readings.
• 8 interrupts, including free fall, single and double tap, activity and inactivity, FIFO overflow.
• Interrupts can be assigned to two output pins.
• Power supply: 3 – 5 volts (for the module).
• Power consumption (according to my measurements):
• from 23 µA (stand-by mode, 3.3 volts operating voltage)
• up to 220 µA (normal mode, 3200 Hz measuring frequency, 5 volts operating voltage).
• Energy-saving modes.

The best way to explain the features of the ADXL345 is to go through the example sketches.

### Wiring the ADXL345 with the Arduino

The wiring shown above was used for all example sketches.

• VCC/GND: 3 – 5 volts.
• 3V3 is a special feature of the Adafruit module: 3.3 volts are provided there.
• CS (Chip Select): when connected to GND, the module is no longer accessible via I2C; so connect it to VCC. Or to an I/O pin, then you can operate more than two ADXL345.
• SDA/SCL: I2C pins; pull-ups should be present on the module.
• SDO: Choice of I2C address. For 0x53 leave the pin unconnected or attach it to GND, for 0x1D connect it to VCC.
• INT1/INT2: Interrupt Pins; you can assign the interrupts to these pins. In addition, the interrupts can be set active-high or active-low.

## Operation with the library ADXL345_WE

You can download the library ADXL345_WE here from Github. For installation, unzip the ZIP file in the Arduino Library folder. Alternatively, you can install it via the Arduino IDE Library Manager.

As mentioned at the beginning, I tried to make the library user-friendly. Nevertheless, it has become very extensive. This is simply due to the many features of the ADXL345.

I will now guide you through the library using the example sketches. The sketches can be grouped according to the following themes:

• Basics functions
• Interrupts
• Activity, inactivity features
• Single and double tap detection
• FIFO functions

I have added lots of comments in all sketches and inserted parameter lists for the functions. But since this can also distract from the essentials, I only print the first sketch completely here. For the others, I took out many comments. If you want to try out the sketches or build on them, take the detailed versions you download with the library.

The post is quite long. Impatient people can also simply try the sample sketches and return here if something should be unclear.

## Basic functions of the ADXL345

The ADXL345 stores the acceleration values as raw data, which are provided in the data registers for the x, y and z axes. You get the latest values there. The maximum “age” of these depends on the measurement frequency (data rate). A high frequency leads to increased noise and power consumption. So don’t overdo it unnecessarily.

The raw values are converted by library functions into acceleration values in g. As a first approximation, the conversion factor in full resolution is 3.9 mg (= milli-g, not milligrams!) per LSB (= Least Significant Bit). In other words:

\text{acceleration in g} = \text{rawValue}\cdot3.9

For result data, such as raw data, g-values or angles, I have defined the structure (struct) xyzFloat. An xyzFloat consists of three float variables. The raw data “raw” includes for example the axis values raw.x, raw.y and raw.z.

Let’s get started. In the first example sketch, you will get to know the following functions:

• ADXL345_WE myAcc(ADXL345_I2CADDR) creates the object myAcc (stands for “my Accelerometer”).
• init() initializes the ADXL345 with some default values. The function returns true if the ADXL345 responds as expected.
• setDataRate(range) sets the measuring frequency. Select from the parameter list.
• setRange(range) sets the g-range. Select from the parameter list.
• setFullRange(true/false) sets the full resolution (10-13 bits) or the reduced resolution (10 bits). The full resolution is preset. I see no reason to change that.
• getDataRateAsString() returns the set measuring frequency as a string.
• getRangeAsString() returns the g-range as a string.
• setLowPower(true/false) sets the Low Power Mode. It provides power savings for certain data rates at the price of slightly higher noise.

As an alternative to the “get as string” functions, you can also use the following functions:

• getRange() / getDataRate()

But then you will only get numerical values returned, which you have to “translate”. Refer to the library file ADXL345_WE.h for the details of the corresponding enum definitions.

#include<Wire.h>

void setup(){
Wire.begin();
Serial.begin(9600);
Serial.println();
if(!myAcc.init()){
}

/* Choose the data rate         Hz
*/
Serial.print("Data rate: ");
Serial.print(myAcc.getDataRateAsString());

/* In full resolution raw values the size of the raw values depend
on the range: 2g = 10 bit; 4g = 11 bit; 8g = 12 bit; 16g =13 bit;
uncomment to change to 10 bit for all ranges.
*/
// myAcc.setFullRes(false);

/* Choose the measurement range
*/
Serial.print("  /  g-Range: ");
Serial.println(myAcc.getRangeAsString());
Serial.println();

/* Uncomment to enable Low Power Mode. It saves power but slightly
increases noise. LowPower only affetcs Data Rates 12.5 Hz to 400 Hz.
*/
// myAcc.setLowPower(true);
}

/* The LSB of the Data registers is 3.9 mg (milli-g, not milligramm).
This value is used calculating g from raw. However, this is an ideal
value which you might want to calibrate.
*/

void loop() {
xyzFloat raw = myAcc.getRawValues();
xyzFloat g = myAcc.getGValues();

Serial.print("Raw-x = ");
Serial.print(raw.x);
Serial.print("  |  Raw-y = ");
Serial.print(raw.y);
Serial.print("  |  Raw-z = ");
Serial.println(raw.z);

Serial.print("g-x   = ");
Serial.print(g.x);
Serial.print("  |  g-y   = ");
Serial.print(g.y);
Serial.print("  |  g-z   = ");
Serial.println(g.z);

Serial.println();

delay(1000);

}

For the following output, I tried to position the ADXL345 flat. The raw- and g-values for the x- and y-axes should therefore be zero. The g-value of the z-axis should be 1.

You can see small deviations for the x- and y-values and a not insignificant deviation for the z-value. The deviations vary from module to module. The accelerometer is a micromechanical component with certain tolerances.

You may have noticed that the first set of values differs more. It is advisable to discard these first values at program startup, when returning from stand-by mode and some other states. In this specific case, you could simply insert a small delay at the end of the setup.

This sketch is a guide to calibrating the ADXL345. Start the sketch and do not change the resolution. Rotate the ADXL345 slowly and try to find the maximum and minimum raw values for the axes. Support your arms because trembling distorts the values. It does not matter one or two units. Write down the values and then use them in the further sketches. How you do this, you will see in the example sketch 3.

The maximum and minimum values correspond to +1 g and -1 g, respectively (if you perform calibration on our home planet!). For the zero points, according to this method, the following applies:

\text{rawValue}_0 = \frac{\text{rawValue}_{\text{min}}+\text{rawValue}_{\text{max}}}{2}

Accordingly, an offset is calculated from it. For the slope:

\text{slope}\;[\text{gValue/rawValue}] = \frac{|\text{rawValue}_{\text{min}}|+\text{rawValue}_{\text{max}}}{2}
#include<Wire.h>

void setup(){
Wire.begin();
Serial.begin(9600);
Serial.println();
if(!myAcc.init()){
}
Serial.println("Calibration procedure:");
Serial.println(" - stay in full resolution");
Serial.println(" - supply voltage has influence (at least for the modules)");
Serial.println("        -> choose the same voltage you will use in your project!");
Serial.println(" - turn your ADXL slowly (!) to find the min and max raw x,y and z values");
Serial.println(" - deviations of one or two units don't matter much");
Serial.println(" - the calibration changes the slope of g vs raw and assumes zero is (min+max)/2 ");
Serial.println(" - write down the six values ");
Serial.println(" - you can try the calibration values in ADXL345_angles_tilt_orientation.ino example sketch");
Serial.println(" - ready to go? Then type in any key and send. ");
while(!Serial.available());
Serial.println(); Serial.println(); Serial.println();
}

void loop() {
xyzFloat raw = myAcc.getRawValues();
Serial.print("Raw-x = ");
Serial.print(raw.x);
Serial.print("  |  Raw-y = ");
Serial.print(raw.y);
Serial.print("  |  Raw-z = ");
Serial.println(raw.z);

delay(1000);

}

The values I determined were: xmin = -266.0, xmax = 285.0, ymin =   -268.0, ymax = 278.0, zmin = -291.0, zmax = 214.0.

Despite the calibration, you will see some deviations because the zero point is not necessarily really in the middle between the min and max values.

Others suggest attaching the ADXL345 to a cube- or square-shaped body to better align it for calibration. However, this assumes that the ADXL345 has been soldered truly flat to the module and that the module is mounted equally flat to the auxiliary body.

Here you can now apply the calibration by entering the values just obtained in the following function:

• setCorrFactors(xmin, xmax, ymin, ymax, zmin, zmax)

The function getRawValues() still provides the uncorrected raw data. getGValues(), on the other hand, uses the corrected values. This also applies to all other sketches.

In addition, the sketch calculates the angles between the axes and the horizontal from the g-values. Up to angles of 60° this works well for x and y. In the next section, you’ll learn about another function that covers higher angles. Here, however, the following simple function is used:

angle = \arcsin(\text{gValue})

I explained why this is so and why values close to 90° are particularly erroneous in my last post. You get the angles via the function getAngles(). Since the arcsin function is not defined for values greater than 1, I simply cut g-values greater than 1.

If you want to measure angles up to 60° quite accurately and want to start at 0°, you can eliminate the offset that still exists despite calibration. For this purpose, you position the ADXL345 as flat and steady as possible and execute the function measureAngleOffsets(). After that, you will receive the additionally corrected values via getCorrAngles().

The last function I want to introduce for this sketch is getOrientationAsString(). This determines which axis is most upwards. Depending on the orientation, it returns: x up, x down, y up, y down, z up or z down as a string.

#include<Wire.h>

void setup(){
Wire.begin();
Serial.begin(9600);
Serial.println();
if(!myAcc.init()){
}

myAcc.setCorrFactors(-266.0, 285.0, -268.0, 278.0, -291.0, 214.0);

/* In this next step the offset for angles is corrected to get quite precise corrected
*  angles for x and y up to ~60°. The additional offsetCorrection is only used for
*  corrected angles measurements.The procedure just ensures to start at 0°.
*/
delay(2000);
myAcc.measureAngleOffsets();
Serial.println("....done");

}

void loop() {
xyzFloat raw = myAcc.getRawValues();
xyzFloat g = myAcc.getGValues();
xyzFloat angle = myAcc.getAngles();
xyzFloat corrAngles = myAcc.getCorrAngles();

/* Still the uncorrected raw values!! */
Serial.print("Raw-x    = ");
Serial.print(raw.x);
Serial.print("  |  Raw-y    = ");
Serial.print(raw.y);
Serial.print("  |  Raw-z    = ");
Serial.println(raw.z);

/* g values use the corrected raws */
Serial.print("g-x     = ");
Serial.print(g.x);
Serial.print("  |  g-y     = ");
Serial.print(g.y);
Serial.print("  |  g-z     = ");
Serial.println(g.z);

/* Angles use the corrected raws. Angles are simply calculated by
angle = arcsin(g Value) */
Serial.print("Angle x  = ");
Serial.print(angle.x);
Serial.print("  |  Angle y  = ");
Serial.print(angle.y);
Serial.print("  |  Angle z  = ");
Serial.println(angle.z);

/* Corrected angles use corrected raws and an extra angle
offsets to ensure they start at 0°
*/
Serial.print("cAngle x = ");
Serial.print(corrAngles.x);
Serial.print("  |  cAngle y   = ");
Serial.print(corrAngles.y);
Serial.print("  |  cAngle z   = ");
Serial.println(corrAngles.z);

Serial.print("Orientation of the module: ");
Serial.println(myAcc.getOrientationAsString());

Serial.println();

delay(1000);

}

You can see that the corrected g-values for the z-axis now look much better. The angles have a certain deviation due to the remaining offset. The corrected angles (“cAngles”), on the other hand, fluctuate close to zero.

I have taken the method of angular calculation described here from other libraries, such as MPU6050 light or Arduino-ADXL345. The advantage of this method is that it includes several axes and thus compensates for errors. To delineate the method, I have adopted the nomenclature of others and referred to the tilt angle of the x-axis as “pitch” and that of the y-axis as “roll”.

pitch\; angle= \arctan \left(\frac{g_x}{\sqrt{g_x\cdot g_y +g_z^2}}\right)
roll\;angle = \arctan\left( \frac{g_y}{g_z} \right)

Again, of course, the angle determination is only valid in the static state. Additional accelerations distort the result.

Here is the example sketch, or more precisely its main components. As a reminder: the original sample sketches are provided with many more comments.

For comparison, the method from the previous sketch is also used.

#include<Wire.h>

void setup(){
Wire.begin();
Serial.begin(9600);
Serial.println("ADXL345 Sketch - Pitch and Roll vs. Corrected Angles");
Serial.println();
if(!myAcc.init()){
}

myAcc.setCorrFactors(-266.0, 285.0, -268.0, 278.0, -291.0, 214.0);

delay(2000);
myAcc.measureAngleOffsets();
Serial.println("....done");

}

void loop() {
xyzFloat corrAngles = myAcc.getCorrAngles();

Serial.print("Angle x = ");
Serial.print(corrAngles.x);
Serial.print("  |  Angle y = ");
Serial.print(corrAngles.y);
Serial.print("  |  Angle z = ");
Serial.println(corrAngles.z);

float pitch = myAcc.getPitch();
float roll  = myAcc.getRoll();

Serial.print("Pitch   = ");
Serial.print(pitch);
Serial.print("  |  Roll    = ");
Serial.println(roll);

Serial.println();

delay(1000);

}

For the above output, I slowly rotated the ADXL345 around the y-axis, i.e. the x-angle varies. With simple means (board and set square) I controlled the values (also for roll). For small to medium angles, the values called “Angle” are closer to reality, at large angles the pitch/roll method is better.

To save power, you can send the ADXL345 to sleep. The function to do this (and to wake it up) is:

• setSleep(true/false)

Sleep is interrupted by short waking phases. That cannot be stopped. But you can set the wake-up frequency to 1, 2, 4 or 8 Hz. To control the sleep mode together with the wake-up frequency, you can alternatively call the function with two parameters:

• setSleep(true/false, frequency)

If you don’t retrieve new data too often, you won’t notice any difference to the permanent wake mode. Only when the frequency of your readings is greater than the wake-up frequency will you see the effect.

In the example sketch, 10 readings are retrieved in wake and sleep mode. I have set the wake-up frequency to one second, and the readings are sampled at 300 millisecond intervals. Here is the (shortened) sketch:

#include<Wire.h>

void setup(){
Wire.begin();
Serial.begin(9600);
Serial.println();
if(!myAcc.init()){
}

}

void loop(){
Serial.println("Measure in Sleep Mode:");
doMeasurements();

myAcc.setSleep(false);
Serial.println("Measure in Normal Mode:");
doMeasurements();
}

void doMeasurements(){
for(int i=0; i<10; i++){
xyzFloat g = myAcc.getGValues();

Serial.print("g-x   = ");
Serial.print(g.x);
Serial.print("  |  g-y   = ");
Serial.print(g.y);
Serial.print("  |  g-z   = ");
Serial.println(g.z);

delay(300);
}
}

For the above output I moved the ADXL345 permanently. You can see that the values in normal mode are different for each query. In Sleep Mode, as expected, 3 to 4 values are identical.

Actually, it would be a good time to introduce the Auto Sleep mode next. But for the Auto Sleep mode we need interrupts and therefore we treat this topic first. I’ll return to Auto Sleep mode a little later.

## Interrupt Features of the ADXL345

### General information about the interrupt features

• Overrun: is triggered when unread data is overwritten, i.e. when the data rate is greater than the frequency of the data retrieval.
• Watermark: if the number of measured values in the FIFO buffer corresponds to the value defined in the FIFO control register (this will become clearer later).
• Free Fall: this is triggered when the acceleration values on all axes fall below a certain value for a certain time.
• Inactivity: when a limit of acceleration is exceeded on specified axes for a specified time.
• Activity: when a limit of acceleration is exceeded on specified axes.
• Single tap: an acceleration of a maximum duration that is above a certain limit.
• Double Tap: two peaks, both of which satisfy the single-tap conditions and also have a certain time interval between them.

You activate interrupts with the function setInterrupt(type, pin1/pin2). The first parameter is the interrupt type, with the second parameter you determine at which pin the interrupt is output. See the example sketches that use interrupts for a list of allowed parameters.

It is important to note that the interrupts for Overrun, Watermark and Data Ready are always enabled. So, you can’t disable them, just change the output pin. Default is INT1. You have to activate all other interrupts first. You deactivate them with deleteInterrupt(type).

In the interrupt register, in the case of an interrupt, the interrupt type is stored. Reading this register deletes the interrupt so that a new interrupt can be triggered. The function for this is readAndClearInterrupts(). It returns the interrupt type as a byte. How to “translate” this can be found in the library file ADXL345_WE.h. Alternatively, you check with checkInterrupt(source, type) for a specific type.

There is another general function, namely setInterruptPolarity(polarity). This sets whether the interrupt pins are active-low or active-high (default).

First, let’s take a look at the Free Fall interrupt. In the example sketch, it is activated with setInterrupt(ADXL345_FREEFALL, INT_PIN_2) and assigned to INT2.

setFreeFallThresholds(0.4, 100) sets the acceleration limit to 0.4 g and the minimum duration for which it must be lower to 100 milliseconds. Limits for parameters and recommended values can be found in the example sketch. It is best to play around with the parameters to get to know this feature better.

#include<Wire.h>
const int int2Pin = 2;
volatile bool freeFall = false;

void setup(){
Wire.begin();
Serial.begin(9600);
pinMode(int2Pin, INPUT);
Serial.println();
if(!myAcc.init()){
}

/* Insert your data from ADXL345_calibration.ino and uncomment for more precise results */
// myAcc.setCorrFactors(-266.0, 285.0, -268.0, 278.0, -291.0, 214.0);

/* The parameters of the setFreeFallThresholds function are:
- g threshold - do not choose a parameter which is too low. 0.3 - 0.6 g is fine.
- time threshold in ms, maximum is 1275. Recommended is 100 - 350;
If time threshold is too low, vibrations can be detected as free fall.
*/
myAcc.setFreeFallThresholds(0.4, 100);

/* You can choose the following interrupts:
Variable name:             Triggered, if:
ADXL345_WATERMARK    -   the number of samples in FIFO equals the number defined in FIFO_CTL
ADXL345_FREEFALL     -   acceleration values of all axes are below the threshold defined in THRESH_FF
ADXL345_INACTIVITY   -   acc. value of all included axes are < THRESH_INACT for period > TIME_INACT
ADXL345_ACTIVITY     -   acc. value of included axes are > THRESH_ACT
ADXL345_DOUBLE_TAP   -   double tap detected on one incl. axis and various defined conditions are met
ADXL345_SINGLE_TAP   -   single tap detected on one incl. axis and various defined conditions are met

Assign the interrupts to INT1 (INT_PIN_1) or INT2 (INT_PIN_2). Data ready, watermark and overrun are
always enabled. You can only change the assignment of these which is INT1 by default.

You can delete interrupts with deleteInterrupt(type);
*/

attachInterrupt(digitalPinToInterrupt(int2Pin), freeFallISR, RISING);
freeFall=false;
}

void loop() {
xyzFloat raw = myAcc.getRawValues();
xyzFloat g = myAcc.getGValues();

Serial.print("Raw-x = ");
Serial.print(raw.x);
Serial.print("  |  Raw-y = ");
Serial.print(raw.y);
Serial.print("  |  Raw-z = ");
Serial.println(raw.z);

Serial.print("g-x   = ");
Serial.print(g.x);
Serial.print("  |  g-y   = ");
Serial.print(g.y);
Serial.print("  |  g-z   = ");
Serial.println(g.z);

Serial.println();

if(freeFall==true){
Serial.println("Aaaaaaaaah!!!!! - I'm faaaaallllling!");
delay(1000);
freeFall = false;
/* by reading the interrupt register the interrupt is cleared */

/* if you expect also other interrupts you can check the type. For this comment the previous line,
and replace by the following four lines: */
//  Serial.println("FREEFALL confirmed");
//}
}

delay(500);
}

void freeFallISR(){
freeFall = true;
}

I still have one example sketch for this part 1, then it’s half-time. Here we use the Data Ready interrupt to control the data output. First, I set the measuring frequency with setDataRate(ADXL345_DATA_RATE_0_20) to a slow 0.2 Hz.

The Data Ready Interrupt is always active. But to not interfere with the other “always-enabled” interrupts, I assigned it to INT2 with setInterrupt(ADXL345_DATA_READY, INT_PIN_2).

The rest is simple. The Data Ready interrupt triggers an interrupt on Arduino Pin 2. This is the signal for reading the measured values. After that, the interrupt is deleted and the next interrupt is expected.

#include<Wire.h>
const int int2Pin = 2;  // interrupt pin

void setup(){
Wire.begin();
Serial.begin(9600);
pinMode(int2Pin, INPUT);
Serial.println();
if(!myAcc.init()){
}

/* Default Interrupt Pin Polarity is active high. Change if you like */

}

/* In the following loop there is only one interrupt type that can occur on INT2.
In cases where you expect more candidates, you can check as follows:
}
*/
void loop() {
// you see here is no delay to control the output rate
xyzFloat g = myAcc.getGValues();

Serial.print("g-x   = ");
Serial.print(g.x);
Serial.print("  |  g-y   = ");
Serial.print(g.y);
Serial.print("  |  g-z   = ");
Serial.println(g.z);

}
}

}

## Outlook

In part 2, we will come to the example sketches for

• Activity / Inactivity
• Auto Sleep Mode
• Single / Double Tap
• Various FIFO modes

## Acknowledgement

The utensils I attached to the ADXL345 module in the post image are from the image of a Swiss Army Knife by Clker-Free-Vector-Images on Pixabay.

I would like to thank Adafruit for publishing the Fritzing scheme of their ADXL345 module.

## 2 thoughts on “ADXL345 – The Universal Accelerometer – Part 1”

1. A good job and thanks for your sharing.

In my opinion, CS is already pulled up to the 3.3v from the LDO.
If the VCC is 3.3v, that’s ok. But if the VCC is 5V, it’s obviously not correct.
And it seems that SDXL345’s output is voltage sensitive, with different voltages,
it got different results.

Hope it will help.

1. Thanks for the feedback. When I apply 4.9 V to the board, I measure 4.72 V at (unconnected) CS. When I apply 3.3 V to the board I measure 3.8 V at CS (when SDA/SCL) are still at 5 V. When I remove SDA/SCL then CS is at 3.28 V. So I think at least VCC, CS and SDA/SCL level should be the same to avoid unnecessary currents on the board.

I can confirm the measured values are quite different if you apply 3.3 V vs. 5 V. Almost 10 % when I switched from 5 to 3.3 V. I will add a note to the blog and maybe to readme on GitHub that the supply voltage should be stable and constant. Good point.