Skip to content

Instantly share code, notes, and snippets.

@penpencool
Last active February 28, 2024 04:29
Show Gist options
  • Select an option

  • Save penpencool/86832183f75f1a67b759a0ae6537ae89 to your computer and use it in GitHub Desktop.

Select an option

Save penpencool/86832183f75f1a67b759a0ae6537ae89 to your computer and use it in GitHub Desktop.
#include <Wire.h>
#define ADXL345_ADDRESS (0x53) // ADXL345 accelerometer address
#define ITG3205_ADDRESS (0x68) // ITG3205 gyroscope address
#define HMC5883L_ADDRESS (0x1E) // HMC5883L magnetometer address
void setup() {
Serial.begin(9600);
Wire.begin();
// Initialize ADXL345
writeTo(ADXL345_ADDRESS, 0x2D, 0); // Power register
writeTo(ADXL345_ADDRESS, 0x2D, 16); // Measure mode
// Initialize ITG3205
writeTo(ITG3205_ADDRESS, 0x3E, 0); // Power register
writeTo(ITG3205_ADDRESS, 0x15, 0x07); // Full-scale range and DLPF setting
// Initialize HMC5883L
writeTo(HMC5883L_ADDRESS, 0x00, 0x18); // Configuration register A
writeTo(HMC5883L_ADDRESS, 0x01, 0x20); // Configuration register B
writeTo(HMC5883L_ADDRESS, 0x02, 0x00); // Mode register
}
void loop() {
// Read accelerometer data
int16_t ax, ay, az;
readFrom(ADXL345_ADDRESS, 0x32, 6, &ax);
Serial.print("Accelerometer: ");
Serial.print("X = "); Serial.print(ax); Serial.print(" | ");
Serial.print("Y = "); Serial.print(ay); Serial.print(" | ");
Serial.print("Z = "); Serial.println(az);
// Read gyroscope data
int16_t gx, gy, gz;
readFrom(ITG3205_ADDRESS, 0x1D, 6, &gx);
Serial.print("Gyroscope: ");
Serial.print("X = "); Serial.print(gx); Serial.print(" | ");
Serial.print("Y = "); Serial.print(gy); Serial.print(" | ");
Serial.print("Z = "); Serial.println(gz);
// Read magnetometer data
int16_t mx, my, mz;
readFrom(HMC5883L_ADDRESS, 0x03, 6, &mx);
Serial.print("Magnetometer: ");
Serial.print("X = "); Serial.print(mx); Serial.print(" | ");
Serial.print("Y = "); Serial.print(my); Serial.print(" | ");
Serial.print("Z = "); Serial.println(mz);
delay(1000); // Delay for 1 second
}
void writeTo(int device, byte address, byte val) {
Wire.beginTransmission(device);
Wire.write(address);
Wire.write(val);
Wire.endTransmission();
}
void readFrom(int device, byte address, int num, int *values) {
Wire.beginTransmission(device);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(device, num);
int i = 0;
while (Wire.available() && i < num) {
values[i] = Wire.read() | (Wire.read() << 8);
i++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment