Guide no. 94
Wemos D1 mini and the ADXL345 accelerometer on the GY-291 module: tilt worked out from gravity, a bubble level on the OLED display, tap and free fall with the interrupt, the values in the Serial Plotter.
By Ada Intelisano · informaticait.it technical team
- At rest, the ADXL345 feels only gravity: the way 1 g splits between X, Y and Z gives the tilt (Analog Devices, note AN-1057).
- Everything at 3.3 V from the 3V3 pin of the D1 mini: sensor and display on D6 (SDA) and D5 (SCL), INT1 on D7.
- On the display, a bubble level with the two angles; the turn-around test corrects the zero error of the sensor and of the mounting.
- The sensor recognizes a tap and a free fall by itself and signals them by raising INT1; the angles go to the Serial Plotter.
An accelerometer sitting still on the table feels only one thing: gravity. Tilt it, and that push is shared out among its three axes; from the way it is shared you can tell how many degrees it is tilted. That is how we use it in this guide: the ADXL345, a D1 mini and a small display become a bubble level. Then we teach it to feel a tap and to notice when it falls, using the interrupt. Everything sits on a breadboard, which serves as the base of the level.
1The parts
| Part | How many | What it's for |
|---|---|---|
| Wemos D1 mini (ESP8266, CH340 USB chip), with the headers to solder | 1 | the board |
| GY-291 module with the ADXL345 accelerometer by Analog Devices, with the 8-pin header to solder | 1 | the sensor |
| 0.96" OLED display, 128 × 64 pixels, I²C, with the header already soldered | 1 | the level |
| Breadboard, 830 points | 1 | the base everything sits on |
| Jumper wires, male-to-male, 20 cm | 14 | the connections |
| Cable, USB-A to micro USB | 1 | uploading and power |
You also need a computer and a soldering iron. For the fall test, a cushion.
2How tilt is measured
- Lying flat, chip up, the ADXL345 reads Z = 1 g and zero on X and Y: the Analog Devices datasheet shows it. For an accelerometer at rest, gravity is a push of 1 g upwards.
- Tilt it, and that g splits: the X axis gets 1 g · sin θ, Z keeps 1 g · cos θ. From the three readings the angle is worked out with the formula in Analog Devices application note AN-1057, θ = arctan(X ÷ √(Y² + Z²)), and the Y angle the same way.
- Why three axes and not just one? With a single axis, near 90° the reading changes less and less and the measurement loses sensitivity. Using the ratio between the axes, the same note explains, the sensitivity stays roughly constant. And if the axes have the same sensitivity, much of their error cancels out in the ratio.
- The level works while it is still. If you move it, the sensor adds your movement to gravity and the angle goes off: note AN-1057 starts from the very assumption that the only acceleration is gravity.
3The GY-291 module
- The ADXL345 chip works from 2.0 to 3.6 V and no pin may go above 3.9 V. According to our product page the module has a regulator and can be powered from 3.3 to 5 V. We power it from the 3V3 pin of the D1 mini: that way every pin stays at 3.3 V, however the module is built.
- The product page also says that the I²C lines already have 4.7 kΩ pull-up resistors (guide no. 20). In our photos you can see three resistors marked 472, that is 4.7 kΩ. Check on your module.
- CS goes to 3V3 and SDO to ground. The datasheet is clear: inside the chip there are no resistors to hold them at a level, so in I²C mode both must be connected. With SDO to ground the address is 0x53; with SDO high it would be 0x1D.
- INT1 and INT2 are push-pull outputs, high when there is an alert: they go straight to a pin of the board, with no resistors. Here we only use INT1.
4Solder the headers
- On the D1 mini, solder the two 8-pin male headers with the pins pointing down; the female headers aren't needed here. The trick from guide no. 9: push the headers into the breadboard, rest the board on top and solder, so they stay straight.
- Do the same on the GY-291 with the 8-pin header: the black plastic under the module, on the side without components, the long pins in the breadboard, the solder joints on the chip side. That makes 24 joints in all; guide no. 70 explains how to make a good one.
- The display comes with the header already soldered, the pins sticking out of the back: it goes into the breadboard glass side up. That's how our photos show it; if yours came with a loose header, solder it the same way round.
- A header soldered crooked makes the level start out already tilted. The test in step 10 corrects this too, but it's better to solder the module nice and flat.
5Build the circuit
- Unplug the USB cable while you connect the wires.
- The D1 mini goes on the left, with the USB socket off the breadboard: its pins go into rows b and i, columns 3 to 10. Column 3 holds 3V3 (top) and 5V (bottom). Each pin has one free hole left: in row a for the top ones, in row j for the bottom ones.
- The GY-291 goes in with its pins in row e, columns 16 to 23, chip up: SCL in 16, GND in 23. The body of the module hangs over the center channel.
- The display also goes into row e, columns 29 to 32 (GND in 29, SDA in 32), glass up and with its body toward you.
- The + and − side rails of this breadboard are split in the middle: we only use the left half.
| Wire | From | To |
|---|---|---|
| red | a3 (3V3) | top + rail, column 3 |
| black | j4 (G) | bottom − rail, column 4 |
| black | bottom − rail, column 14 | top − rail, column 14 |
| yellow | a7 (D5) | a16 (SCL of the GY-291) |
| blue | a6 (D6) | a17 (SDA of the GY-291) |
| green | a5 (D7) | a20 (INT1 of the GY-291) |
| black | a18 (SDO) and a23 (GND) | top − rail, same columns |
| red | a21 (CS) and a22 (VCC) | top + rail, same columns |
| yellow | c16 | c31 (SCL of the display) |
| blue | b17 | b32 (SDA of the display) |
| black | a29 (GND of the display) | top − rail, column 29 |
| red | a30 (VCC of the display) | top + rail, column 30 |
Wire.begin(D6, D5). D7 is fine for INT1: D3, D4 and D8 decide how the board starts up (guide no. 9), and D0 doesn't take interrupts.6Get the computer ready
- Arduino IDE 2, the driver for the CH340 chip, the ESP8266 package and the LOLIN(WEMOS) D1 R2 & mini board: follow guide no. 9, chapters 3 and 4, including the first test of the board on its own.
- In the Library Manager install Adafruit ADXL345 and Adafruit SSD1306. When it offers the libraries they need (Adafruit Unified Sensor, Adafruit BusIO, Adafruit GFX Library), install them all. We compiled with Adafruit ADXL345 1.3.4 and SSD1306 2.5.17.
7The first test: numbers in the plotter
Before the level, a short sketch to see what the sensor measures. Twenty times a second it sends the three accelerations to the computer, in m/s².
// First test of the ADXL345 accelerometer (GY-291 module) with the Wemos D1 mini. // Twenty times a second it prints the three accelerations, in m/s², for the Serial Plotter. // Wiring: SDA -> D6, SCL -> D5, module powered from 3V3, SDO to GND (address 0x53). #include <Arduino.h> #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_ADXL345_U.h> Adafruit_ADXL345_Unified accel(345); // the number is just a name for the sensor void setup() { Serial.begin(115200); Wire.begin(D6, D5); // SDA on D6, SCL on D5 if (!accel.begin(0x53)) { // 0x53: the address with SDO connected to GND Serial.println("ADXL345 not found: check the wiring"); while (true) delay(1000); } accel.setRange(ADXL345_RANGE_16_G); // up to 16 g, still 4 mg per step accel.setDataRate(ADXL345_DATARATE_100_HZ); } void loop() { sensors_event_t reading; accel.getEvent(&reading); // the three accelerations in m/s² Serial.print("x:"); // "name:value" gives the line its name Serial.print(reading.acceleration.x); Serial.print(",y:"); Serial.print(reading.acceleration.y); Serial.print(",z:"); Serial.println(reading.acceleration.z); delay(50); }
- The ±16 g range costs no precision: the library turns on full resolution, and in that mode the step stays at about 4 mg in every range, the datasheet says. The highest range also leaves room for knocks.
- Upload the sketch, then open the Serial Plotter with the button at the top right of the IDE, at 115200 baud. The
x:before the number gives the line its name.
- “ADXL345 not found”: SDA and SCL swapped (yellow and blue), CS or SDO not connected, or the module isn't getting 3.3 V.
- x goes down when you lift the left end: your module is mounted the other way round. In the level sketch you fix this with
DIR_XandDIR_Y. - A tap on the table barely shows up: the sketch reads twenty times a second and a sharp knock can fall between two readings. Taps are the interrupt's job, in step 11.
8The level
Now the real sketch: angles, the bubble on the display, tap and fall. The first lines hold the values you can change.
// The electronic spirit level: Wemos D1 mini, ADXL345 accelerometer (GY-291) and OLED display. // It works out the tilt on two axes from gravity, draws a bubble level and, with the // INT1 interrupt, recognizes a tap and a free fall. // Wiring: SDA -> D6, SCL -> D5, INT1 -> D7; modules powered from 3V3. #include <Arduino.h> #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_ADXL345_U.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> const float ZERO_X = 0.0; // corrections in degrees, from the turn-around test const float ZERO_Y = 0.0; const int DIR_X = -1; // the GY-291 X points left: bubble the other way const int DIR_Y = 1; // Y points toward you const float PIXELS_PER_DEG = 3.0; // one degree moves the bubble 3 pixels const float SMOOTH = 0.2; // the smaller it is, the calmer (and slower) the bubble const float LEVEL_TOL = 0.5; // under half a degree on both axes: "level" Adafruit_ADXL345_Unified accel(345); Adafruit_SSD1306 display(128, 64, &Wire, -1); volatile bool alert = false; // set to true by the interrupt float angleX = 0, angleY = 0; int taps = 0, falls = 0; String message = ""; unsigned long messageEnd = 0; void IRAM_ATTR onInt1() { // runs when INT1 goes high: it only raises a flag alert = true; } void prepareInterrupts() { accel.writeRegister(ADXL345_REG_INT_ENABLE, 0); // first, everything off accel.writeRegister(ADXL345_REG_THRESH_TAP, 0x38); // tap: above 3.5 g (62.5 mg x 56) accel.writeRegister(ADXL345_REG_DUR, 0x20); // for less than 20 ms (625 µs x 32) accel.writeRegister(ADXL345_REG_TAP_AXES, 0x07); // on all three axes accel.writeRegister(ADXL345_REG_THRESH_FF, 0x07); // fall: below 0.44 g (62.5 x 7) accel.writeRegister(ADXL345_REG_TIME_FF, 0x14); // for at least 100 ms (5 ms x 20) accel.writeRegister(ADXL345_REG_INT_MAP, 0); // all the alerts on the INT1 pin accel.writeRegister(ADXL345_REG_INT_ENABLE, 0x44); // tap (0x40) and fall (0x04) } void printAt(int x, int y, int size, String text) { display.setTextSize(size); display.setCursor(x, y); display.print(text); } String withSign(float a) { // +1.2 or -0.4: always with the sign return (a >= 0 ? "+" : "") + String(a, 1); } void showMessage(String text) { // big text for a second and a half message = text; messageEnd = millis() + 1500; } void drawScreen() { display.clearDisplay(); if (millis() < messageEnd) { printAt((128 - message.length() * 12) / 2, 12, 2, message); printAt(10, 44, 1, "taps " + String(taps) + " falls " + String(falls)); } else { display.drawCircle(31, 32, 30, SSD1306_WHITE); // the glass of the level display.drawCircle(31, 32, 7, SSD1306_WHITE); // the center circle display.drawFastHLine(1, 32, 10, SSD1306_WHITE); // four tick marks display.drawFastHLine(52, 32, 10, SSD1306_WHITE); display.drawFastVLine(31, 2, 10, SSD1306_WHITE); display.drawFastVLine(31, 53, 10, SSD1306_WHITE); float dx = constrain(DIR_X * angleX * PIXELS_PER_DEG, -24.0f, 24.0f); float dy = constrain(DIR_Y * angleY * PIXELS_PER_DEG, -24.0f, 24.0f); display.fillCircle(31 + (int)dx, 32 + (int)dy, 5, SSD1306_WHITE); // the bubble printAt(66, 0, 1, "X (deg)"); printAt(66, 10, 2, withSign(angleX)); printAt(66, 30, 1, "Y (deg)"); printAt(66, 40, 2, withSign(angleY)); if (fabs(angleX) < LEVEL_TOL && fabs(angleY) < LEVEL_TOL) { printAt(66, 56, 1, "level"); } } display.display(); // sends the screen to the display } void setup() { Serial.begin(115200); Wire.begin(D6, D5); // SDA on D6, SCL on D5 display.begin(SSD1306_SWITCHCAPVCC, 0x3C); display.setTextColor(SSD1306_WHITE); if (!accel.begin(0x53)) { // 0x53: the address with SDO connected to GND Serial.println("ADXL345 not found: check the wiring"); display.clearDisplay(); printAt(0, 0, 1, "ADXL345 not found"); display.display(); while (true) delay(1000); } accel.setRange(ADXL345_RANGE_16_G); // up to 16 g, still 4 mg per step accel.setDataRate(ADXL345_DATARATE_100_HZ); prepareInterrupts(); pinMode(D7, INPUT); attachInterrupt(digitalPinToInterrupt(D7), onInt1, RISING); accel.readRegister(ADXL345_REG_INT_SOURCE); // clears any alerts left pending } void loop() { sensors_event_t m; accel.getEvent(&m); // the three accelerations in m/s² float x = m.acceleration.x, y = m.acceleration.y, z = m.acceleration.z; // angles from the horizontal: Analog Devices AN-1057, equations 11 and 12 float ax = degrees(atan2(x, sqrt(y * y + z * z))) - ZERO_X; float ay = degrees(atan2(y, sqrt(x * x + z * z))) - ZERO_Y; angleX += SMOOTH * (ax - angleX); // one step toward the new value angleY += SMOOTH * (ay - angleY); int event = 0; if (alert) { // the ADXL345 has raised INT1 alert = false; uint8_t source = accel.readRegister(ADXL345_REG_INT_SOURCE); // reading it clears INT1 if (source & 0x04) { falls++; event = -5; showMessage("FALL!"); } else if ((source & 0x40) && millis() > messageEnd) { taps++; event = 5; showMessage("TAP!"); } } drawScreen(); Serial.printf("angleX:%.2f,angleY:%.2f,event:%d\n", angleX, angleY, event); delay(20); }
9How the level works
- On every pass,
loop()reads the three accelerations and works out the two angles with equations 11 and 12 of note AN-1057.degrees()converts them from radians to degrees. - The readings jitter a little.
SMOOTHmoves the angle on the display only a fifth of the way toward the new value: the bubble calms down, but it responds a bit more slowly. - The bubble moves 3 pixels per degree, so it reaches the edge at 8° (our calculation: 24 pixels divided by 3). On the GY-291 the X axis
points left: if you lift the left end, the X angle becomes positive, and the bubble, which always moves toward the higher end, has to
go left. That is why
DIR_Xis -1. - “level” appears below half a degree on both axes: it is our own threshold, and you can change it in
LEVEL_TOL. - The computer receives the two angles and a third number,
event: it is 5 on the line of a tap, -5 on the line of a fall, 0 on all the others. In the Serial Plotter it shows up as a clear spike.
angleX and angleY.- Blank display: does your display answer at 0x3C? Some answer at 0x3D (guide no. 9). Also check VCC and GND in columns 29 and 30.
- The bubble runs the wrong way: change the sign of
DIR_XorDIR_Y. - It doesn't read zero when flat: that's normal, and the test in step 10 fixes it.
10The turn-around test: the zero
Freshly built, the level almost never reads zero on a perfectly flat surface. For the 0 g output of the X and Y axes the datasheet gives a value between -150 and +150 mg, that is up to about 8.6° (our calculation: the arcsine of 0.15). Analog Devices adds that soldering and mounting shift the zero, and recommends calibrating it after mounting. Then there is the header, which is never soldered perfectly flat.
- Set the level on a shelf or on the table and mark where it sits with masking tape. Wait for the numbers to settle and write down X and Y.
- Turn it half a turn in the same spot, with the USB socket at the other end, and write down X and Y again.
- For each axis, add the two readings and divide by 2: that is the error of the level. Enter it in
ZERO_XandZERO_Yand upload the sketch again. The difference divided by 2, on the other hand, is the true tilt of the shelf.
This is our own method, built on the same idea as the two-point calibration in note AN-1057: the error stays the same, the tilt changes sign, and the average of the two readings leaves only the error. It holds for small tilts, a few degrees.
11Tap and free fall with the interrupt
The ADXL345 can recognize a tap and a free fall on its own.
You set the thresholds in its registers, and when something happens it raises the INT1 pin. The prepareInterrupts() function
writes these values; the units are the ones in the datasheet.
| Register | Value | What it means |
|---|---|---|
| THRESH_TAP | 0x38 | tap threshold: 56 × 62.5 mg = 3.5 g |
| DUR | 0x20 | the tap must last less than 32 × 625 µs = 20 ms |
| TAP_AXES | 0x07 | taps count on X, Y and Z |
| THRESH_FF | 0x07 | fall threshold: 7 × 62.5 mg ≈ 0.44 g |
| TIME_FF | 0x14 | below the threshold for at least 20 × 5 ms = 100 ms |
| INT_MAP | 0x00 | all the alerts on the INT1 pin |
| INT_ENABLE | 0x44 | single tap (0x40) and free fall (0x04) turned on |
- For the fall, Analog Devices recommends a threshold between 300 and 600 mg and a time between 100 and 350 ms: we are inside both. For the tap it gives, as a starting point, a duration above 10 ms and a threshold above 3 g, and warns that every object responds in its own way: you will have to try a few values.
- The
onInt1()function starts by itself when INT1 goes high. The ESP8266 core wantsIRAM_ATTRin front of it; the function only raises a flag,alert, andloop()does the rest. loop()reads the INT_SOURCE register, which tells what happened. Reading it puts INT1 back at rest, ready for the next alert.
- The tap isn't counted: tap harder. You can lower the threshold, but with very low values, the datasheet says, the sensor also picks up the echoes of the knock.
- The fall isn't detected: the USB cable was pulling, or the drop was too short. After the test, check that the modules are still pushed in firmly.
- Nothing happens in either case: the green wire goes from a5 (D7) to a20 (INT1).
- Set
PIXELS_PER_DEGto 10: the bubble reaches the edge at 2.4° and the level gets finer. - Lower
SMOOTHto 0.05 and watch in the plotter how the response changes. - Turn on the double tap too (0x20 in INT_ENABLE): it needs the Latent and Window registers, and the datasheet suggests starting from above 20 ms and above 80 ms.
- at rest, an accelerometer measures gravity, and the way it splits between the axes gives you the tilt;
- with three axes, the AN-1057 formula stays sensitive at every angle;
- the zero is corrected with two readings and half a turn in between;
- the sensor recognizes taps and falls by itself and alerts the board through the interrupt.
Useful products
Other guides
- Resistor colour code and tolerances
- N-channel and P-channel MOSFETs
- Bipolar transistor (BJT) or MOSFET?
- Relays: how to drive them and how much current they draw
- THT and SMD/SMT components
- XIAO board pinouts
- LEDs: forward voltage and series resistor
- The multimeter: measuring voltage and current
- Wemos D1 mini: first steps
- MOSFET module with Arduino and ESP32
- Relay module with Arduino and ESP32
- 3D printing filaments: PLA, PETG and fibre-filled versions
- Analog and digital: the differences
- ADS1115: 16-bit converter with Arduino and ESP32
- From bits to real values: converting sensor readings
- DS3231 RTC clock with Arduino and ESP32
- Linear or switching regulator: which one to choose
- Step-down, step-up and buck-boost: choosing the right module
- Voltage divider: reading voltages higher than 5 V or 3.3 V
- Pull-up, pull-down and bounce: wiring a button properly
- 3.3 V and 5 V logic levels: getting an ESP32 and an Arduino to talk
- The I²C bus: addresses, pull-ups and the scanner
- Lithium batteries: voltages, charging and protection
- ESP32 power consumption and deep sleep: how long the battery lasts
- Temperature sensors compared
- ESP32: which pins to use and which to avoid
- Getting started with the ESP32 in Arduino IDE 2 and PlatformIO
- SSD1306 OLED display and 16×2 I²C LCD with Arduino and ESP32
- PIR motion sensor and HC-SR04 ultrasonic sensor
- Date and time from the Internet with the ESP32: NTP, Italian time zone and daylight saving time
- MicroSD data logger: saving measurements to CSV
- Solar-powered ESP32: panel, charger and the numbers for Italy
- Web server on the ESP32: control a relay from your phone
- Your first LED: wire it up and make it blink
- The button: let Arduino decide
- The potentiometer: turn a knob and read its value
- Soft light: adjusting the brightness of an LED
- The buzzer: playing notes and melodies
- The traffic light: three LEDs in sequence
- The thermometer: reading the temperature with the TMP36
- The servo motor: moving an arm with Arduino
- The night light: the photoresistor and your first decision
- The relay: switching on a light bulb with Arduino
- The LCD display: making Arduino write
- The electronic dice: your first complete project
- The RGB LED: every color from three lights
- The joystick: two-axis control with a shield
- The LED ring: twelve colors from a single pin
- The DC motor: driving it with a MOSFET
- Soil moisture: the plant that asks for water
- The stepper motor: turn exactly as far as you want
- The parking sensor: faster and faster beeps
- The 7-segment display: big, bright numbers
- Automatic watering: the plant that waters itself
- The keypad: a lock with a secret code
- Networked weather station: values and chart on your phone
- A Telegram bot on the ESP32: your home from your phone
- MQTT with the ESP32: the language of connected devices
- Updating the ESP32 over Wi-Fi (OTA)
- ESP-NOW: two ESP32 boards talking without a router
- WebSocket with the ESP32: the LED that follows the slider
- Readings on a Google sheet, with deep sleep
- WiFiManager: choose the Wi-Fi from your phone
- Bluetooth LE with the ESP32: the phone without a network
- The camera in your browser with the ESP32-S3
- A portable Bluetooth speaker you build yourself
- Bluetooth desktop speakers, 2 × 20 W
- Stereo MP3 player with two buttons
- The shelf that plays music: a Visaton exciter
- How to solder well
- How much does it draw? Current and power with the INA219
- Load-cell scale with the HX711
- CO2 traffic light: when to open the windows
- RFID card door opener
- GPS: track logger on microSD
- LoRa: how far does it go? A range test with two boards
- Battery weather sign with an e-paper display
- Web radio with an ESP32 and an I2S amplifier
- Getting started with the Raspberry Pi Pico 2 in MicroPython
- Your first amplifier: the LM386 and a speaker
- Talking Arduino: the DFR0760 speech synthesis module
- The spectrum of your music on an LED matrix
- Drawing with 64 LEDs: the 8×8 matrix with the MAX7219
- A real voltage: the 12-bit MCP4725 DAC
- Your own macro keyboard: four NeoKey keys and the QT Py RP2040
- The Maqueen robot with the micro:bit: follow the line, avoid obstacles
- A two-way speaker with a Visaton woofer, tweeter and crossover
- A 120-LED NeoPixel strip, powered the right way
- A linear actuator to open a lid
- The heartbeat on Arduino: an ECG with the AD8232
- The infrared remote: controlling Arduino from the couch