A motionless accelerometer commonly reports approximately one g, not zero. Rotate it slowly and that vector moves between its axes. Shake it and the same numbers now contain additional effects. This laboratory separates those observations before an Arduino program turns every three-axis vector into an apparently confident angle.
Use the exact Adafruit ADXL345 breakout, product 1231, with an original Arduino UNO Rev3/ATmega328P and Arduino AVR Boards 1.8.6. A breakout is a small board that exposes the sensor and adds power/interface components. We use its documented, level-shifted two-wire interface; a bare ADXL345 or an arbitrary module cannot inherit these 5 V wiring assumptions.
What a stationary accelerometer is telling you
An accelerometer senses the displacement of a small internal suspended structure and converts it into axis measurements. At rest on a table, the table’s support prevents free fall; the sensor reports a gravity-related support-force vector. It does not report zero merely because the board’s position is unchanged. Conversely, it is not a speedometer and does not know a travelled distance.
The symbol g here is an acceleration unit, not grams of mass. We use standard g=9.80665 m/sยฒ to express the nominal scale. Actual local gravity, sensor offsets, scale factors and axis alignment can differ. An axis with approximately 256 counts at rest is near one g under our nominal conversion, not proof of a calibrated instrument.
A coordinate frame defines the axes and sign directions used to describe the vector. Record the module’s marked X, Y and Z directions and which physical face is up. A fixed sensor-to-enclosure rotation changes the mapping to โforwardโ or โupโ in your project. Wiring A4 to SDA does not define a mechanical axis.
Exact module and power boundaries
- Adafruit ADXL345 product 1231, preferably its current STEMMA QT version with readable axis/connection labels. STEMMA QT is Adafruit’s compact connector family; this experiment uses the labelled header nets.
- Original UNO Rev3/ATmega328P, a data-capable Universal Serial Bus (USB) cable and the pinned Arduino AVR Boards 1.8.6 core.
- Four short wires, soldered headers and a nonconductive support that can hold several repeatable orientations without stressing the sensor.
- A voltmeter for the initial supply check and a serial console. No motor driver, battery, external supply, extra pullup or interrupt wire is required.
The bare sensor operates from 2.0โ3.6 V, with a separate interface supply limited relative to its own supply. A 5 V UNO therefore needs a compatible interface board. This exact Adafruit module has a 3.3 V regulator and level shifting on SDA/SCL; its manufacturer instructs a 5 V controller to use VIN=5 V. That does not make every auxiliary pin or a bare chip 5 V safe.
The module’s published support circuitry includes 10 kฮฉ pullups, a regulator and 10 ยตF/100 nF decoupling. These parts establish supply and idle bus levels; they are already fitted. An absolute voltage or mechanical-shock limit in a datasheet is a stress category, not a suggested bench test. Do not drop, strike or vigorously shake the board to see a larger number.
Confirm the actual module and chip markings before building. The manufacturer’s current QT design file reuses an ADXL343 component-library label even though product 1231 is documented as ADXL345. We use that file to understand support circuitry, not as proof of installed silicon. A common device ID cannot authenticate the part; a board actually marked as another sensor needs its own qualified review.
Connect the documented shifted bus

