ADXL345 Arduino Accelerometer: Wiring, Tilt, Tap and Free Fall
ADXL345 Arduino guide: I2C and SPI wiring, ±2g to ±16g ranges, tilt angle, tap and free-fall interrupts, MPU6050 comparison and 3200 Hz vibration logging.
The ADXL345 Arduino combination is one of the most popular ways to measure acceleration on three axes: the sensor tells you how far a board is tilted, how hard it is shaken or whether it is falling, in g, and sends the result as a ready-made number over I2C or SPI. Unlike analog accelerometers, you don't have to deal with ADC readings, offset maths or noisy wires, and the chip has built-in circuits that detect taps, double taps and free fall and raise an interrupt. That's why it is a first choice for fall alarms, tilt-controlled game controllers, earthquake detectors and vibration loggers.
In this article you'll learn how the ADXL345 works, its ±2g to ±16g ranges and resolution, and how to wire the GY-291 module over I2C and SPI. You'll read it on an Arduino Uno without a library, calculate the tilt angle from raw values and set up the tap and free-fall interrupts. Then you'll compare the ADXL345 with the MPU6050, log vibration at 3200 samples per second over SPI with an ESP32 and read the same sensor on a Raspberry Pi Pico with MicroPython.
What is the ADXL345 and how does it work?
The ADXL345 is a MEMS (micro-electro-mechanical system) accelerometer made by Analog Devices. Inside the chip there is a tiny silicon mass hanging on springs, surrounded by capacitor plates. When the board accelerates, the mass moves closer to or further from the plates, the capacitance changes, and the chip measures that change for each axis and converts it into a digital number. The key point: an accelerometer also sees gravity as acceleration. An ADXL345 lying flat on a table reads about +1 g (9.81 m/s²) on the Z axis. That is exactly why we can calculate tilt: when the sensor is still, the share of gravity on each of the three axes tells you how far the board is leaning.
| Feature | ADXL345 |
|---|---|
| Axes | 3 axes (X, Y, Z), acceleration only |
| Range | ±2 g, ±4 g, ±8 g, ±16 g (selectable) |
| Resolution | 3.9 mg/LSB in full resolution (up to 13 bits), 10 bits in fixed mode |
| Interface | I2C (100/400 kHz) and SPI (3- or 4-wire, up to 5 MHz) |
| I2C address | 0x53 (SDO to GND) or 0x1D (SDO to VCC) |
| Output data rate (ODR) | 0.1 Hz to 3200 Hz |
| Supply | Chip 2.0–3.6 V; GY-291 module 3.3–5 V with its regulator |
| Current | 23–140 µA when measuring depending on data rate, 0.1 µA in standby |
| Built-in interrupts | Data ready, single and double tap, activity, inactivity, free fall, FIFO |
| FIFO | 32-sample buffer |
| Shock survival | 10,000 g |
Measurement range and resolution: from ±2g to ±16g
The range is set by the last two bits of the DATA_FORMAT (0x31) register. ±2 g is the most sensitive and suits slow, small changes such as tilt; ±16 g measures hard impacts, drops and sports movements without clipping. When the FULL_RES bit in the same register is on, the ADXL345 keeps 3.9 mg/LSB in every range and only the number of bits grows as the range widens. With that bit off the output is always 10 bits, and at ±16 g one step becomes 31.2 mg. In practice, leaving FULL_RES on and choosing ±16 g is the easiest option for most projects: you get a sensitive reading that doesn't overflow, and your conversion factor stays the same in every range.
| Range | DATA_FORMAT (FULL_RES on) | Full resolution | In 10-bit mode | Typical use |
|---|---|---|---|---|
| ±2 g | 0x08 | 10 bits, 256 LSB/g | 256 LSB/g | Tilt, spirit level, slow motion |
| ±4 g | 0x09 | 11 bits, 256 LSB/g | 128 LSB/g | Hand gestures, walking, game controller |
| ±8 g | 0x0A | 12 bits, 256 LSB/g | 64 LSB/g | Machine vibration, vehicle shaking |
| ±16 g | 0x0B | 13 bits, 256 LSB/g | 32 LSB/g | Impacts, drops, jumps, sports |
ADXL345 wiring: I2C and SPI
Most ADXL345 boards on the market are the small GY-291 module. It carries a 3.3 V regulator and pull-up resistors for the I2C lines. In I2C mode two data wires are enough and you can share the bus with other sensors; for this the CS pin must be high (3.3 V). On most modules that resistor is already on the board; if not, tie CS to 3.3 V. The SDO pin sets the address: 0x53 when it is at GND, 0x1D when it is at VCC. SPI mode needs four wires (CS, SDO, SDA, SCL) but runs at up to 5 MHz; at 1600 and 3200 Hz data rates you should use SPI so you don't miss samples. You'll find how the bus works in detail in the I2C guide and in the SPI article.
| ADXL345 pin | Arduino Uno (I2C) | ESP32 (I2C) | ESP32 (SPI) | Raspberry Pi Pico (I2C) |
|---|---|---|---|---|
| VCC | 5V (module with regulator) or 3.3V | 3V3 | 3V3 | 3V3(OUT), pin 36 |
| GND | GND | GND | GND | GND |
| SDA / SDI | A4 | GPIO 21 | GPIO 23 (MOSI) | GP4, pin 6 |
| SCL / SCLK | A5 | GPIO 22 | GPIO 18 (SCK) | GP5, pin 7 |
| SDO | GND (address 0x53) | GND | GPIO 19 (MISO) | GND |
| CS | 3.3V (or pulled up on the module) | 3.3V | GPIO 5 | 3.3V |
| INT1 | D2 | GPIO 4 | GPIO 4 | GP15 |
Step by step: first reading with an Arduino Uno
- Wire the GY-291 module as in the table: VCC to 5V, GND to GND, SDA to A4, SCL to A5, SDO to GND.
- You don't need to install a library; the code only uses Arduino's own Wire library.
- Upload the code and open the Serial Monitor at 115200 baud.
- With the module lying flat, check that X and Y are close to 0 and Z is close to 1.00 g.
- Tilt the board slowly to one side; watch the Roll and Pitch angles change and the three axes move as separate lines in the Serial Plotter.
1// ADXL345 + Arduino Uno: kütüphanesiz I2C okuma ve eğim açısı
2// ADXL345 + Arduino Uno: library-free I2C reading and tilt angle
3#include <Wire.h>
4
5const uint8_t ADXL_ADDR = 0x53; // SDO GND'de; SDO VCC'deyse 0x1D / SDO to GND; 0x1D if SDO is at VCC
6const uint8_t REG_DEVID = 0x00;
7const uint8_t REG_BW_RATE = 0x2C;
8const uint8_t REG_POWER_CTL = 0x2D;
9const uint8_t REG_DATA_FORMAT = 0x31;
10const uint8_t REG_DATAX0 = 0x32;
11
12const float G_PER_LSB = 0.0039; // tam çözünürlükte 3,9 mg/LSB / 3.9 mg/LSB in full resolution
13
14void writeReg(uint8_t reg, uint8_t val) {
15 Wire.beginTransmission(ADXL_ADDR);
16 Wire.write(reg);
17 Wire.write(val);
18 Wire.endTransmission();
19}
20
21uint8_t readReg(uint8_t reg) {
22 Wire.beginTransmission(ADXL_ADDR);
23 Wire.write(reg);
24 Wire.endTransmission(false); // tekrar başlat / repeated start
25 Wire.requestFrom(ADXL_ADDR, (uint8_t)1);
26 return Wire.available() ? Wire.read() : 0;
27}
28
29void readAxes(int16_t &x, int16_t &y, int16_t &z) {
30 Wire.beginTransmission(ADXL_ADDR);
31 Wire.write(REG_DATAX0);
32 Wire.endTransmission(false);
33 Wire.requestFrom(ADXL_ADDR, (uint8_t)6);
34 uint8_t b[6] = {0, 0, 0, 0, 0, 0};
35 for (uint8_t i = 0; i < 6 && Wire.available(); i++) b[i] = Wire.read();
36 x = (int16_t)((b[1] << 8) | b[0]); // önce düşük bayt gelir / low byte comes first
37 y = (int16_t)((b[3] << 8) | b[2]);
38 z = (int16_t)((b[5] << 8) | b[4]);
39}
40
41void setup() {
42 Serial.begin(115200);
43 Wire.begin();
44 Wire.setClock(400000); // 400 kHz hızlı mod / 400 kHz fast mode
45
46 uint8_t id = readReg(REG_DEVID);
47 if (id != 0xE5) { // ADXL345 kimliği her zaman 0xE5 / ADXL345 ID is always 0xE5
48 Serial.print(F("ADXL345 bulunamadi / not found, DEVID=0x"));
49 Serial.println(id, HEX);
50 while (true) {}
51 }
52 writeReg(REG_DATA_FORMAT, 0x0B); // FULL_RES + ±16 g
53 writeReg(REG_BW_RATE, 0x0A); // 100 Hz veri hızı / 100 Hz output data rate
54 writeReg(REG_POWER_CTL, 0x08); // ölçüm modunu aç / enable measure mode
55}
56
57void loop() {
58 int16_t rx, ry, rz;
59 readAxes(rx, ry, rz);
60
61 float ax = rx * G_PER_LSB; // g cinsinden / in g
62 float ay = ry * G_PER_LSB;
63 float az = rz * G_PER_LSB;
64
65 // Eğim açıları (yalnız durağanken doğru) / tilt angles (valid only when still)
66 float roll = atan2(ay, az) * 180.0 / PI;
67 float pitch = atan2(-ax, sqrt(ay * ay + az * az)) * 180.0 / PI;
68
69 Serial.print(F("X:")); Serial.print(ax, 3);
70 Serial.print(F(" Y:")); Serial.print(ay, 3);
71 Serial.print(F(" Z:")); Serial.print(az, 3);
72 Serial.print(F(" Roll:")); Serial.print(roll, 1);
73 Serial.print(F(" Pitch:")); Serial.println(pitch, 1);
74 delay(100);
75}The code first reads the DEVID (0x00) register; on every ADXL345 this value is 0xE5. If you get any other number, the address, the wiring or the CS connection is wrong. It then writes 0x0B to DATA_FORMAT to select FULL_RES and ±16 g, sets the data rate to 100 Hz with BW_RATE and, most importantly, turns on the Measure bit (0x08) in the POWER_CTL register. Until that bit is set, the sensor stays in standby and you read nothing but zeros. The data sits in six bytes starting at 0x32, low byte first; two bytes are combined into a signed 16-bit number and multiplied by 0.0039 to get g.
Calculating the tilt angle
When the sensor is still, the only acceleration it measures is gravity, and that 1 g vector is shared between the axes as the board tilts. So you can find two angles with trigonometry: Roll = atan2(Y, Z) and Pitch = atan2(−X, √(Y² + Z²)). Because atan2 takes the sign into account, it returns the correct angle between −180° and +180°. There are two limits you should know. First, an accelerometer can't see rotation around the gravity axis, i.e. compass heading (yaw); for that you need a compass module or a gyroscope. Second, while the board is moving, the measured acceleration is added to gravity and the angle is temporarily wrong. For fast-moving robots, sensors such as the MPU6050 that fuse the angle with a gyroscope are more stable; for slow tilt measurements the ADXL345 on its own is enough.
| Board position | X (g) | Y (g) | Z (g) | Roll | Pitch |
|---|---|---|---|---|---|
| Flat on the table, components up | 0.00 | 0.00 | +1.00 | 0° | 0° |
| Tilted 45° around the X axis | 0.00 | +0.71 | +0.71 | 45° | 0° |
| Upright with the Y axis pointing up | 0.00 | +1.00 | 0.00 | 90° | 0° |
| Upright with the X axis pointing up | +1.00 | 0.00 | 0.00 | 0° | −90° |
| Upside down | 0.00 | 0.00 | −1.00 | 180° | 0° |
Tap and free-fall interrupts
What really sets the ADXL345 apart is that it detects motion events by itself and sends an interrupt to a pin. The Arduino doesn't have to read data all the time and decide; it only checks what happened when INT1 goes high. For a single tap, acceleration must exceed the THRESH_TAP threshold and drop back within the DUR time, so the chip knows it was a short knock and not continuous shaking. For a double tap, it waits for Latent after the first tap and then looks for a second one within the Window time. For free fall, all three axes drop below the THRESH_FF threshold, because a falling object is weightless and the sensor reads about 0 g; if this lasts for TIME_FF, an interrupt fires. Interrupts are enabled with INT_ENABLE, routed to INT1 or INT2 with INT_MAP and cleared by reading INT_SOURCE.
| Register | Address | Unit | Value in the code | Purpose |
|---|---|---|---|---|
| THRESH_TAP | 0x1D | 62.5 mg/LSB | 0x30 = 3 g | Acceleration needed to count as a tap |
| DUR | 0x21 | 625 µs/LSB | 0x10 = 10 ms | The knock must be shorter than this |
| Latent | 0x22 | 1.25 ms/LSB | 0x50 = 100 ms | Wait after the first tap |
| Window | 0x23 | 1.25 ms/LSB | 0xC8 = 250 ms | Window in which the second tap is searched |
| THRESH_FF | 0x28 | 62.5 mg/LSB | 0x07 = 437.5 mg | Free-fall threshold (300–600 mg recommended) |
| TIME_FF | 0x29 | 5 ms/LSB | 0x14 = 100 ms | Minimum fall time (100–350 ms recommended) |
| INT_ENABLE | 0x2E | Bits | 0x64 | Single tap (0x40) + double tap (0x20) + free fall (0x04) |
1// ADXL345 + Arduino Uno: tek dokunma, çift dokunma ve serbest düşme kesmeleri (INT1 -> D2)
2// ADXL345 + Arduino Uno: single tap, double tap and free-fall interrupts (INT1 -> D2)
3#include <Wire.h>
4
5const uint8_t ADXL_ADDR = 0x53;
6const uint8_t INT_PIN = 2; // Uno'da harici kesme 0 / external interrupt 0 on the Uno
7
8volatile bool intFlag = false;
9
10void writeReg(uint8_t reg, uint8_t val) {
11 Wire.beginTransmission(ADXL_ADDR);
12 Wire.write(reg);
13 Wire.write(val);
14 Wire.endTransmission();
15}
16
17uint8_t readReg(uint8_t reg) {
18 Wire.beginTransmission(ADXL_ADDR);
19 Wire.write(reg);
20 Wire.endTransmission(false);
21 Wire.requestFrom(ADXL_ADDR, (uint8_t)1);
22 return Wire.available() ? Wire.read() : 0;
23}
24
25void onAdxlInt() {
26 intFlag = true; // kesmede I2C kullanma, yalnız bayrak / no I2C inside the ISR, only a flag
27}
28
29void setup() {
30 Serial.begin(115200);
31 Wire.begin();
32 pinMode(INT_PIN, INPUT);
33
34 writeReg(0x2D, 0x00); // ayar sırasında bekleme modu / standby while configuring
35 writeReg(0x31, 0x0B); // FULL_RES + ±16 g, INT aktif HIGH / INT active HIGH
36 writeReg(0x2C, 0x0A); // 100 Hz
37 writeReg(0x1D, 0x30); // THRESH_TAP: 48 x 62,5 mg = 3 g
38 writeReg(0x21, 0x10); // DUR: 16 x 625 us = 10 ms
39 writeReg(0x22, 0x50); // Latent: 80 x 1,25 ms = 100 ms
40 writeReg(0x23, 0xC8); // Window: 200 x 1,25 ms = 250 ms
41 writeReg(0x2A, 0x07); // TAP_AXES: X, Y ve Z / X, Y and Z
42 writeReg(0x28, 0x07); // THRESH_FF: 7 x 62,5 mg = 437,5 mg
43 writeReg(0x29, 0x14); // TIME_FF: 20 x 5 ms = 100 ms (yaklaşık 5 cm düşüş / about a 5 cm drop)
44 writeReg(0x2F, 0x00); // INT_MAP: hepsi INT1'e / all to INT1
45 writeReg(0x2E, 0x64); // INT_ENABLE: SINGLE_TAP + DOUBLE_TAP + FREE_FALL
46 readReg(0x30); // bekleyen kesmeleri temizle / clear pending interrupts
47 writeReg(0x2D, 0x08); // ölçüm modu / measure mode
48
49 attachInterrupt(digitalPinToInterrupt(INT_PIN), onAdxlInt, RISING);
50 Serial.println(F("Hazir: masaya vur ya da sensoru birak / Ready: tap the table or drop the sensor"));
51}
52
53void loop() {
54 if (intFlag || digitalRead(INT_PIN) == HIGH) {
55 intFlag = false;
56 uint8_t tapStatus = readReg(0x2B); // ACT_TAP_STATUS: hangi eksen / which axis
57 uint8_t src = readReg(0x30); // INT_SOURCE okumak kesmeyi temizler / reading INT_SOURCE clears it
58
59 if (src & 0x04) Serial.println(F("SERBEST DUSME / FREE FALL"));
60 if (src & 0x20) Serial.println(F("CIFT DOKUNMA / DOUBLE TAP"));
61 else if (src & 0x40) {
62 Serial.print(F("TEK DOKUNMA / SINGLE TAP, eksen / axis: "));
63 if (tapStatus & 0x04) Serial.print('X');
64 if (tapStatus & 0x02) Serial.print('Y');
65 if (tapStatus & 0x01) Serial.print('Z');
66 Serial.println();
67 }
68 }
69}The interrupt function only raises a flag; the I2C reading happens in loop, because using Wire inside an interrupt can lock up the Uno. You'll find the interrupt logic explained in the Arduino interrupt article. As long as INT_SOURCE isn't read, INT1 stays high and no new events come in, which is why the loop also reads the register if the pin is still high. With double tap enabled, the first knock may also be flagged as a single tap; in that case the code prints only the double tap. Simple physics helps when choosing the free-fall time: the fall height is h = ½ × g × t², so 100 ms corresponds to a drop of about 5 cm and 300 ms to about 44 cm. To catch a device falling off a table, 100–150 ms is a good starting point.
ADXL345 vs MPU6050
| Feature | ADXL345 | MPU6050 |
|---|---|---|
| Sensors | 3-axis accelerometer | 3-axis accelerometer + 3-axis gyroscope + temperature |
| Acceleration range | ±2 / ±4 / ±8 / ±16 g | ±2 / ±4 / ±8 / ±16 g |
| Resolution | 10–13 bits (3.9 mg/LSB) | 16 bits |
| Interface | I2C and SPI | I2C only (400 kHz) |
| I2C address | 0x53 / 0x1D | 0x68 / 0x69 |
| Maximum data rate | 3200 Hz | 1 kHz for acceleration |
| Built-in interrupts | Single/double tap, free fall, activity, inactivity | Data ready, motion detection |
| FIFO | 32 samples | 1024 bytes |
| Current | 23–140 µA | About 3.9 mA (with the gyroscope on) |
| Best at | Low power, impacts and vibration, battery devices | Stable angle on fast-moving robots |
In short, if you only need tilt, impacts, drops or vibration, the ADXL345 draws less current, samples much faster over SPI and shortens your code with its built-in tap interrupts. If you need to measure rotation speed or get a reliable angle while moving, pick a sensor with a gyroscope; see the MPU6050 guide for details. If you just want to know whether something vibrates or not, the very cheap SW-420 vibration sensor, which gives no numeric value, may be enough.
Vibration logging with an ESP32 over SPI (3200 Hz)
Monitoring the vibration of a motor, a fan or a washing machine needs a high sampling rate. The ADXL345 delivers up to 3200 Hz, but I2C at 400 kHz can't keep up with that, so we use SPI on the ESP32. The sensor collects samples in its 32-entry FIFO buffer in stream mode, and the ESP32 reads from FIFO_STATUS how many samples are waiting and pulls them all at once. For each sample the code calculates the magnitude of the total acceleration and every second it outputs two values: the RMS vibration with the mean (that is, gravity) removed, and the peak value, the largest deviation from 1 g, both in mg.
1// ESP32 + ADXL345 (SPI, 3200 Hz): FIFO ile titreşim kaydı, her saniye RMS ve tepe değeri CSV olarak
2// ESP32 + ADXL345 (SPI, 3200 Hz): vibration logging with the FIFO, RMS and peak as CSV every second
3#include <SPI.h>
4
5const int PIN_CS = 5; // VSPI: SCK 18, MISO 19, MOSI 23, CS 5
6const float G_PER_LSB = 0.0039;
7SPISettings adxlSpi(5000000, MSBFIRST, SPI_MODE3); // en fazla 5 MHz, mod 3 / max 5 MHz, mode 3
8
9void writeReg(uint8_t reg, uint8_t val) {
10 SPI.beginTransaction(adxlSpi);
11 digitalWrite(PIN_CS, LOW);
12 SPI.transfer(reg & 0x3F); // yazma: bit7 = 0 / write: bit7 = 0
13 SPI.transfer(val);
14 digitalWrite(PIN_CS, HIGH);
15 SPI.endTransaction();
16}
17
18uint8_t readReg(uint8_t reg) {
19 SPI.beginTransaction(adxlSpi);
20 digitalWrite(PIN_CS, LOW);
21 SPI.transfer(0x80 | reg); // okuma: bit7 = 1 / read: bit7 = 1
22 uint8_t v = SPI.transfer(0x00);
23 digitalWrite(PIN_CS, HIGH);
24 SPI.endTransaction();
25 return v;
26}
27
28void readSample(int16_t &x, int16_t &y, int16_t &z) {
29 uint8_t b[6];
30 SPI.beginTransaction(adxlSpi);
31 digitalWrite(PIN_CS, LOW);
32 SPI.transfer(0x80 | 0x40 | 0x32); // çok baytlı okuma, DATAX0'dan / multi-byte read from DATAX0
33 for (int i = 0; i < 6; i++) b[i] = SPI.transfer(0x00);
34 digitalWrite(PIN_CS, HIGH);
35 SPI.endTransaction();
36 x = (int16_t)((b[1] << 8) | b[0]);
37 y = (int16_t)((b[3] << 8) | b[2]);
38 z = (int16_t)((b[5] << 8) | b[4]);
39}
40
41double sum = 0, sumSq = 0;
42float peak = 0;
43uint32_t count = 0, windowStart = 0;
44
45void setup() {
46 Serial.begin(115200);
47 pinMode(PIN_CS, OUTPUT);
48 digitalWrite(PIN_CS, HIGH);
49 SPI.begin(); // varsayılan VSPI pinleri / default VSPI pins
50
51 if (readReg(0x00) != 0xE5) {
52 Serial.println("ADXL345 yok, kabloyu kontrol et / ADXL345 missing, check wiring");
53 while (true) delay(1000);
54 }
55 writeReg(0x2D, 0x00); // bekleme / standby
56 writeReg(0x31, 0x0B); // 4 telli SPI, FULL_RES, ±16 g / 4-wire SPI, FULL_RES, ±16 g
57 writeReg(0x2C, 0x0F); // 3200 Hz
58 writeReg(0x38, 0x80); // FIFO akış modu / FIFO stream mode
59 writeReg(0x2D, 0x08); // ölçüm / measure
60 Serial.println("ms,ornek_samples,rms_mg,tepe_peak_mg");
61 windowStart = millis();
62}
63
64void loop() {
65 uint8_t entries = readReg(0x39) & 0x3F; // FIFO'daki örnek sayısı / samples waiting in the FIFO
66 for (uint8_t i = 0; i < entries; i++) {
67 int16_t rx, ry, rz;
68 readSample(rx, ry, rz);
69 delayMicroseconds(5); // FIFO okumaları arasında en az 5 us / at least 5 us between FIFO reads
70 float ax = rx * G_PER_LSB, ay = ry * G_PER_LSB, az = rz * G_PER_LSB;
71 float mag = sqrtf(ax * ax + ay * ay + az * az); // toplam ivme, durağanken 1 g / total acceleration, 1 g at rest
72 sum += mag;
73 sumSq += (double)mag * mag;
74 float dev = fabsf(mag - 1.0f);
75 if (dev > peak) peak = dev;
76 count++;
77 }
78
79 if (millis() - windowStart >= 1000 && count > 0) {
80 double mean = sum / count;
81 double var = sumSq / count - mean * mean; // yerçekimi (ortalama) çıkarılır / gravity (the mean) is removed
82 float rmsMg = (var > 0 ? sqrt(var) : 0) * 1000.0;
83 Serial.printf("%lu,%lu,%.1f,%.1f\n", (unsigned long)millis(), (unsigned long)count, rmsMg, peak * 1000.0f);
84 sum = sumSq = 0;
85 peak = 0;
86 count = 0;
87 windowStart = millis();
88 }
89}Because the output is comma-separated (CSV), you can copy it from the Serial Monitor into a spreadsheet or watch it live in the Serial Plotter. On a calm table the RMS is a few mg; on top of a running desk fan you'll see tens, and on an unevenly loaded washing machine hundreds of mg. With 3200 Hz sampling the highest vibration frequency you can measure is half of that, 1600 Hz. For long-term logging you can write the same lines to an SD card module or send a phone notification when a threshold is crossed. The code works the same on the Arduino-ESP32 2.0.x and 3.x cores, because it only uses the standard SPI class.
ADXL345 with the Raspberry Pi Pico (MicroPython)
On the Pico you don't need an extra library; the readfrom_mem and writeto_mem functions of MicroPython's machine.I2C class read and write the registers directly. Connect the sensor to I2C0, i.e. pins GP4 (SDA) and GP5 (SCL), and power VCC from the 3V3(OUT) pin. With struct.unpack, six bytes turn into three signed numbers in a single line. The code below prints the tilt angles and detects a single tap by polling the INT_SOURCE register; you can also wire INT1 to GP15 and turn it into an interrupt with Pin.irq.
1# Raspberry Pi Pico + ADXL345 (MicroPython, I2C0: GP4 SDA, GP5 SCL): eğim açısı ve dokunma
2# Raspberry Pi Pico + ADXL345 (MicroPython, I2C0: GP4 SDA, GP5 SCL): tilt angle and tap
3from machine import I2C, Pin
4import math
5import struct
6import time
7
8ADDR = 0x53
9i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
10
11def wr(reg, val):
12 i2c.writeto_mem(ADDR, reg, bytes([val]))
13
14def rd(reg, n=1):
15 return i2c.readfrom_mem(ADDR, reg, n)
16
17if rd(0x00)[0] != 0xE5:
18 raise OSError("ADXL345 bulunamadi / not found: " + str(i2c.scan()))
19
20wr(0x2D, 0x00) # bekleme / standby
21wr(0x31, 0x0B) # FULL_RES + ±16 g
22wr(0x2C, 0x0A) # 100 Hz
23wr(0x1D, 0x30) # dokunma eşiği 3 g / tap threshold 3 g
24wr(0x21, 0x10) # dokunma süresi 10 ms / tap duration 10 ms
25wr(0x2A, 0x07) # X, Y, Z eksenleri / X, Y, Z axes
26wr(0x2E, 0x40) # yalnız SINGLE_TAP / SINGLE_TAP only
27rd(0x30) # bekleyen kesmeleri temizle / clear pending interrupts
28wr(0x2D, 0x08) # ölçüm modu / measure mode
29
30while True:
31 x, y, z = struct.unpack("<hhh", rd(0x32, 6)) # küçük uçlu 3 x int16 / little-endian 3 x int16
32 ax, ay, az = x * 0.0039, y * 0.0039, z * 0.0039
33 roll = math.degrees(math.atan2(ay, az))
34 pitch = math.degrees(math.atan2(-ax, math.sqrt(ay * ay + az * az)))
35 if rd(0x30)[0] & 0x40: # INT_SOURCE: SINGLE_TAP
36 print("DOKUNMA / TAP")
37 print("roll {:6.1f} pitch {:6.1f} z {:5.2f} g".format(roll, pitch, az))
38 time.sleep_ms(100)ADXL345 project ideas
- Idea: A fall alarm for an elderly person or a cyclist; if a hard impact follows right after free fall, a buzzer sounds.
- Idea: A digital spirit level; show roll and pitch in big digits on an OLED display with a moving bubble.
- Idea: A simple earthquake alarm that logs table shaking; when the RMS value crosses a threshold, light and sound go off.
- Idea: A washing machine done alert; when the ESP32 sees the vibration stop, it sends a message through a Telegram bot.
- Idea: A tilt-controlled camera mount or arm; pass the pitch angle to a servo motor.
- Idea: A secret lock that opens when you knock twice on a box, or a lamp that turns on when you tap the table; the double-tap interrupt is made for this.
Common problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| DEVID reads 0x00 or 0xFF instead of 0xE5 | Wrong address (0x1D), SDA and SCL swapped, CS low | Find the address with an I2C scanner, check the wiring and that CS is at 3.3 V |
| All axes always 0 | Measure bit in POWER_CTL not set | Write 0x08 to register 0x2D |
| Z reads about 0.12 g when flat | FULL_RES off with ±16 g, wrong factor | Write 0x0B to DATA_FORMAT or use 31.2 mg/LSB in 10-bit mode |
| Interrupt fires once and never again | INT_SOURCE not read, INT1 stays high | Read register 0x30 after every event |
| Taps never detected or detected all the time | Threshold or duration not suitable, sensor loose | Try THRESH_TAP between 2 and 5 g, fix the module with a screw or double-sided tape |
| Angle keeps jittering | Measurement noise and vibration | Average, lower the data rate, apply a filter |
| Samples skip or repeat at high rates | I2C can't keep up with 1600–3200 Hz | Use SPI and read the FIFO in stream mode |
The ADXL345 is a small chip, but with the right register settings it becomes a versatile sensor that measures tilt, impacts, drops and vibration; all you have to do is choose the range, data rate and interrupt thresholds for your project. If you want to try sensor projects step by step with a circuit diagram and ready code, take a look at the motion and measurement projects in the BlueGrays app.
Frequently asked questions
What is the difference between the ADXL345 and the MPU6050?
The ADXL345 is a 3-axis accelerometer only, while the MPU6050 also contains a 3-axis gyroscope. The ADXL345 stands out with SPI support, data rates up to 3200 Hz, built-in tap and free-fall interrupts and very low current. If you need a stable angle while moving or rotation speed, the MPU6050 is the better fit.
What is the I2C address of the ADXL345?
The address is 0x53 when the SDO pin is tied to GND and 0x1D when it is tied to VCC. Most GY-291 modules come with 0x53. If you're not sure, run an I2C scanner sketch and check that the DEVID register returns 0xE5.
Can the ADXL345 run on 5V?
The ADXL345 chip runs on 3.6 V at most and is damaged if you apply 5 V directly. Modules with a 3.3 V regulator, such as the GY-291, accept 5 V on VCC, but their data lines are still at 3.3 V level. The Arduino Uno usually reads that level; for permanent builds a logic level converter is recommended.
Can the ADXL345 measure angles?
Yes, when the sensor is still, roll and pitch are calculated with atan2 from how gravity is distributed over the axes. However, rotation around the gravity axis (yaw) can't be measured, and during fast movement the angle is temporarily wrong. For yaw you need a compass module, and for a stable angle while moving a gyroscope.
How does ADXL345 free-fall detection work?
A falling object is weightless, so the sensor reads about 0 g on all three axes. If all three axes stay below the THRESH_FF threshold for the TIME_FF duration, the ADXL345 generates a FREE_FALL interrupt. A 437 mg threshold and 100 ms duration catch drops longer than about 5 cm.
Can the ADXL345 measure vibration?
Yes, because the ADXL345 can take up to 3200 samples per second, it captures vibration frequencies up to about 1600 Hz. To avoid missing samples at that rate, use SPI instead of I2C and read the 32-sample FIFO in stream mode. By calculating RMS and peak values from the readings you can monitor machine vibration.
Projects to build after reading this
See all projects
Using LCD Screen with I2C
Give your Arduino its own screen and make it write its first message. The two-line LCD screen hooks up with just a few wires; a greeting appears on the top line, then a second message on the bottom…

