Close Menu
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
Facebook X (Twitter) Instagram
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us
Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
How To Electronics
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
How To Electronics
Home » Measuring Acceleration with ADXL345 Accelerometer & Raspberry Pi
Raspberry Pi Raspberry Pi Projects

Measuring Acceleration with ADXL345 Accelerometer & Raspberry Pi

Mamtaz AlamBy Mamtaz AlamUpdated:August 19, 20236 Mins Read
Share Facebook Twitter LinkedIn Telegram Reddit WhatsApp
ADXL345 Accelerometer Raspberry Pi 4
Share
Facebook Twitter LinkedIn Pinterest Email Reddit Telegram WhatsApp

Overview

In this guide, we’ll learn how to connect the ADXL345 accelerometer to the Raspberry Pi and measure acceleration using Python. The Raspberry Pi is a small, powerful computer, and the ADXL345 is a sensor that can detect motion. When combined, they make a great pair for all sorts of fun projects like motion alarms or interactive games.

We’ll walk through the steps to connect the two devices, then show you how to write simple Python code to read data from the accelerometer. By the end, you’ll know how to use the Raspberry Pi 4 and ADXL345 together and be ready to start your own projects.



Components Required

We need the following components for this guide.

S.N.ComponentsQuantityPurchase Link
1Raspberry Pi1Amazon | AliExpress | SunFounder
2ADXL345 3-Axis Accelerometer1Amazon | AliExpress | SunFounder
3Breadboard1Amazon | AliExpress | SunFounder
4Connecting Wires5Amazon | AliExpress | SunFounder

ADXL345 Digital Acccelerometer

The ADXL345 is a 3-axis accelerometer developed by Analog Devices. This sensor is designed to accurately measure acceleration in the X, Y, and Z axes, making it suitable for various applications. It is particularly popular in the fields of robotics, gaming, virtual reality, wearables, and IoT devices, among others.

This accelerometer is capable of detecting both static acceleration, such as the force of gravity, and dynamic acceleration resulting from motion or vibrations. The ADXL345 has adjustable sensitivity, enabling it to cater to a range of applications with different acceleration requirements.

The ADXL345 communicates with microcontrollers using either I2C or SPI interfaces, which makes it compatible with a wide range of development platforms, such as Arduino, Raspberry Pi , and others. Thanks to its low power consumption and small form factor, the ADXL345 is ideal for battery-powered and space-constrained applications.


Specifications of ADXL345

The ADXL345 is a triple-axis accelerometer with the following key specifications:

  1. Axes: 3-axis (X, Y, Z)
  2. Sensitivity: User-selectable, ±2g, ±4g, ±8g, or ±16g
  3. Resolution: 10-bit or 13-bit, user-selectable
  4. Output data rate (ODR): 0.10 Hz to 3200 Hz
  5. Communication interfaces: I2C (up to 400 kHz) and SPI (4-wire and 3-wire, up to 5 MHz)
  6. Supply voltage range: 2.0 V to 3.6 V
  7. Current consumption: 23 µA to 130 µA, depending on output data rate and measurement mode
  8. Operating temperature range: -40°C to +85°C
  9. Package: 3 mm × 5 mm × 1 mm LGA




Pinout of ADXL345

The ADXL345 3-axis Digital Accelerometer Module has 8 pins.

ADXL345 Pinout

  1. GND: Ground connection for the module.
  2. VCC: Power supply input, typically 3.3V, but it can accept a voltage range from 2.0V to 3.6V
  3. CS (Chip Select): Used for SPI communication. When pulled low, it enables SPI communication; when pulled high, it switches to I2C communication.
  4. INT1 (Interrupt 1): This pin can be configured to output interrupt signals for certain events like activity/inactivity detection, single/double-tap detection, or free-fall detection.
  5. INT2 (Interrupt 2): This pin can be configured to output interrupt signals for certain events like activity/inactivity detection, single/double-tap detection, or free-fall detection.
  6. SDO (Serial Data Out): Master In Slave Out (MISO) line for SPI communication.
  7. SDA (Serial Data): Serial Data (I2C)/Serial Data Input (SPI 4-Wire)/Serial Data Input and Output (SPI 3-Wire).
  8. SCL (Serial Clock): Serial Communications Clock. SCL is the clock for I2C, and SCLK is the clock for SPI.

