HOW to Detect Acceleration with ESP32
Overview
In this kit, there is a DIY electronic building block ADXL345 acceleration sensor module, which uses the ADXL345BCCZ chip. The chip is a small, thin, low-power 3-axis accelerometer with a high resolution (13 bits) and a measurement range of ±16g that can measure both dynamic acceleration due to motion or impact as well as stationary acceleration such as gravitational acceleration, making the device usable as a tilt sensor.
Working Principle
The ADXL345 is a complete 3-axis acceleration measurement system with a selection of measurement ranges of ±2 g, ±4 g, ±8 g or ±16 g. Its digital output data is in 16-bit binary complement format and can be accessed through an SPI (3-wire or 4-wire) or I2C digital interface.
The sensor can measure static acceleration due to gravity in tilt detection applications, as well as dynamic acceleration due to motion or impact. Its high resolution (3.9mg/LSB) enables measurement of tilt Angle changes of less than 1.0°.
Components Required
|
|
|
|
|
---|---|---|---|---|
ESP32 Board*1 |
ESP32 Expansion Board*1 |
Keyestudio ADXL345 |
4P Dupont Wire*1 |
Micro USB Cable*1 |
Connection Diagram
Add Library
Open“Thonny”, click“This computer”→“D:”→“2. ESP32_code_MicroPython”→“lesson 40. ADXL345”.
Select“ADXL345.py”,right-click and select“Upload to /”,waiting for the “ADXL345.py” to be uploaded to the ESP32.
Test Code
from machine import Pin
import time
from ADXL345 import adxl345
scl = Pin(22)
sda = Pin(21)
bus = 0
snsr = adxl345(bus, scl, sda)
while True:
x,y,z = snsr.readXYZ()
print('x:',x,'y:',y,'z:',z,'uint:mg')
time.sleep(0.1)
Code Explanation
Set IIC pins, select IIC0,sda–>21, scl–>22,then assign the value to x, y and z. The shell shows the value of x,y and z,unit is mg.
Test Result
Connect the wires according to the experimental wiring diagram and power on. Click“Run current script”, the code starts executing, the shell will display the corresponding value of the three-axis acceleration in mg, as shown in the following figure, as shown below. Press “Ctrl+C”or click
“Stop/Restart backend”to exit the program.