ESP32 I2C LCD Display (16x2)
In this project we connect a 16x2 character LCD to the ESP32 over I2C and display text. With I2C, just 2 data pins (SDA and SCL) control the screen, instead of the 6+ pins a classic parallel connection wastes. The code prints a fixed message on the first line and a counter that goes up every second on the second. At startup an I2C scanner also prints the display's address to the Serial Monitor (usually 0x27 or 0x3F).

ESP32 HTTPClient + Weather API (with SSD1306 OLED Display)
In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. Unlike the I2C LCD version, it uses an SSD1306 OLED (128×64) display, with large text and vector icons for a richer look. Seven weather icons (sunny, rainy, snowy and more) are drawn on the fly, with no bitmap files.

Motion Detector with Motion Sensor
A simple guard that tells you when someone walks into the room. The motion sensor picks up the warmth given off by the human body, and the Arduino keeps the LED on as long as there is movement and…

ESP32 Motion Alarm System (PIR + Buzzer + LED + Telegram)
A smart security alarm: when the PIR sensor detects motion, it sounds the buzzer, lights the LED and sends the owner an instant Telegram notification. A 30-second cooldown limits how often the alarm repeats; it does not filter out the PIR sensor's false detections. Use it at home, in a garage, a storeroom or a study.

ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)
Build a timed temperature and humidity logger with the ESP32! A DHT22 sensor reads temperature and humidity once a minute, and each reading is saved to a microSD card in CSV format with a real-time stamp from the DS1307 RTC module. The OLED display shows the latest temperature, humidity, timestamp and total number of records live, in large text.

Servo Control with Joystick
Steer two motors with a joystick, just like turning a security camera. Push the stick left or right and the bottom servo motor slowly turns, push it up or down and the top servo tilts up and down…
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