Interfacing ADXL345 Accelerometer with Raspberry Pi 4

To use the ADXL345 accelerometer with a Raspberry Pi 4 using Python, you’ll need to make the necessary hardware connections and then write a Python script to communicate with the sensor. Let’s start by understanding the connection procedure. Follow the steps below to connect the accelerometer to your Raspberry Pi 4.

Raspberry Pi 4 ADXL345 Accelerometer

Connect the ADXL345 to the Raspberry Pi Pico as follows:

  • VCC from ADXL345 to 3.3V on Raspberry Pi 4 (Pin 1)
  • GND from ADXL345 to GND on Raspberry Pi 4 (Pin 6)
  • SDA from ADXL345 to SDA (GPIO 2, Pin 3) on Raspberry Pi 4
  • SCL from ADXL345 to SCL (GPIO 3, Pin 5) on Raspberry Pi 4

ADXL345 Accelerometer with Raspberry Pi 4




Python Code for Measuring Acceleration & Tilt Angles

Now lets write a Python Code to interface ADXL345 with Raspberry 4 and measure Acceleration in X, Y, Z axis as well as Tilt Angles. We haven’t used any library for this code. You need to enable I2C Communication first to use this code.

This Python script is for interfacing with the ADXL345 accelerometer using the I2C communication protocol. The ADXL345 is a 3-axis accelerometer, and this script allows you to read acceleration data from it and calculate the tilt angles (pitch and roll) based on the acceleration values.

Copy the following code and paste it on your Thonny IDE Editor Window.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import smbus
import time
import math
 
# ADXL345 I2C Address
ADXL345_I2C_ADDR = 0x53
 
# ADXL345 Registers
POWER_CTL = 0x2D
DATA_FORMAT = 0x31
DATAX0 = 0x32
DATAX1 = 0x33
DATAY0 = 0x34
DATAY1 = 0x35
DATAZ0 = 0x36
DATAZ1 = 0x37
 
class ADXL345:
    G = 9.81  # Earth's gravity in m/s^2
 
    def __init__(self, bus_num=1):
        self.bus = smbus.SMBus(bus_num)
        # Set range to +/- 16g and FULL_RES bit
        self.bus.write_byte_data(ADXL345_I2C_ADDR, DATA_FORMAT, 0x0B)
        # Turn on the accelerometer
        self.bus.write_byte_data(ADXL345_I2C_ADDR, POWER_CTL, 0x08)
 
    def read_acceleration(self):
        # Read acceleration data
        bytes = self.bus.read_i2c_block_data(ADXL345_I2C_ADDR, DATAX0, 6)
        
        # Convert to 2's complement and then to m/s^2
        x = (bytes[1] << 8 | bytes[0])
        if x & (1 << 15):
            x = x - (1 << 16)
        x = (x / (2**15)) * 16 * self.G
        
        y = (bytes[3] << 8 | bytes[2])
        if y & (1 << 15):
            y = y - (1 << 16)
        y = (y / (2**15)) * 16 * self.G
        
        z = (bytes[5] << 8 | bytes[4])
        if z & (1 << 15):
            z = z - (1 << 16)
        z = (z / (2**15)) * 16 * self.G
        
        return (x, y, z)
 
    def get_tilt_angles(self):
        x, y, z = self.read_acceleration()
        
        pitch = math.degrees(math.atan2(y, math.sqrt(x**2 + z**2)))
        roll = math.degrees(math.atan2(-x, z))
 
        return pitch, roll
 
if __name__ == "__main__":
    accelerometer = ADXL345()
    while True:
        x, y, z = accelerometer.read_acceleration()
        pitch, roll = accelerometer.get_tilt_angles()
        print(f"Acceleration - X: {x:.3f} m/s^2, Y: {y:.3f} m/s^2, Z: {z:.3f} m/s^2")
        print(f"Pitch: {pitch:.2f}°, Roll: {roll:.2f}°")
        time.sleep(0.5)



Code Explanation

1
2
3
import smbus
import time
import math

These lines import three Python modules:

  • smbus: Provides functions to communicate with devices over I2C, a communication protocol.
  • time: Used for various time-related tasks. In this code, specifically for introducing delays.
  • math: Provides access to mathematical functions. Here, it’s used for trigonometry and angle conversion.

