Example Code for Micropython-3-axis Acceleration and Tilt Sensing

Last revision 2025/12/15

This article provides example code and instructions for setting up 3-axis acceleration and tilt sensing using Micropython and the ADXL345 accelerometer, including hardware and software preparation, wiring, and code execution.

Hardware Preparation

  • Triple Axis Accelerometer Breakout ADXL345 (SEN0032): 1, Purchase Link
  • Micropython-compatible board (e.g., ESP32): 1

Software Preparation

  • Development Tool: Thonny IDE or other Micropython IDE, Download Link
  • Library: ADXL345 Library (Need to be installed)

Wiring Diagram

This diagram is an IIC connection method suitable with Micropython-compatible board (e.g., ESP32) where SCL=22, SDA=21.

Connection Diagram

Other Preparation Work

Connect the module to the Micropython-compatible board according to the Wiring Diagram. Upload the ADXL345 library to the board. Open the IDE and select the correct port.

Sample Code

from machine import Pin,I2C
import ADXL345
import time

i2c = I2C(scl=Pin(22),sda=Pin(21), freq=10000)
adx = ADXL345.ADXL345(i2c)

while True:
    x=adx.xValue
    y=adx.yValue
    z=adx.zValue
    print('The acceleration info of x, y, z are:%d,%d,%d'%(x,y,z))
    roll,pitch = adx.RP_calculate(x,y,z)
    print('roll=',roll)
    print('pitch=',pitch)
    time.sleep_ms(50)

Result

Open the serial monitor of your Micropython IDE to see the 3-axis acceleration data and Roll-Pitch angle. See changes as you sway the Accelerometer.

Additional Information

By the way, we have collected some useful 3-axis data processing methods: How to Use a Three-Axis Accelerometer for Tilt Sensing.

Was this article helpful?

TOP