tricky-circuit-batch-006/images/uno-adxl345-gravity.svg)IยฒC, Inter-Integrated Circuit, is an addressable serial bus. SDA means serial data, and SCL serial clock. Connect UNO 5 VโVIN, GNDโGND, A4โSDA and A5โSCL. The extra SDA/SCL header pins on UNO Rev3 are the same bus nets, not another independent bus. The code uses the default seven-bit address 0x53; 0x introduces hexadecimal notation.
Leave 3Vo, CS, SDO/ALT ADDR and INT1/INT2 open. The module holds CS, chip select, in its default two-wire mode and the alternate-address input low for 0x53. SDO means serial data output in the alternative interface. INT1/INT2 are optional interrupt outputs. Their source flags can be read in registers without connecting those physical pins. Never tie these auxiliary pins to 5 V to make them โunused.โ
With power removed, verify the real header labels and breadboard rail continuity. Power only through UNO USB, then check VIN and common return before running the program. Keep the mount, cable strain and orientation stable. A loose wire and a moving mount can both change data, but they require different diagnoses.
Freshness and a complete vector matter
An analog-to-digital converter (ADC) produces numeric measurements of the sensing structure. In full-resolution ยฑ2 g mode, the nominal scale is approximately 3.9 mg per count; mg here means one-thousandth of g. The least significant bit (LSB) is the smallest code increment. Signed axis values use two’s complement, an encoding in which the top sign bit represents a negative weight. The program reconstructs each signed word explicitly.
We select an output data rate (ODR) of 25 Hz, meaning 25 new sensor vectors per nominal second, in normal-power mode. The actual sample clock belongs to the sensor. Host polling and serial output do not make it an exact 25 Hz timebase. Full resolution, ยฑ2 g, right-justified words and zeroed user-offset registers are explicit configuration choices; this is not a silent import of a previous program’s settings.
The current Analog Devices datasheet is revision G, May 2022. Its asynchronous-reading section warns about reading output registers while they update and recommends stream mode or synchronized data-ready reads. We choose FIFO, first in, first out, a queue that preserves complete vectors, in stream mode. It retains up to 32 samples and replaces older entries when full.
The driver checks the DATA_READY source bit and queue count, then retrieves all six X/Y/Z bytes in one burst. It never reads axes separately or treats an empty queue as three zeroes. A full queue, overrun indication or inconsistent ready/count state discards the whole partial analysis window and clears the queue. Overrun means that buffer history is uncertain; it does not reveal an exact number of missed samples. A second check catches an overrun that appears during the read.
There is an explicit 5 ยตs, five-microsecond, pause after a vector read before subsequent queue operations; one microsecond is one-millionth of a second. The manufacturer notes that ordinary IยฒC transaction spacing is already slow enough, but the pause makes our intended sequencing explicit. The program checks identity, rate, format, power, buffer mode and user offsets on each acquisition. Another program must not share ownership of those settings.
A gravity candidate is a conditional conclusion