1
2
3
4
5
6
7
8
# ADXL345 I2C Address
ADXL345_I2C_ADDR = 0x53
 
# ADXL345 Registers
POWER_CTL = 0x2D
DATA_FORMAT = 0x31
DATAX0 = 0x32
...

This section defines constants:

  • ADXL345_I2C_ADDR: The I2C address of the ADXL345 accelerometer.
  • The next lines (like POWER_CTL, DATA_FORMAT, etc.) are register addresses within the ADXL345 device. These registers store configurations and data. For instance, POWER_CTL is the address for the power control register, which can be used to turn the accelerometer on/off.

1
2
class ADXL345:
    G = 9.81  # Earth's gravity in m/s^2

This line starts the definition of a class called ADXL345. Within this class, a constant G representing Earth’s gravitational force (9.81 m/s^2) is defined. This constant will be used later for acceleration calculations.

1
2
3
4
5
6
def __init__(self, bus_num=1):
    self.bus = smbus.SMBus(bus_num)
    # Set range to +/- 16g and FULL_RES bit
    self.bus.write_byte_data(ADXL345_I2C_ADDR, DATA_FORMAT, 0x0B)
    # Turn on the accelerometer
    self.bus.write_byte_data(ADXL345_I2C_ADDR, POWER_CTL, 0x08)

The __init__ function is a constructor, which gets automatically called when an object of the ADXL345 class is created. Here, it initializes the I2C bus for communication and sends commands to the accelerometer:

  • Setting its range to ±16g and setting the FULL_RES bit.
  • Turning on the accelerometer.

1
bytes = self.bus.read_i2c_block_data(ADXL345_I2C_ADDR, DATAX0, 6)

This line reads 6 bytes of data starting from the DATAX0 register. These bytes contain acceleration values for the X, Y, and Z axes.

1
2
3
4
x = (bytes[1] << 8 | bytes[0])
if x & (1 << 15):
    x = x - (1 << 16)
x = (x / (2**15)) * 16 * self.G

Here, the 2 bytes corresponding to the X-axis acceleration are combined to form a 16-bit number. The acceleration values are represented in 2’s complement, so there’s a check and conversion for negative values. Then, the value is scaled to get acceleration in m/s^2.

1
2
pitch = math.degrees(math.atan2(y, math.sqrt(x**2 + z**2)))
roll = math.degrees(math.atan2(-x, z))

This section calculates the pitch and roll angles from the acceleration values using trigonometric relationships.

1
2
3
4
5
6
7
8
if __name__ == "__main__":
    accelerometer = ADXL345()
    while True:
        x, y, z = accelerometer.read_acceleration()
        pitch, roll = accelerometer.get_tilt_angles()
        print(f"Acceleration - X: {x:.3f} m/s^2, Y: {y:.3f} m/s^2, Z: {z:.3f} m/s^2")
        print(f"Pitch: {pitch:.2f}°, Roll: {roll:.2f}°")
        time.sleep(0.5)

If the script is run as the main program, it enters this loop:

  • An ADXL345 object is created.
  • It then continually reads acceleration values and calculates tilt angles.
  • These values are printed out every 0.5 seconds.




Testing & Results

Save the Python Code with any name. Then hit the Run Button.

In the Thonny Shell, you will see the value of Acceleration in X, Y, Z Axis in unit of m/s^2. You will also see the values of Pitch and Roll in degrees.

To observe the change in the values, you can rotate or tilt the accelerometer.

In this reading, it is observed that the yaw value is not calculated.

To calculate yaw using only an accelerometer like ADXL345 isn’t directly feasible. The reason is that yaw is a rotation about the vertical (gravity) axis, and an accelerometer measures linear acceleration. Without a reference (like magnetic North from a magnetometer or compass), there’s no change in gravitational force on the sensors to determine the yaw angle.

Hence using the ADXL345 3-axis Accelerometer, you can calculate Acceleration in X, Y, Z axis and also measure the Pitch and Roll Values.

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Reddit Telegram WhatsApp
Previous ArticleHow to use ADS1115 16-Bit ADC Module with Raspberry Pi
Next Article Interfacing HMC5883L Magnetometer with Raspberry Pi

Related Posts

ADXL375 Accelerometer with Raspberry Pi Pico & MicroPython

ADXL375 Accelerometer with Raspberry Pi Pico & MicroPython

Updated:July 24, 2025
Interface BMI160 with Raspberry Pi Pico & MicroPython

Interface BMI160 with Raspberry Pi Pico & MicroPython

Updated:February 2, 20253K
Shift Register 74HC595 with Raspberry Pi Pico & MicroPython

Shift Register 74HC595 with Raspberry Pi Pico & MicroPython

Updated:February 2, 202513K
Interfacing XBee Module with Raspberry Pi Pico & MicroPython

Interfacing XBee Module with Raspberry Pi Pico & MicroPython

Updated:February 2, 20253K
Modbus RTU with Raspberry Pi Pico & Micropython

Modbus RTU with Raspberry Pi Pico & MicroPython

Updated:February 2, 20258K
Fever Detector with MLX90640 & OpenCV Raspberry Pi

Thermal Fever Detector with MLX90640 & OpenCV Raspberry Pi

Updated:February 2, 20256K
Add A Comment

CommentsCancel reply

Latest Posts
IoT Based PM & Air Quality Monitoring System using ESP32

IoT Based PM & Air Quality Monitoring System using ESP32

May 31, 2026
DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

May 10, 2026
IoT Activity Tracker with ESP32 & Accelerometer Gyroscope

IoT Activity Tracker with ESP32 & Accelerometer/Gyroscope

May 2, 2026
A Guide to Sourcing Obsolete ICs for Vintage Projects

Beyond AliExpress: A Guide to Sourcing Obsolete ICs for Vintage Projects

April 21, 2026

ESP32 IoT Vehicle Motion Analyzer with MPU6050 & LIS3MDL

April 27, 2026
Building a Smart Sensor Node with a BLE Microcontroller

Building a Smart Sensor Node with a BLE Microcontroller

February 26, 2026
High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

April 27, 2026
DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

February 1, 2026
Top Posts & Pages
  • How to use INA226 DC Current Sensor with Arduino
    How to use INA226 DC Current Sensor with Arduino
  • Buck Converter: Basics, Working, Design & Application
    Buck Converter: Basics, Working, Design & Application
  • How to use Modbus RTU with ESP32 to read Sensor Data
    How to use Modbus RTU with ESP32 to read Sensor Data
  • 12V DC to 220V AC Inverter Circuit & PCB
    12V DC to 220V AC Inverter Circuit & PCB
  • How to use INA219 DC Current Sensor Module with Arduino
    How to use INA219 DC Current Sensor Module with Arduino
  • Designing of MPPT Solar Charge Controller using Arduino
    Designing of MPPT Solar Charge Controller using Arduino
  • IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
    IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
  • IoT Based Electricity Energy Meter using ESP32 & Blynk
    IoT Based Electricity Energy Meter using ESP32 & Blynk
Categories
  • Arduino Projects (197)
  • Articles (60)
    • Learn Electronics (19)
    • Product Review (15)
    • Tech Articles (28)
  • Electronics Circuits (46)
    • 555 Timer Projects (21)
    • Op-Amp Circuits (7)
    • Power Electronics (13)
  • IoT Projects (204)
    • ESP32 MicroPython (7)
    • ESP32 Projects (81)
    • ESP32-CAM Projects (15)
    • ESP8266 Projects (76)
    • LoRa/LoRaWAN Projects (22)
  • Microcontrollers (38)
    • AMB82-Mini IoT AI Camera (4)
    • BLE Projects (18)
    • STM32 Projects (19)
  • Raspberry Pi (93)
    • Raspberry Pi Pico Projects (57)
    • Raspberry Pi Pico W Projects (12)
    • Raspberry Pi Projects (24)
Follow Us
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • YouTube
About Us

“‘How to Electronics’ is a vibrant community for electronics enthusiasts and professionals. We deliver latest insights in areas such as Embedded Systems, Power Electronics, AI, IoT, and Robotics. Our goal is to stimulate innovation and provide practical solutions for students, organizations, and industries. Join us to transform learning into a joyful journey of discovery and innovation.

Copyright © How To Electronics. All rights reserved.
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Looks like you're using an ad blocker. Please allow ads on our site. We rely on advertising to help fund our site.