How to Interface ADXL345 Accelerometer with Arduino UNO

How to Interface ADXL345 Accelerometer with Arduino UNO Машинки

Adxl345 accelerometer arduino code

Here’s the Arduino code fo reading the ADXL345 accelerometer data.

#include<Wire.h> // Wire library - used for I2C communicationint ADXL345 = 0x53; float X_out, Y_out, Z_out; voidsetup(){ Serial.begin(9600); Wire.begin(); Wire.beginTransmission(ADXL345); Wire.write(0x2D); Wire.write(8); Wire.endTransmission(); delay(10); } voidloop(){ Wire.beginTransmission(ADXL345); Wire.write(0x32); Wire.endTransmission(false); Wire.requestFrom(ADXL345, 6, true); X_out = ( Wire.read()| Wire.read() << 8); X_out = X_out/256; Y_out = ( Wire.read()| Wire.read() << 8); Y_out = Y_out/256; Z_out = ( Wire.read()| Wire.read() << 8); Z_out = Z_out/256; Serial.print("Xa= "); Serial.print(X_out); Serial.print(" Ya= "); Serial.print(Y_out); Serial.print(" Za= "); Serial.println(Z_out); }

Code language:Arduino(arduino)

Description: So first we need to include the Wire.h library which is used for the I2C communication. If you want to learn more on how the I2C communication works and how to use it with Arduino you can check my other detailed tutorial for it.

Each device that uses the I2C communication has a unique I2C address, and this address can be found in the datasheet of the sensor (ADXL345 Datasheet). So, once we define the address and the variables for the three outputs, in the setup section, first, we need to initialize the wire library and then set the accelerometer in measuring mode.

So, using the beginTransmission() function we start the communication, then using the write() function we tell which register we want to access, and again using the write() function we set the D3 bit HIGH, by writing the number 8 in decimal which correspond to setting the bit D3 HIGH.

Wire.beginTransmission(ADXL345); Wire.write(0x2D); Wire.write(8); Wire.endTransmission();

Code language:Arduino(arduino)

In the loop section now we read the data from the sensor. The data for each axis is stored in two bytes or registers. We can see the addresses of these registers from the datasheet.

In order to read them all, we start with the first register, and the using the requestionFrom() function we ask to read the 6 registers. Then using the read() function, we read the data from each register, and because the outputs are twos complements we combine them appropriately to get the correct values.

Wire.beginTransmission(ADXL345); Wire.write(0x32); Wire.endTransmission(false); Wire.requestFrom(ADXL345, 6, true); X_out = ( Wire.read()| Wire.read() << 8); X_out = X_out/256; Y_out = ( Wire.read()| Wire.read() << 8); Y_out = Y_out/256; Z_out = ( Wire.read()| Wire.read() << 8); Z_out = Z_out/256;

Code language:Arduino(arduino)

The output values from the sensor actually depend on the selected sensitivity, which can vary from – 2g to -16g. The default sensitivity is -2g so that’s why we need to divide the output by 256 in order to get values from -1 to 1g. The 256 LSB/g means that we have 256 counts per g.

Смотрите про коптеры:  Взаимодействие nRF24L01 с Arduino: удаленное управление серводвигателем

Depending on the application we can select the appropriate sensitivity. In this case, for tracking orientation, -2g sensitivity is fine, but for application where we need to sense higher acceleration force from like sudden movements, shocks and so on, we can choose some of the other sensitivity ranges using the DATA_FORMAT register and its D1 and D0 bits.

Adxl345 accelerometer calibration

Nevertheless, once we read the data, we can simply print it on the serial monitor to check whether the values are as expected. In my case, the values I was getting were not exactly as they should be, especially the Z-axis which had a noticeable error of 0.1g.

To solve this issue, we need to calibrate the accelerometer using the 3 offset calibration registers, and here’s how we can do that. So, we need to position the sensor flat, and print the RAW values without dividing them by 256.

From here now we can notice the how much the outputs are off, in my case, the Z output was around 283. That’s difference of 27 in positive. Now we need to divide this value by 4, and that will give use the number that we need to write to the Z-axis offset register. If we upload the code now, the Z-axis output will be exactly 256, or 1g as it should be.

Wire.beginTransmission(ADXL345); Wire.write(0x1E); Wire.write(1); Wire.endTransmission(); delay(10); Wire.beginTransmission(ADXL345); Wire.write(0x1F); Wire.write(-2); Wire.endTransmission(); delay(10); Wire.beginTransmission(ADXL345); Wire.write(0x20); Wire.write(-7); Wire.endTransmission(); delay(10);

Code language:Arduino(arduino)

If needed we should calibrate the other axis using the same method. And just a quick note that this calibration is not permanently written to the registers. We need to do write these values to the registers at each power up of the sensor.

Смотрите про коптеры:  Самодельная байдарка из ПВХ-трубок и скотча | Пикабу

Once we are done with the calibration, we can now finally calculate the Roll and Pitch, or the rotation around the X-axis and the rotation around the Y axis in degrees, using these two formulas.

roll = atan(Y_out / sqrt(pow(X_out, 2) pow(Z_out, 2))) * 180 / PI; pitch = atan(-1 * X_out / sqrt(pow(Y_out, 2) pow(Z_out, 2))) * 180 / PI;

