#include <Arduino.h>
#include <Wire.h>
#include <math.h>

#define ADXL345_ADDR 0x53   // GY-291 meist: SDO/GND -> 0x53

int16_t Ax, Ay, Az;

void WriteRegister(byte address, byte value) 
{
  Wire.beginTransmission(ADXL345_ADDR);
  Wire.write(address);
  Wire.write(value);
  Wire.endTransmission();
}

void ReadAcceleration() 
{
  Wire.beginTransmission(ADXL345_ADDR);
  Wire.write(0x32);                 // DATAX0
  Wire.endTransmission(false);
  Wire.requestFrom(ADXL345_ADDR, 6);
  Ax = Wire.read() | (Wire.read() << 8);
  Ay = Wire.read() | (Wire.read() << 8);
  Az = Wire.read() | (Wire.read() << 8);
}

float AT2Degree(int16_t dy, int16_t dx) 
{
  return atan2((float)dy, (float)dx) * 180.0 / PI;
}

void setup() 
{
  Serial.begin(115200);
  delay(333);
  Wire.begin();

  // ADXL345 einschalten
  WriteRegister(0x2D, 0x08);   // POWER_CTL: Measure = 1

  // +/- 2g, Full Resolution
  WriteRegister(0x31, 0x08);   // DATA_FORMAT
  
  Serial.println("ADXL345 gestartet");
}

void loop() 
{
  ReadAcceleration();
  float AngleXY = AT2Degree(Ay, Ax);
  float AngleXZ = AT2Degree(Az, Ax);
  float AngleYZ = AT2Degree(Az, Ay);

  Serial.print("X=");
  Serial.print(Ax);
  Serial.print(" Y=");
  Serial.print(Ay);
  Serial.print(" Z=");
  Serial.print(Az);
  Serial.print("   ");

  Serial.print("Winkel XY=");
  Serial.print(AngleXY, 3);
  Serial.print("deg");

  Serial.print(" XZ=");
  Serial.print(AngleXZ, 3);
  Serial.print("deg");

  Serial.print(" YZ=");
  Serial.print(AngleYZ, 3);
  Serial.print("deg");

  Serial.println();
  delay(500);
}