ADXL345 accelerometer on I2C, on an Arduino Uno
An ADXL345 on A4 and A5: the sketch wakes it, reads its X, Y and Z registers over I2C with Wire, and prints the raw values. The whole build, an Arduino Uno and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Intermediate Runs in your browser. Free, and no account needed.
The parts retail for about $30. On Mokxi they're free.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// An ADXL345 accelerometer, read with nothing but Wire.
//
// ADXL345 SDA -> A4 SCL -> A5 VCC -> 5V GND -> GND CS -> 3.3V
//
// The chip answers at address 0x53. Writing 0x08 to its power register
// (0x2D) starts it measuring; then six bytes from 0x32 are X, Y and Z, each
// a 16-bit number, low byte first.
//
// Drag the board to tip it.
#include <Wire.h>
const int ADDRESS = 0x53;
void writeRegister(byte reg, byte value) {
Wire.beginTransmission(ADDRESS);
Wire.write(reg);
Wire.write(value);
Wire.endTransmission();
}
void setup() {
Serial.begin(9600);
Wire.begin();
writeRegister(0x2D, 0x08);
Serial.println("Mokxi Uno: ADXL345 on A4 and A5");
}
void loop() {
Wire.beginTransmission(ADDRESS);
Wire.write(0x32);
Wire.endTransmission();
Wire.requestFrom(ADDRESS, 6);
int axes[3];
for (int i = 0; i < 3; i++) {
byte low = Wire.read();
byte high = Wire.read();
axes[i] = (int)((high << 8) | low);
}
Serial.print("x ");
Serial.print(axes[0]);
Serial.print(" y ");
Serial.print(axes[1]);
Serial.print(" z ");
Serial.println(axes[2]);
delay(300);
}
Parts list
2 parts, plus the jumper wires. They retail for about $30; on Mokxi they're free.
How it is wired
4 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Arduino Uno R3 pin 5V; Accelerometer, ADXL345 pin VCC
- Ground: Arduino Uno R3 pin GND; Accelerometer, ADXL345 pin GND
- Arduino Uno R3 pin A4; Accelerometer, ADXL345 pin SDA
- Arduino Uno R3 pin A5; Accelerometer, ADXL345 pin SCL
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.