The analysis collects 32 complete vectors, about 1.28 seconds at nominal 25 Hz. It requires each axis’s observed maximum-minus-minimum span to be no more than 0.08 g, and the magnitude of the mean vector to lie between 0.8 and 1.2 g. These are declared experiment-quality rules, not factory accuracy limits or a proof that the board was motionless.
Values near the selected range’s ends, raw counts of magnitude at least 480, produce CLIPPED. A variable window produces MOVING_OR_NOISY. A mean magnitude outside the screening interval produces MAGNITUDE_AMBIGUOUS. None prints an angle. When Y and Z together are too small to give a meaningful roll reference, ANGLE_SINGULAR also leaves angles unknown rather than displaying an arbitrary zero.
Only a surviving window becomes STATIC_GRAVITY_CANDIDATE. The formula uses roll=atan2(Y,Z) and pitch=atan2(โX,โ(Yยฒ+Zยฒ)); atan2 is a two-argument inverse tangent that preserves the correct quadrant. These are this program’s stated angle conventions. They should be interpreted as static inclination only when you independently know that the mount is still and gravity is the dominant stimulus.
A constant additional acceleration can pass a low-variation test. The synthetic vector (0.6,0,0.8) g has magnitude exactly one g but does not tell you which physical causes produced it. Gravity alone also supplies no yaw, rotation around the vertical direction: turning a level board like a compass needle can leave its gravity vector unchanged. Averaging cannot recover information that this sensor does not observe.
Complete raw-register program
Create a folder named gravity_lab containing an empty gravity_lab.ino and the full downloaded C++ file. Select UNO and Arduino AVR Boards 1.8.6, then compile the whole sketch folder before a real experiment. That future board-target build has not been performed here. The program uses only the core Wire two-wire bus and Serial console interfaces; no external sensor library is required.
The Arduino application programming interface (API), its callable software interface, provides the actual bus and timing calls. We set the bus to 100 kHz and request the core’s 25000 ยตs bus timeout with interface reset. Host tests verify the shared driver/controller against a fake bus; they do not establish physical Wire timing or guarantee recovery from every wiring fault.
Download the entire program (ZIP; file: tricky-circuit-batch-006/code/uno-adxl345-gravity.cpp). The exact same file, including its Arduino adapter and entry points, follows.
Complete C++ / Arduino program
/* Original UNO Rev3 / ATmega328P, Arduino AVR Boards 1.8.6.
Exact Adafruit ADXL345 PID1231. Keep beside an empty gravity_lab.ino
in a gravity_lab sketch folder. HOST_TEST omits the Arduino adapter only. */
#include <stdint.h>
#include <math.h>
const double G_PER_COUNT=0.0039; // Nominal scale, not this unit's calibration.
struct Bus {
virtual bool read(uint8_t reg,uint8_t *out,uint8_t length)=0;
virtual bool write(uint8_t reg,uint8_t value)=0;
virtual void pause_us(unsigned n)=0;
virtual ~Bus(){}
};
struct Frame {int16_t axis[3];uint8_t source_before,queued_before;};
enum SampleState {NO_SAMPLE,FRESH_SAMPLE,BUFFER_GAP,BUS_OR_CONFIG_FAULT,DATA_RANGE_FAULT};
class ADXL345 {
Bus &bus;
bool byte(uint8_t reg,uint8_t &out){return bus.read(reg,&out,1);}
public:
explicit ADXL345(Bus &b):bus(b){}
bool reset_buffer(){return bus.write(0x38,0)&&bus.write(0x38,0x80);}
bool guard(){
const uint8_t reg[]={0x00,0x2d,0x2c,0x31,0x38,0x2e,0x1e,0x1f,0x20};
const uint8_t expected[]={0xe5,0x08,0x08,0x08,0x80,0,0,0,0};
for(uint8_t i=0;i<sizeof(reg);i++){uint8_t v;if(!byte(reg[i],v)||v!=expected[i])return false;}
return true;
}
bool begin(){
uint8_t id;if(!byte(0,id)||id!=0xe5)return false;
if(!bus.write(0x2d,0)||!bus.write(0x2e,0))return false;
if(!bus.write(0x31,0x08)||!bus.write(0x2c,0x08))return false;
for(uint8_t reg=0x1e;reg<=0x20;reg++)if(!bus.write(reg,0))return false;
return reset_buffer()&&bus.write(0x2d,0x08)&&guard();
}
SampleState take(Frame &frame){
if(!guard())return BUS_OR_CONFIG_FAULT;
uint8_t source,status;
if(!byte(0x30,source)||!byte(0x39,status))return BUS_OR_CONFIG_FAULT;
uint8_t count=status&0x3f;
if(count>32)return DATA_RANGE_FAULT;
if((source&1)||count==32){return reset_buffer()?BUFFER_GAP:BUS_OR_CONFIG_FAULT;}
if(count==0)return NO_SAMPLE;
if(!(source&0x80)){return reset_buffer()?BUFFER_GAP:BUS_OR_CONFIG_FAULT;}
uint8_t raw[6];if(!bus.read(0x32,raw,6))return BUS_OR_CONFIG_FAULT;
bus.pause_us(5);
uint8_t after;if(!byte(0x30,after)||!guard())return BUS_OR_CONFIG_FAULT;
if(after&1){return reset_buffer()?BUFFER_GAP:BUS_OR_CONFIG_FAULT;}
for(uint8_t i=0;i<3;i++){
uint16_t bits=uint16_t(raw[i*2])|(uint16_t(raw[i*2+1])<<8);
int32_t signed_value=(bits&0x8000)?int32_t(bits)-65536:int32_t(bits);
if(signed_value < -512 || signed_value > 511)return DATA_RANGE_FAULT;
frame.axis[i]=int16_t(signed_value);
}
frame.source_before=source;frame.queued_before=count;
return FRESH_SAMPLE;
}
};
enum ResultKind {CLIPPED_WINDOW,MOVING_WINDOW,MAGNITUDE_AMBIGUOUS,ANGLE_SINGULAR,STATIC_GRAVITY_CANDIDATE};
struct Result {ResultKind kind;double mean_g[3],norm_g,roll_deg,pitch_deg;bool angles_valid;};
class Window {
int32_t sum[3];int16_t lo[3],hi[3];uint8_t n;bool clipped;
public:
Window(){clear();}
void clear(){n=0;clipped=false;for(uint8_t i=0;i<3;i++){sum[i]=0;lo[i]=511;hi[i]=-512;}}
uint8_t count()const{return n;}
bool add(const Frame &f){
for(uint8_t i=0;i<3;i++){
int16_t x=f.axis[i];sum[i]+=x;if(x<lo[i])lo[i]=x;if(x>hi[i])hi[i]=x;
if(x<=-480||x>=480)clipped=true;
}
return ++n==32;
}
Result evaluate()const{
Result r={MAGNITUDE_AMBIGUOUS,{0,0,0},0,0,0,false};
if(n!=32)return r;
bool moving=false;
for(uint8_t i=0;i<3;i++){r.mean_g[i]=double(sum[i])/32*G_PER_COUNT;if((hi[i]-lo[i])*G_PER_COUNT>0.08)moving=true;}
double x=r.mean_g[0],y=r.mean_g[1],z=r.mean_g[2];
r.norm_g=sqrt(x*x+y*y+z*z);
if(clipped){r.kind=CLIPPED_WINDOW;return r;}
if(moving){r.kind=MOVING_WINDOW;return r;}
if(r.norm_g<0.8||r.norm_g>1.2)return r;
double yz=sqrt(y*y+z*z);
if(yz<0.1){r.kind=ANGLE_SINGULAR;return r;}
r.roll_deg=atan2(y,z)*180.0/3.14159265358979323846;
r.pitch_deg=atan2(-x,yz)*180.0/3.14159265358979323846;
r.angles_valid=true;r.kind=STATIC_GRAVITY_CANDIDATE;return r;
}
};
enum Event {WAITING,COLLECTING,WINDOW_COMPLETE,GAP_DISCARDED,STOP_FAULT};
class Experiment {
ADXL345 sensor;Window window;uint32_t last_poll,last_sample;bool have_poll,stopped;
public:
Result last;
explicit Experiment(Bus &bus):sensor(bus),last_poll(0),last_sample(0),have_poll(false),stopped(false){}
bool begin(){window.clear();have_poll=false;stopped=!sensor.begin();return !stopped;}
uint8_t samples()const{return window.count();}
Event step(uint32_t now_ms){
if(stopped)return STOP_FAULT;
if(have_poll&&uint32_t(now_ms-last_poll)>120){
window.clear();last_poll=last_sample=now_ms;
if(!sensor.reset_buffer()){stopped=true;return STOP_FAULT;}
return GAP_DISCARDED;
}
if(!have_poll)last_sample=now_ms;
last_poll=now_ms;have_poll=true;
Frame frame;SampleState state=sensor.take(frame);
if(state==NO_SAMPLE){
if(uint32_t(now_ms-last_sample)>500){window.clear();stopped=true;return STOP_FAULT;}
return WAITING;
}
if(state==BUFFER_GAP){window.clear();last_sample=now_ms;return GAP_DISCARDED;}
if(state!=FRESH_SAMPLE){window.clear();stopped=true;return STOP_FAULT;}
last_sample=now_ms;
if(!window.add(frame))return COLLECTING;
last=window.evaluate();window.clear();return WINDOW_COMPLETE;
}
};
#ifndef HOST_TEST
#include <Arduino.h>
#include <Wire.h>
class WireBus:public Bus {
public:
bool read(uint8_t reg,uint8_t *out,uint8_t length){
Wire.clearWireTimeoutFlag();Wire.beginTransmission(0x53);Wire.write(reg);
if(Wire.endTransmission(false)!=0||Wire.getWireTimeoutFlag())return false;
uint8_t got=Wire.requestFrom(uint8_t(0x53),length,uint8_t(true));
if(got!=length||Wire.getWireTimeoutFlag()){while(Wire.available())Wire.read();return false;}
for(uint8_t i=0;i<length;i++){if(!Wire.available())return false;out[i]=Wire.read();}
return true;
}
bool write(uint8_t reg,uint8_t value){
Wire.clearWireTimeoutFlag();Wire.beginTransmission(0x53);Wire.write(reg);Wire.write(value);
return Wire.endTransmission(true)==0&&!Wire.getWireTimeoutFlag();
}
void pause_us(unsigned n){delayMicroseconds(n);}
};
WireBus bus;Experiment experiment(bus);
void setup(){
Serial.begin(115200);Wire.begin();Wire.setClock(100000);Wire.setWireTimeout(25000,true);
if(!experiment.begin())Serial.println(F("INITIALIZATION_FAULT: no current acceleration or angle"));
else Serial.println(F("ADXL345 25Hz/fullres2g/stream;32sample windows; no yaw or velocity."));
}
void loop(){
static bool reported_stop=false;
Event e=experiment.step(millis());
if(e==STOP_FAULT){if(!reported_stop)Serial.println(F("FAULT_STOP: current acceleration/angle=unknown; inspect then restart"));reported_stop=true;delay(20);return;}
if(e==GAP_DISCARDED)Serial.println(F("GAP_DISCARDED: full/overrun/host gap; window and FIFO cleared; no drop count known"));
if(e==WINDOW_COMPLETE){
const Result &r=experiment.last;
Serial.print(F("WINDOW,readout_ms="));Serial.print(millis());Serial.print(F(",kind="));
switch(r.kind){
case CLIPPED_WINDOW:Serial.print(F("CLIPPED"));break;
case MOVING_WINDOW:Serial.print(F("MOVING_OR_NOISY"));break;
case MAGNITUDE_AMBIGUOUS:Serial.print(F("MAGNITUDE_AMBIGUOUS"));break;
case ANGLE_SINGULAR:Serial.print(F("ANGLE_SINGULAR"));break;
default:Serial.print(F("STATIC_GRAVITY_CANDIDATE"));break;
}
Serial.print(F(",mean_g="));for(uint8_t i=0;i<3;i++){Serial.print(r.mean_g[i],4);Serial.print(i==2?';':',');}
Serial.print(F("norm_g="));Serial.print(r.norm_g,4);
if(r.angles_valid){Serial.print(F(",roll_deg="));Serial.print(r.roll_deg,2);Serial.print(F(",pitch_deg="));Serial.println(r.pitch_deg,2);}
else Serial.println(F(",angles=unknown"));
}
delay(1);
}
#endif
Open the console at 115200 baud, the serial signalling rate. Readout rows label values as mean_g, norm_g, roll_deg and pitch_deg. Multiply a nominal g reading by 9.80665 to express it in m/sยฒ, without claiming that the conversion corrects the sensor’s scale error. The reported readout_ms is the host readout time, not a hardware acquisition timestamp for every buffered entry.
A host polling gap greater than 120 ms clears the partial window and queue. More than 500 ms of continued polling with no fresh vector produces a fault stop. An ordinary short wrap of the millisecond counter is handled by unsigned subtraction; a pause hiding complete wraps cannot be reconstructed. After uncertain debugger history, restart and repeat the stationary sequence.
Configuration, identity, transfer-length or data-range faults clear the partial window and stop. Current acceleration and angles are explicitly unknown; an old angle is never reprinted as a new result. Buffer gaps may recover by collecting a whole new window. Fault stops require inspection and an explicit restart. Do not confuse the screen’s last remaining old line with an ongoing stream of current data.
Stationary poses, then a limited movement comparison
- Record module/chip marking, firmware/core version, supply and axis directions. Start with the board supported on a flat nonconductive fixture. After a pose change, ignore a mixed initial window and wait for a new complete stationary window.
- Record at least two windows with each of X, Y and Z pointing up, then down. Compare the signed dominant axis and vector magnitude. Do not assume exact ยฑ256 counts or exactly zero on the other axes. Some X-up poses intentionally reach our roll singularity refusal.
- Rotate slowly to a modest inclined support, stop moving and compare the next complete stationary windows. Record which physical rotation corresponds to each code angle. A measured reference angle is needed before discussing real angle error.
- Keep the board level and rotate it gently around vertical, then stop. Test whether the gravity-based angle distinguishes your heading change. No promised trace is supplied; record what the actual mount and environment produce.
- While holding the board securely close to the table, make a small gentle movement without impact, then stop. Inspect the moving/noisy or magnitude states and subsequent recovery. Do not drop the board to produce a zero-g interval or bang it into clipping.
- Use the host tests to reproduce missing data, corrupt words, changed configuration, full FIFO and a long host pause. A debugger pause is not a calibrated sampling experiment, and a wire short is not an appropriate fault injector.
Blank observation sheet (ZIP; file: tricky-circuit-batch-006/code/uno-adxl345-gravity-observations-blank.csv) contains no measurements. Keep pose, mount, mean counts/units, state and independent reference separate. A useful result can be a rejected window or a reproducible offset; do not discard it to make all poses look ideal.
Calibration is not โsubtract one stationary vectorโ
A six-orientation check can estimate each axis’s offset and scale under controlled assumptions. If r+ and rโ are that axis’s mean counts when it sees approximately +1 g and โ1 g, an offset estimate is b=(r++rโ)/2 and a scale estimate is s=(r+โrโ)/2 counts per g. Then a corrected estimate is (rawโb)/s. The quality still depends on alignment, stillness, temperature and known reference conditions.
The supplied logger deliberately leaves these coefficients unapplied and zeroes only the chip’s user-offset registers at initialization. It reports a nominal scale so actual owner measurements can be reviewed first. Subtracting all three values from one flat stationary pose would also remove the gravity component you wanted to study. Neither that trick nor numerical integration turns this setup into a reliable velocity or position instrument.
Challenge: a stable vector has magnitude one g. Have we proved the angle?
No. Stability and magnitude only pass the stated screening rules. A steady acceleration or mounting/scale error can still change the result. Confirm that the fixture is stationary, know the frame, compare against an independent inclination reference and keep the label โcandidateโ until those assumptions are justified. The norm alone cannot determine physical cause or heading.
Sources, errata and verification limits
The host tests compile and execute the delivered driver, state controller and calculations with injected register behavior. They cover signed words, stream/full/overrun cases, changed settings, unknown data, gap boundaries, ordinary counter wrap and misleading steady vectors. They do not compile the AVR adapter, run an UNO, measure bus margins or calibrate an ADXL345. The electronics lessons provide the basic measurement background.
- Analog Devices ADXL345 datasheet, revision G, May 2022: current PDF, especially signed format, FIFO, overrun and asynchronous data readings.
- Manufacturer product documentation and AN-1077 quick-start guidance.
- AN-1057 inclination assumptions; manufacturer FAQ correcting a historical bus-traffic gate drawing. That correction concerns an alternative interface drawing, not permission to ignore current update-coherency guidance.
- Exact Adafruit product 1231, module pinouts and voltage levels and support-circuit design files.
- UNO Rev3 hardware and pinned core Wire API.