Code language:Arduino(arduino)

For more details how these formulas work, you can check this Freescale Semiconductor application note.

Arduino and adxl345 accelerometer orientation tracking – 3d visualization

Ok, let’s make the accelerometer 3D visualization example now.

So, we are using the same code, which sends the Roll and Pitch values through the serial port. Here’s the complete Arduino code:

#include<Wire.h> // Wire library - used for I2C communicationint ADXL345 = 0x53; float X_out, Y_out, Z_out; float roll,pitch,rollF,pitchF=; voidsetup(){ Serial.begin(9600); Wire.begin(); Wire.beginTransmission(ADXL345); Wire.write(0x2D); Wire.write(8); Wire.endTransmission(); delay(10); Wire.beginTransmission(ADXL345); Wire.write(0x1E); Wire.write(1); Wire.endTransmission(); delay(10); Wire.beginTransmission(ADXL345); Wire.write(0x1F); Wire.write(-2); Wire.endTransmission(); delay(10); Wire.beginTransmission(ADXL345); Wire.write(0x20); Wire.write(-9); Wire.endTransmission(); delay(10); } voidloop(){ Wire.beginTransmission(ADXL345); Wire.write(0x32); Wire.endTransmission(false); Wire.requestFrom(ADXL345, 6, true); X_out = ( Wire.read() | Wire.read() << 8); X_out = X_out / 256; Y_out = ( Wire.read() | Wire.read() << 8); Y_out = Y_out / 256; Z_out = ( Wire.read() | Wire.read() << 8); Z_out = Z_out / 256; roll = atan(Y_out / sqrt(pow(X_out, 2) pow(Z_out, 2))) * 180 / PI; pitch = atan(-1 * X_out / sqrt(pow(Y_out, 2) pow(Z_out, 2))) * 180 / PI; rollF = 0.94 * rollF 0.06 * roll; pitchF = 0.94 * pitchF 0.06 * pitch; Serial.print(rollF); Serial.print("/"); Serial.println(pitchF); }

Code language:Arduino(arduino)

Now in the Processing development environment we need to receive these values and use them to rotate the 3D object that we will create. Here’s the complete Processing code:

Circuit diagram

Circuit diagram for ADXL345 accelerometer interface with Arduino is given below:​

ADXL345 Arduino Connections:

Components required

  1. Arduino UNO
  2. ADXL345 Accelerometer
  3. Male-female wires
  4. Breadboard

Demonstration video

Here’s a video showing the output of the sketch:

Overview

First, I will explain how the sensor work and how to read the data from it, and then using the Processing development environment, we will make a 3D visualization of the accelerometer orientation.

Смотрите про коптеры:  АВОК 1.05-2006 Условные графические обозначения в проектах отопления, вентиляции, кондиционирования воздуха и теплохолодоснабжения.

Range value

The last function is the displayRange() function:

This prints out the current range of the ADXL345. If ±2g is selected, the accelerometer can now detect acceleration up to ±19.6 m/s2 (2 * 9.8). The default value is ±16g which is equivalent ±156.8 m/s2.

To change the range, use the setRange(range) function. The range can be any of the following:


For example, the following changes the range to ±2g:

Make sure that the above code is after the accel.begin() function inside setup().

Setting up arduino ide

First, we need the ADXL345 Arduino library. Open Arduino IDE (ver. 1.8.9) then go to Tools > Manage Libraries…

The Library Manager now appears. On the search field, type “Adafruit ADXL345”, press enter and the library should appear.

We also need to install the Unified Sensor library:

Types of accelerometersensors

There are many types of MEMS accelerometer sensors available in the market. They can be classified on the basis of precision, power consumption, and interfacing. All these sensors are portable and can be fitted in any kind of device like wearables. These sensors measure acceleration in 3-axis (x,y,z).

Some widely used Sensors are:

  1. ADXL335
  2. ADXL345
  3. ADXL356

These accelerometer sensors are very popular and apart from these three, there are many other accelerometer sensors like ADXL354, ADXL355, ADXL372, etc.

Let’s see the difference between these sensors.

Comparison: ADXL335 vs ADXL345 vs ADXL356 

Among the above three, ADXL345 is easy to interface because of its digital nature. But its programming is difficult as it works on the SPI/I2C protocol. ADXL345 can measure static and dynamic accelerations and suitable for mobile applications. Also, these sensors are laboratory calibrated and don’t require any further calibrations.

Here we will use the Adafruit library for the ADXL345 sensor to interface it with Arduino Uno.

Using the adxl345 with arduino

After installation of the libraries, go to Files > Examples > Adafruit ADXL345 > sensortest. The example sketch is as shown:


To use this sketch, follow this wiring diagram:

For other boards, make sure that this connection is followed:

Arduino PinADLX345 Pin
3.3VVDD
GNDGND
A4SDA/SDI
A5SCL/SCLK

Upload the sketch to your Arduino and open Serial Monitor. The acceleration values is now visible:

The library converts the output to m/s2 instead of g units.

Оцените статью
Радиокоптер.ру
Добавить комментарий

Adblock
detector